2. Linear Patterns, Stacks & Queues
Practice Lab 1: Hash Maps, Sliding Windows & Monotonic Stacks
Sharpen your Module 1-2 interview skills with three timed coding drills: Top-K Frequent Elements, Max Sum Subarray of Size K, and Next Greater Element.
- Solve Top-K Frequent Elements using Counter / bucket grouping
- Implement a fixed-size sliding window in O(n) time
- Implement Next Greater Element using a monotonic decreasing stack
Time to combine everything from Modules 1 & 2! In real technical screens, these three problems test whether you can replace O(n²) loops and repeated slice allocations with clean linear-time Python patterns.
Why These 3 Drills Matter
| Drill | Naive Brute Force | Target Optimal Pattern | Target Complexity |
|---|---|---|---|
1. max_sum_k | Re-sum sum(nums[i : i + k]) each step → O(n · k) | Fixed Sliding Window (add right, drop left) | O(n) time, O(1) space |
2. top_k_frequent | Sort entire array or scan repeatedly → O(n log n) | Frequency Map + Bucket Sort (or Counter) | O(n) bucket / O(n log k) |
3. next_greater | Nested loop scanning right for each item → O(n²) | Monotonic Decreasing Stack of indices | O(n) time, O(n) space |
Blueprint & Edge-Case Checklist Before You Code
Drill 1: Fixed-Size Sliding Window (max_sum_k)
- Idea: Compute the first window
window = sum(nums[:k]), then forifromktolen(nums) - 1, updatewindow += nums[i] - nums[i - k]. - Dry-run on
[2, 1, 5, 1, 3, 2],k = 3:- Initial (
0..2):2 + 1 + 5 = 8,best = 8 i = 3:8 + 1 - 2 = 7,best = 8i = 4:7 + 3 - 1 = 9,best = 9i = 5:9 + 2 - 5 = 6,best = 9
- Initial (
- Edge cases: Negative numbers! Never initialize
best = 0—initializebest = windowso an array like[-5, -2, -3]withk = 2returns-5, not0. Also guardif k <= 0 or k > len(nums):.
Drill 2: Top-K Frequent Elements (top_k_frequent)
- Idea A (Concise Stdlib):
Counter(nums).most_common(k)returns the topk(value, count)pairs cleanly (O(n log k)internally using a heap whenk < n). - Idea B (True
O(n)Bucket Sort): Because no frequency can exceedlen(nums), createbuckets = [[] for _ in range(len(nums) + 1)], drop eachvalintobuckets[freq], and read fromlen(nums)down to1untillen(res) == k. - Edge cases:
k == len(unique_elements)or negative numbers (Counterhandles negative keys effortlessly).
Drill 3: Next Greater Element (next_greater)
- Idea: Initialize
res = [-1] * len(nums)and an emptystackof indices. Whenval > nums[stack[-1]], pop the smaller index and setres[idx] = val. - Dry-run on
[2, 1, 2, 4, 3]:i=0 (2):stack = [0]i=1 (1):1 <= 2,stack = [0, 1]i=2 (2): pops1(res[1] = 2),2 <= 2stops,stack = [0, 2]i=3 (4): pops2(res[2] = 4), pops0(res[0] = 4),stack = [3]i=4 (3):3 <= 4,stack = [3, 4]→ finalres = [4, 2, 4, -1, -1]!
Initializing best = 0 before scanning [ -4, -1, -7 ] with k = 2 returns 0 instead of -5. Always initialize best = window using the first actual window sum!
Once your assertions pass with Counter(nums).most_common(k), challenge yourself to rewrite top_k_frequent using O(n) bucket grouping without sorting or heaps.
Live Coding Lab
Complete all three core interview drills in the live Python sandbox below and uncomment the assert tests to verify your solutions (including negative-number and duplicate edge cases):
Click “Run Code” to execute this snippet right in your browser.
Lab Checkpoint
In top_k_frequent using bucket sort, why is len(nums) + 1 buckets always enough?