← LinkedIn Interview InsightsAI Engineer
Start by restating the problem and clarifying assumptions (1D points, sum of absolute distances). Explain that the objective function is convex and piecewise linear, so the minimum occurs where the subgradient contains zero, which is at the median. Then discuss time complexity: sorting takes O(n log n), but selection algorithms like Quickselect or Median of Medians can find the median in O(n) average or worst-case time.
Pro tip: Mention that for even n, any point between the two middle values minimizes the sum, and that the median approach extends to higher dimensions via the geometric median (though not simply coordinate-wise medians). This shows depth beyond the basic proof.
Restate the problem: given points x1,...,xn, minimize f(c)=Σ|xi-c|. Confirm that c can be any real number and that we seek the exact minimum.
Show that f is convex and piecewise linear with slope changes at each xi. The subgradient is zero when the number of points left of c equals the number right, i.e., c is a median. Alternatively, use the pairing argument: moving c away from the median increases distances to more points than it decreases.
Explain that for even n, any c between the two middle values yields the same minimum sum, so the median is not unique but the minimum value is.
Sorting gives O(n log n). To achieve better, use Quickselect (average O(n)) or Median of Medians (worst-case O(n)) to find the median, then compute the sum in O(n).
Write code for the O(n) selection-based solution, handle edge cases (empty array, single element), and verify with examples.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.