Rolling Window Median Bounds + Binary Array Tiling
Heaps, Sorting & SearchModel answerLast updated
Find the max and min sliding-window medians in O(n log k), then partition a binary array into even uniform segments with minimum flips.
Part A — Min and Max of All Window Medians
You are given an integer array nums of length n and a window size k (1 ≤ k ≤ n).
Slide a window of exactly k elements across nums from left to right. For each position, compute the lower median of the elements in that window — that is, the element at 0-indexed sorted position (k - 1) // 2. Once you have all those medians, return their maximum and their minimum.
Requirements:
- Time complexity: O(n log k)
- Space complexity: O(k)
- Describe the data structures you use and justify both bounds.
Example:
nums = [3, 1, 4, 1, 5, 9, 2], k = 3
Windows: [3,1,4] → 3, [1,4,1] → 1, [4,1,5] → 4, [1,5,9] → 5, [5,9,2] → 5
Output: max = 5, min = 1
Part B — Even-Length Uniform Tiling with Fewest Flips
You are given a binary array frames of length n (each element is 0 or 1).
You may flip any elements (0 to 1, or 1 to 0). After flipping, the array must be partitioned into contiguous segments where every segment has even length and every element in a segment is identical (all 0s or all 1s). Adjacent segments may have different values.
Goals, in priority order:
- Minimize the number of segments.
- Subject to that minimum, minimize the total number of flips.
Return the minimum segment count and the minimum number of flips needed to achieve it.
Requirements:
- Describe your algorithm and state its time and space complexity.
- Handle edge cases: odd
n, empty array, already-uniform arrays.
Example:
frames = [1, 1, 0, 1, 0, 0]
Pairs: (1,1), (0,1), (0,0)
Pair 0 is already uniform (value 1, 0 flips).
Pair 1 is mixed — flip to 1 (1 flip) to stay in the same segment, or flip to 0 (1 flip) to start a new segment.
Pair 2 is already uniform (value 0).
Optimal: [1,1,1,1,0,0] → 2 segments, 1 flip.
Output: (2, 1)
Hints
Hint 1
For Part A, think about what structure lets you read off the median in O(1). A max-heap holding the smaller half and a min-heap holding the larger half keeps the median at the top of the max-heap — but how do you remove the element that leaves the window without breaking the heap property?
Hint 2
For Part A's deletion problem, you don't have to remove stale elements immediately. Instead, mark them and skip them when they surface at the top. Track valid counts separately from physical heap sizes so rebalancing uses real counts. To keep space O(k) rather than O(n), periodically strip out stale entries and re-heapify.
Hint 3
For Part B, notice that every segment boundary must fall on an even index, so the array naturally breaks into consecutive non-overlapping pairs. Each pair must become uniform independently. The number of segments is 1 plus the number of adjacent pairs that end up with different values — a classic DP transition over two states (the value assigned to the current pair).
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Part A: Maximum and Minimum of Sliding-Window Medians
Approach
The lower median of a window of size k is the element at sorted index (k-1)//2 — the top of the smaller half when the window is split evenly. That points directly to a two-heap structure:
low: a max-heap holding theceil(k/2)smallest elements. Its top is the lower median.high: a min-heap holding the remainingfloor(k/2)elements.
Invariants to maintain after every step:
- Every valid element in
low≤ every valid element inhigh(by value; break ties by index). lo_n == hi_norlo_n == hi_n + 1, wherelo_nandhi_nare counts of valid (non-stale) elements.
When both hold, low's valid top is exactly the lower median.
Handling deletions: lazy eviction
Heaps don't support arbitrary removal efficiently. Instead, use lazy deletion:
- Store
(value, index)pairs so every element has a unique identity. - An entry is stale if its index falls before the current window's left boundary.
- Before reading any heap top, pop and discard stale entries until a live one is at the front.
- Maintain
lo_nandhi_nas separate counters and rebalance using those, not the physical heap sizes.
When the element leaving the window belonged to low, decrement lo_n; otherwise decrement hi_n. You can tell which half it belongs to by comparing it against the current valid top of low.
Keeping space O(k): periodic compaction
Lazy deletion alone lets stale entries accumulate up to O(n). Fix this with compaction: whenever the combined physical size of both heaps exceeds 2k + 2, filter out all stale entries from both and re-heapify. Each compaction costs O(k). It can only be triggered once per Θ(k) new insertions, so the amortized cost per element is O(1) and space stays O(k).
In C++ or Java, std::multiset / TreeMap support true O(log k) deletion and avoid this complication entirely.
Complexity
- Time: O(n log k). Each element is pushed and popped at most once per heap, and heaps stay O(k) by compaction.
- Space: O(k).
Edge cases
k = 1: every element is its own median; just returnmax(nums)andmin(nums).k = n: one window, one median.- Duplicate values: index tie-breaking makes the ordering total, so duplicates never cause ambiguity about which half an element belongs to.
- Even
k:ceil(k/2)elements go intolow, so the top is automatically the lower median.
Code
import heapq
def median_extremes(nums, k):
# low stores (-value, -index) to simulate a max-heap
# high stores (value, index) as a min-heap
low, high = [], []
lo_n = hi_n = 0
start = 0
best_max, best_min = float('-inf'), float('inf')
def clean_low():
while low and -low[0][1] < start:
heapq.heappop(low)
def clean_high():
while high and high[0][1] < start:
heapq.heappop(high)
def rebalance():
nonlocal lo_n, hi_n
while lo_n > hi_n + 1:
clean_low()
v, j = heapq.heappop(low)
lo_n -= 1
heapq.heappush(high, (-v, -j))
hi_n += 1
while lo_n < hi_n:
clean_high()
v, j = heapq.heappop(high)
hi_n -= 1
heapq.heappush(low, (-v, -j))
lo_n += 1
def compact():
if len(low) + len(high) > 2 * k + 2:
low[:] = [e for e in low if -e[1] >= start]
high[:] = [e for e in high if e[1] >= start]
heapq.heapify(low)
heapq.heapify(high)
for i, x in enumerate(nums):
# Insert new element
clean_low()
if not low or x <= -low[0][0]:
heapq.heappush(low, (-x, -i))
lo_n += 1
else:
heapq.heappush(high, (x, i))
hi_n += 1
rebalance()
compact()
# Evict element leaving the window
if i >= k:
out_j = i - k
out_v = nums[out_j]
clean_low()
if low and out_v <= -low[0][0]:
lo_n -= 1
else:
hi_n -= 1
rebalance()
compact()
# Record median once we have a full window
if i >= k - 1:
clean_low()
med = -low[0][0]
best_max = max(best_max, med)
best_min = min(best_min, med)
return best_max, best_min
Part B: Even-Length Uniform Tiling with Minimum Flips
Structural observation
Every segment has even length and the first one starts at index 0, so every segment boundary falls at an even index. The array decomposes naturally into non-overlapping consecutive pairs (frames[2i], frames[2i+1]). Each pair must be made uniform (both 0 or both 1). The number of segments equals 1 plus the number of adjacent pairs assigned different values.
If n is odd, no valid partition exists — return (-1, -1). If n is 0, return (0, 0).
Algorithm: two-state DP over pairs
Let dp[v] = best (segments, flips) achievable for all pairs processed so far, with the most recent pair assigned value v. For each new pair at index 2i, compute:
cost(v)= number of flips to make this pair all-v(0, 1, or 2).- Stay in the same segment:
(dp[v][0], dp[v][1] + cost(v)) - Start a new segment:
(dp[1-v][0] + 1, dp[1-v][1] + cost(v))
Take whichever is lexicographically smaller under (segments, flips) ordering.
Why DP works here
Both cost components accumulate additively, and lexicographic comparison is preserved under addition: a ≤ b ⇒ a + c ≤ b + c. So the optimal-substructure property holds. Only the value of the last pair influences future transitions, so two states are sufficient.
Complexity
- Time: O(n) — one pass over pairs, O(1) work each.
- Space: O(1) — only two DP states at a time.
Edge cases
nodd: impossible, return(-1, -1).n = 0: return(0, 0).- All elements equal: one segment, zero flips.
- All pairs mixed (
01or10): each needs 1 flip; the DP chooses the same target value greedily to avoid extra segment breaks.
Code
def min_segments_and_flips(frames):
n = len(frames)
if n % 2 == 1:
return (-1, -1)
if n == 0:
return (0, 0)
def pair_cost(i, v):
# flips needed to make frames[2i], frames[2i+1] both equal to v
return (frames[2 * i] != v) + (frames[2 * i + 1] != v)
# dp[v] = (segments, flips) for the best assignment ending with value v
dp = [
(1, pair_cost(0, 0)), # first pair forced to value 0
(1, pair_cost(0, 1)), # first pair forced to value 1
]
for i in range(1, n // 2):
new_dp = []
for v in (0, 1):
c = pair_cost(i, v)
stay = (dp[v][0], dp[v][1] + c)
switch = (dp[1-v][0]+1, dp[1-v][1] + c)
# lexicographic min: fewer segments wins; tie goes to fewer flips
new_dp.append(min(stay, switch))
dp = new_dp
return min(dp)
Common mistakes to watch for
- Part A: forgetting that
lo_nandhi_ntrack valid elements, not physical heap sizes — rebalancing on physical sizes breaks the median invariant. - Part A: ignoring the space blowup from lazy deletion and not implementing compaction.
- Part B: treating the problem as operating on individual elements rather than on pairs, which makes the state space and transitions much harder to reason about.
- Part B: conflating the two priority orderings (segments-first vs. flips-first). State the assumed priority explicitly before coding; the DP structure is the same but the comparison function differs.