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.

5 min readUpdated 2026-11-30
In This Lesson
  • 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

DrillNaive Brute ForceTarget Optimal PatternTarget Complexity
1. max_sum_kRe-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_frequentSort entire array or scan repeatedly → O(n log n)Frequency Map + Bucket Sort (or Counter)O(n) bucket / O(n log k)
3. next_greaterNested loop scanning right for each item → O(n²)Monotonic Decreasing Stack of indicesO(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 for i from k to len(nums) - 1, update window += 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 = 8
    • i = 4: 7 + 3 - 1 = 9, best = 9
    • i = 5: 9 + 2 - 5 = 6, best = 9
  • Edge cases: Negative numbers! Never initialize best = 0—initialize best = window so an array like [-5, -2, -3] with k = 2 returns -5, not 0. Also guard if 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 top k (value, count) pairs cleanly (O(n log k) internally using a heap when k < n).
  • Idea B (True O(n) Bucket Sort): Because no frequency can exceed len(nums), create buckets = [[] for _ in range(len(nums) + 1)], drop each val into buckets[freq], and read from len(nums) down to 1 until len(res) == k.
  • Edge cases: k == len(unique_elements) or negative numbers (Counter handles negative keys effortlessly).

Drill 3: Next Greater Element (next_greater)

  • Idea: Initialize res = [-1] * len(nums) and an empty stack of indices. When val > nums[stack[-1]], pop the smaller index and set res[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): pops 1 (res[1] = 2), 2 <= 2 stops, stack = [0, 2]
    • i=3 (4): pops 2 (res[2] = 4), pops 0 (res[0] = 4), stack = [3]
    • i=4 (3): 3 <= 4, stack = [3, 4] → final res = [4, 2, 4, -1, -1]!
Watch Out for Negative Values in max_sum_k

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!

Try Both Counter and Bucket Sort for top_k_frequent

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):

Python 3Lab 1: Implement All 3 Linear Algorithm Drills
Output

Click “Run Code” to execute this snippet right in your browser.

Lab Checkpoint

Check Your Understanding

In top_k_frequent using bucket sort, why is len(nums) + 1 buckets always enough?

DSA Lab 1 Checklist

0/4 done