Solve median extremes and segment flips
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Take-home Project
Quick Answer: Solve median extremes and segment flips evaluates algorithm design, data structures, correctness, complexity, edge cases, and implementation details in a realistic interview setting. A strong answer states assumptions, handles edge cases, explains trade-offs, and shows how to validate the result clearly.
Sliding-Window Median Extremes
Constraints
- 1 ≤ k ≤ n is the valid case; if k > n return [].
- 0 ≤ n ≤ 10^5
- -10^9 ≤ nums[i] ≤ 10^9
- For even k, the median is the lower of the two middle elements (sorted index (k-1)/2).
Examples
Input: (3, [1, 3, -1, -3, 5, 3, 6, 7])
Expected Output: [6, -1]
Explanation: Windows of size 3 have medians 1, -1, -1, 3, 5, 6; max=6, min=-1.
Input: (1, [5, 2, 8, 1])
Expected Output: [8, 1]
Explanation: k=1: each element is its own median; max=8, min=1.
Hints
- Maintain the current window as an ordered multiset; the lower median is always at sorted index (k-1)//2.
- On each slide, delete the element leaving the window and insert the one entering it, then read the element at the fixed median index.
- Track a running max and min of the medians as you go, or collect all medians and reduce — either way the answer is [max, min].
- Edge case: when k > n there are no windows, so return an empty array.
Even-Length Uniform Segmenting with Minimal Flips
Constraints
- 0 ≤ n ≤ 10^5
- frames[i] ∈ {0, 1}
- A valid partition (all segments even-length) exists iff n is even.
- Minimize segment count first, then total flips.
Examples
Input: ([1, 0, 0, 1],)
Expected Output: [1, 2]
Explanation: n=4 even; two 1s and two 0s, flip the two of the minority value -> 1 segment, 2 flips.
Input: ([0, 0, 0, 0],)
Expected Output: [1, 0]
Explanation: Already uniform and even length: 1 segment, 0 flips.
Hints
- Every segment has even length, so the segment lengths sum to an even number — a valid partition exists only when n is even.
- When n is even, one single even-length uniform segment covering the whole array is always valid, so the minimum segment count is 1.
- With one segment the whole array must be uniform; the cheapest way is to flip the minority value, costing min(#ones, #zeros) flips.
- Handle the empty array as [0, 0] and odd-length n as impossible ([-1, -1]).