← Questions

Backpropagate through sort and divide by the median

0
OpenAICodingLast asked Feb 2019

A coding interview question asked in OpenAI's agentic coding (beta) round, last asked Feb 2019. It tests autograd, gradients and numpy.

A function sorts a vector in ascending order and divides every sorted element by the median of the input:

def f(x):
    return np.sort(x) / np.median(x)

For example, f([3, 2, 1]) = [0.5, 1.0, 1.5]. Given the input x and the upstream gradient v = dL/dy for y = f(x), return dL/dx, written by hand rather than with an autodiff library.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • grad(x: list[float], v: list[float]) -> list[float] — same length as x, in the original order of x.

Example

grad([3.0, 2.0, 1.0], [1.0, 1.0, 1.0])  -> [0.5, -1.0, 0.5]
    # each element gets v at its sorted slot / m = 1/2;
    # the median 2 also gets -(1*1 + 1*2 + 1*3) / 2^2 = -1.5, so 0.5 - 1.5 = -1

grad([4.0, 1.0, 2.0], [1.0, 0.0, 2.0])  -> [1.0, 0.5, -2.25]
    # sorted [1, 2, 4], m = 2: direct parts 2/2, 1/2, 0/2;
    # the median 2 also gets -(1*1 + 0*2 + 2*4) / 4 = -2.25

Constraints

  • n is odd and the median is unique, so the median is one element of x.
  • Answers are compared with a small floating-point tolerance.
  • Roughly linear time, allowing the sort: O(n log n).

Clarifying questions

  • Is n always odd? What about ties in x, where sort is not differentiable?
  • Can the median be zero?
  • Should the result be in the input's order or the sorted order?
  • May I use numpy for the forward pass?

What a strong answer covers

  • The two paths from x_j to the loss: through its own slot in the sorted output (v[p(j)] / m, where p(j) is its sorted position), and through the median, which divides every output.
  • The median term: dL/dm = -sum(v_i * s_i) / m^2, and it flows only to the element that is the median.
  • Mapping gradients back with the sort permutation (argsort), in O(n log n).
  • A finite-difference check on random inputs as the test.

Follow-ups

  • Even n, where the median is the mean of two middle elements: how does the median term split?
  • Ties in x: what subgradient do you choose and why?
  • Write the backward pass for y = sort(x) / mean(x) or / max(x).

Where it's asked

  • OpenAI · Agentic coding (beta) · Last asked Feb 2019An existing codebase and changes too large to write by hand; you work through them with an AI coding agent · An AI coding agent is expected

What it tests

autograd · gradients · numpy

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding