Practice: stacks and queues
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Solving realistic interview challenges tests your ability to choose between stacks, queues, and deques. Each problem matches an access pattern: backtracking, sequential ordering, or boundary tracking.
Path simplification and directory navigation
Simplifying a Unix path is a stack problem: each folder name is pushed, and .. pops the last folder.
- Split string by
/. - Skip empty tokens and
.. - On
.., pop from stack if not empty. - Push standard directory names.
- Join stack from bottom to top prefixed by
/.
Example 1 · Simplify Unix File Path Demo
import java.util.ArrayDeque;import java.util.Deque;
public class SimplifyPathDemo { public static String simplifyPath(String path) { Deque<String> stack = new ArrayDeque<>(); for (String part : path.split("/")) { if (part.equals("..")) { if (!stack.isEmpty()) stack.pop(); } else if (!part.isEmpty() && !part.equals(".")) { stack.push(part); } } if (stack.isEmpty()) return "/"; StringBuilder sb = new StringBuilder(); while (!stack.isEmpty()) { sb.append("/").append(stack.pollLast()); } return sb.toString(); }
public static void main(String[] args) { System.out.println(simplifyPath("/a/./b/../../c/")); }}/c
What this code does
- Entering
athenbpushes both. - First
..popsb, second..popsa. - Entering
cleaves/cas the canonical path.
- Delimiter split: split path string by
/. - Ignore tokens: skip empty strings and single dots
.. - Parent directory: pop from stack on
... - Directory push: push regular names onto the stack.
Use ArrayDeque for the stack: the legacy java.util.Stack synchronises every call, and ArrayDeque throws NullPointerException for null elements, so use LinkedList only when nulls must be stored.
Collision physics and greedy digit removal
Asteroid collisions simulate moving objects: positive values move right and negative values move left. A collision happens only when a positive asteroid meets an incoming negative asteroid.
Example 2 · Asteroid Collision Simulation
import java.util.ArrayDeque;import java.util.Arrays;import java.util.Deque;
public class AsteroidCollisionDemo { public static int[] asteroidCollision(int[] asteroids) { Deque<Integer> stack = new ArrayDeque<>(); for (int a : asteroids) { boolean destroyed = false; while (!stack.isEmpty() && a < 0 && stack.peek() > 0) { if (stack.peek() < -a) { stack.pop(); } else if (stack.peek() == -a) { stack.pop(); destroyed = true; break; } else { destroyed = true; break; } } if (!destroyed) stack.push(a); } int[] res = new int[stack.size()]; for (int i = res.length - 1; i >= 0; i--) res[i] = stack.pop(); return res; }
public static void main(String[] args) { int[] ast = {5, 10, -5}; System.out.println(Arrays.toString(asteroidCollision(ast))); }}[5, 10]
What this code does
- Asteroid 10 moves right and -5 moves left.
- 10 is larger than 5, so -5 explodes.
- Surviving asteroids are
[5, 10].
Example 3 · Remove K Digits Using Monotonic Stack
import java.util.ArrayDeque;import java.util.Deque;
public class RemoveKDigitsDemo { public static String removeKdigits(String num, int k) { Deque<Character> stack = new ArrayDeque<>(); for (char c : num.toCharArray()) { while (!stack.isEmpty() && k > 0 && stack.peek() > c) { stack.pop(); k--; } stack.push(c); } while (k > 0 && !stack.isEmpty()) { stack.pop(); k--; } StringBuilder sb = new StringBuilder(); while (!stack.isEmpty()) sb.append(stack.pollLast()); while (sb.length() > 0 && sb.charAt(0) == '0') sb.deleteCharAt(0); return sb.length() == 0 ? "0" : sb.toString(); }
public static void main(String[] args) { System.out.println(removeKdigits("1432219", 3)); }}1219
What this code does
- Greedily pops 4 and 3 because smaller numbers 2 and 1 follow.
- Removes leading zeroes if any appear.
- Smallest resulting number is 1219.
A stack tracks surviving asteroids moving right. When a negative asteroid arrives, compare sizes and pop smaller positive asteroids until one explodes or both explode. In digit removal, a monotonic increasing stack greedily removes larger preceding digits to form the smallest possible number.
Remember:
- Collision condition: top of stack > 0 and incoming asteroid < 0.
- Equal sizes: both asteroids explode and vanish.
- Greedy digit removal: pop stack when incoming digit < stack top and k > 0.
Decision guide: choosing between stack, queue and deque
Java's ArrayDeque works as a stack, a queue or a deque; the data access pattern a problem needs decides which ends you use.
Deque<Integer> stack = new ArrayDeque<>();stack.push(1); stack.push(2);stack.pop(); // 2: LIFO, one end only
Queue<Integer> queue = new ArrayDeque<>();queue.offer(1); queue.offer(2);queue.poll(); // 1: FIFO, in at the back, out at the front
Deque<Integer> window = new ArrayDeque<>();window.offerLast(1); window.offerLast(2);window.pollFirst(); window.pollLast(); // both ends, as in a sliding windowUse a stack for LIFO order, undo history, balanced delimiters, expression evaluation, and next-greater element searches.
Use a queue for FIFO order, event buffering, and Breadth-First Search. Use a deque when operations touch both boundaries, such as sliding windows.
- Stack (
ArrayDeque): LIFO access, undo, matching, monotonic boundaries. - Queue (
ArrayDeque): FIFO access, task queues, BFS level order. - Deque (
ArrayDeque): dual-ended access, sliding window extrema.
Finish up
Mark complete & continue
Next: How hashing works