I knew the answer was the median from some vague memory but actually proving it on the spot was a different story.
First, restate the problem and clarify that the objective is to minimize the sum of absolute deviations. Then, prove that the median minimizes this sum by using the subgradient method or a pairwise exchange argument. Finally, implement an efficient solution using quickselect (or sorting) to find the median in O(n) expected time.
Pro tip: Mention that for even-sized arrays, any point between the two middle elements is optimal, and that the median minimizes L1 loss, which is more robust to outliers than the mean (L2 loss).
Confirm the problem: given a 1D array of coordinates, find c that minimizes f(c) = sum_i |x_i - c|. Note that the points can be unsorted and may contain duplicates.
Prove that the median minimizes f(c). Use the subgradient method: f'(c) = (# points < c) - (# points > c), and set to zero. Alternatively, use a pairwise exchange argument: if c is not a median, moving it toward the median reduces the sum.
Choose an efficient algorithm to find the median. Options: sort the array (O(n log n)) or use quickselect (O(n) expected). For large n, quickselect is preferred. Handle even n by picking either middle element.
Implement the chosen algorithm. For quickselect, write a partition function and recursively select the k-th element. Ensure it handles edge cases (empty array, single element, duplicates).
Analyze time and space complexity: O(n) expected time for quickselect, O(1) extra space if in-place. Discuss trade-offs: sorting is simpler but slower; quickselect has worst-case O(n^2) unless using median-of-medians.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.