← Questions
Backpropagate through sort and divide by the median
0
I was asked this
No reports yet. Sign in to say where you were asked it.
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 asx, in the original order ofx.
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
-
nis odd and the median is unique, so the median is one element ofx. - Answers are compared with a small floating-point tolerance.
- Roughly linear time, allowing the sort: O(n log n).
Clarifying questions
- Is
nalways odd? What about ties inx, 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_jto the loss: through its own slot in the sorted output (v[p(j)] / m, wherep(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
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
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
