Copy-me cards
1. Queue using Stacks two stacks / reversal
Insight: a second stack reverses LIFO into FIFO; move all elements over so the queue-front sits on top.
Complexity: amortized O(1) per op [+]; naive move-every-time O(n) per op. Space O(n).
push(x): while s2 not empty: s1.push(s2.pop()); s1.push(x) peek(): if s2 empty: while s1: s2.push(s1.pop()); return s2.top pop(): peek(); return s2.pop() empty(): s1.empty && s2.empty
star TRICK: shift only when the target stack is empty → amortized O(1). [+]
LeetCode 232 — "Implement Queue using Stacks"
2. Moving Average from Stream sliding window / queue
Insight: keep a running sum + a queue of window size; on overflow, subtract the popped front.
Complexity: O(1) per next(), O(k) space.
next(v): q.add(v); sum += v
if q.size > k: sum -= q.poll()
return sum / q.size()
star TRICK: never re-sum the window — maintain sum incrementally.
! PITFALL: divide by current count (min(seen,k)), not always k.
LeetCode 346 — "Moving Average from Data Stream"
3. Flatten Multilevel Linked List queue / traversal
Insight: walk next chain; enqueue
each child seen; when next==null, splice the queue's
front on.
Complexity: O(n) time, O(n) space (queue).
cur = head
while cur: if cur.child: q.add(cur.child)
if cur.next == null && q not empty: cur.next = q.poll()
cur = cur.next
return head
star TRICK: queue turns nested pointers into a flat FIFO order — no messy pointer surgery.
LeetCode 430 — "Flatten a Multilevel Doubly Linked List" (variant) [!]
4. Node to the Right of Key (Tree) BFS / level order
Insight: BFS level by level; when node==key, its right neighbor is the next item in the queue — unless it's last in the level.
Complexity: O(n) time, O(n) space.
q=[root]
while q: n=q.size
for i in 0..n-1: cur=q.poll()
if cur.data==key: return (i==n-1)? null : q.peek()
add cur.left, cur.right
return null
! PITFALL: check the key-match inside the per-level loop; peek (don't poll) the right neighbor.
GeeksforGeeks — "Find right node of a given node in binary tree"
5. Sliding Window Maximum monotonic deque
Insight: store indices in a deque kept decreasing by value; front is always the window max.
Complexity: O(n) time, O(k) space.
for i in 0..n-1: if dq.front <= i-k: dq.pollFirst // out of window while dq && a[dq.last] <= a[i]: dq.pollLast // smaller → useless dq.addLast(i) if i >= k-1: output a[dq.first]
star TRICK: store indices not values → you can
detect the window edge i-k.
! PITFALL: pop stale front by index before reading the max.
LeetCode 239 — "Sliding Window Maximum"