Skip to content

ORIGINAL CODING QUESTION

Running lower median of response times

Response times arrive one by one. After each arrival, take the lower median of everything seen so far: with c values in sorted order, it is the value at zero-based position floor((c-1)/2). Return the sum of these lower medians over all arrivals.

Open practice workspace

Original exercise · hard. Editorial role relevance does not imply a company has asked this question.

Input and output

n, then n response times in arrival order.

Constraints

1 ≤ n ≤ 200; -1000 ≤ value ≤ 1000.

Example 1

Input

4 5 1 3 2

Output

11

Lower medians are 5, 1, 3 and 2, totalling 11.

Example 2

Input

3 -2 -2 -2

Output

-6

Every median is -2, totalling -6.

Explain your approach

Explain your time and auxiliary space complexity. Which input makes your algorithm work hardest?

Private grading inputs, expected outputs and canonical reference implementations are withheld. Authored expected outputs were cross-checked with independent reference oracles; compiler/runtime behavior still needs a verified execution provider.

Hint 1

Re-sorting after every arrival works but repeats a lot of effort.

Hint 2

Split values into a max-heap of the lower half and a min-heap of the upper half.

Hint 3

Keep the lower half equal in size or exactly one larger; its top is the lower median.

Practice this question

Save your work privately, explain decisions and return to your revision queue.

Open practice workspaceBrowse the question library →