Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard

Problem: Report the median of every window of size k (sorted-list version with bisect).

Problem: Report the median of every window of size k (sorted-list version with bisect).
from bisect import insort, bisect_left
def medians(a, k):
    w = sorted(a[:k]); out = []
    for i in range(k, len(a) + 1):
        m = w[k // 2] if k % 2 else (w[k//2 - 1] + w[k//2]) / 2
        out.append(f"{m:g}")
        if i == len(a): break
        w.pop(bisect_left(w, a[i - k])); insort(w, a[i])
    return " ".join(out)
print(medians([1, 3, -1, -3, 5, 3, 6, 7], 4))
What is printed?
  1. A. 1 1 -1 4 5.5
  2. B. 2 1 0 4 5.5
  3. C. 1 1 3 3 6
  4. D. 0 1 1 4 5.5

Correct answer: D. 0 1 1 4 5.5

Windows: [1,3,−1,−3] → (−1 + 1)/2 = 0; [3,−1,−3,5] → (−1 + 3)/2 = 1; [−1,−3,5,3] → (−1 + 3)/2 = 1; [−3,5,3,6] → (3 + 5)/2 = 4; [5,3,6,7] → (5 + 6)/2 = 5.5. Removing the outgoing value by binary search keeps each step O(k) here (O(log k) with two heaps and lazy deletion).

More Coding Interview Problems questions

Exams that ask this topic