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?- A. 1 1 -1 4 5.5
- B. 2 1 0 4 5.5
- C. 1 1 3 3 6
- 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
- Problem: A single-threaded CPU receives tasks [enqueueTime, processingTime]. When idle it runs the available task with the shortest…
- Problem: A min-stack supports push, pop, top and getMin in O(1) by storing (value, current minimum) pairs. python st, out = [], [] def…
- Problem: Josephus problem: n people in a circle, every k-th person is eliminated; find the 1-based position of the survivor. python def…
- Problem: Count permutations of 1..n where, for every position i (1-based), the value is divisible by i or i is divisible by the value…
- Problem: Each candidate can be used at most ONCE and the list has duplicates; count the distinct combinations that sum to the target…
- Problem: Divide two integers without , / or %, truncating toward zero, using doubling (shifts). python def divide(a, b): neg = (a < 0) !=…