Topic set: lists, stacks and queues
28 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Linear data structures form the backbone of coding interviews. We tackle classic pointer-manipulation and stack patterns, contrasting naive scanning with optimal linear-time algorithms.
Brute force versus pointer techniques in linked lists
When faced with a linked list task—such as finding the middle node, detecting cycles, or reversing nodes—a beginner often copies all node values into an auxiliary array or list. Once in an array, finding the middle is trivial via index N / 2, and reversing is just reading backwards. However, this naive approach consumes O(N) extra space and violates strict in-place constraints.
Optimal linked list algorithms rely on pointer manipulation in O(1) auxiliary space. For reversal, we maintain three pointers—prev, curr, and next—reorienting each node's next pointer in a single linear pass of O(N) time.
For cycle detection and middle-node identification, Floyd's cycle-finding algorithm (the slow and fast pointer technique) advances the fast pointer twice as quickly as the slow pointer. If a cycle exists, the fast pointer laps and collides with the slow pointer inside the cycle; if no cycle exists, fast hits null. Both techniques require exactly O(N) time while utilizing strictly O(1) extra memory.
Example 1 · Iterative In-Place Linked List Reversal
public class ReverseLinkedListDemo { static class ListNode { int val; ListNode next; ListNode(int val) { this.val = val; } }
public static ListNode reverseList(ListNode head) { ListNode prev = null; ListNode curr = head; while (curr != null) { ListNode next = curr.next; curr.next = prev; prev = curr; curr = next; } return prev; }
public static void main(String[] args) { ListNode n1 = new ListNode(1); ListNode n2 = new ListNode(2); ListNode n3 = new ListNode(3); n1.next = n2; n2.next = n3;
ListNode rev = reverseList(n1); StringBuilder sb = new StringBuilder(); while (rev != null) { sb.append(rev.val).append(" "); rev = rev.next; } System.out.println("Reversed: " + sb.toString().trim()); }}Reversed: 3 2 1
What this code does
- Maintains prev, curr, and next pointers to redirect edges backwards in-place.
- Iterates through the list of 3 nodes in O(N) time with O(1) extra space.
- Returns the new head node (3) pointing sequentially to 2 and 1.
Monotonic stack mechanics: next greater element and span
Many interview problems ask for the next greater element, previous smaller element, or stock span across an array. The brute-force solution uses nested loops: for each index i, scan rightward across indices i + 1 through N - 1 until encountering a larger value. In the worst case—such as a strictly decreasing array—this nested scan executes N * (N - 1) / 2 comparisons, degrading to O(N^2) quadratic time.
A monotonic stack reduces this quadratic runtime to O(N) linear time. A monotonic decreasing stack stores elements (or their indices) in descending order from bottom to top. As we iterate through the array, before pushing the current element, we repeatedly pop all elements from the stack that are smaller than or equal to the current element.
Because every array element is pushed onto the stack exactly once and popped at most once, the total number of stack operations across the entire algorithm is bounded by 2 * N. This guarantees strictly O(N) total time complexity, transforming an intractable quadratic bottleneck into a fast single-pass scan.
Example 2 · Monotonic Stack for Next Greater Element
import java.util.*;
public class NextGreaterElementDemo { public static int[] nextGreaterElements(int[] nums) { int n = nums.length; int[] result = new int[n]; Arrays.fill(result, -1); Deque<Integer> stack = new ArrayDeque<>(); // stores indices
for (int i = 0; i < n; i++) { while (!stack.isEmpty() && nums[stack.peek()] < nums[i]) { int prevIdx = stack.pop(); result[prevIdx] = nums[i]; } stack.push(i); } return result; }
public static void main(String[] args) { int[] arr = {2, 1, 2, 4, 3}; int[] ans = nextGreaterElements(arr); System.out.println("Next greater: " + Arrays.toString(ans)); }}Next greater: [4, 2, 4, -1, -1]
What this code does
- For 2 at index 0, next greater is 4.
- For 1 at index 1, next greater is 2 at index 2.
- Each element is pushed and popped at most once, guaranteeing O(N) total time.
Queues and sliding window deques
Standard FIFO (First-In-First-Out) queues process elements in arrival order and form the operational foundation of Breadth-First Search (BFS) and streaming buffers. Both enqueue (offer) and dequeue (poll) execute in O(1) time.
Example 3 · Sliding Window Maximum via Monotonic Deque
import java.util.*;
public class SlidingWindowDequeDemo { public static int[] maxSlidingWindow(int[] nums, int k) { if (nums == null || nums.length == 0) return new int[0]; int n = nums.length; int[] res = new int[n - k + 1]; Deque<Integer> deque = new ArrayDeque<>(); // stores indices
for (int i = 0; i < n; i++) { // Remove indices outside the current window [i - k + 1 .. i] while (!deque.isEmpty() && deque.peekFirst() < i - k + 1) { deque.pollFirst(); } // Remove smaller elements from the back while (!deque.isEmpty() && nums[deque.peekLast()] < nums[i]) { deque.pollLast(); } deque.offerLast(i);
// Record maximum once first window is formed if (i >= k - 1) { res[i - k + 1] = nums[deque.peekFirst()]; } } return res; }
public static void main(String[] args) { int[] nums = {1, 3, -1, -3, 5, 3, 6, 7}; int[] maxes = maxSlidingWindow(nums, 3); System.out.println("Window maxes: " + Arrays.toString(maxes)); }}Window maxes: [3, 3, 5, 5, 6, 7]
What this code does
- Window 1 {1, 3, -1} has maximum 3.
- Window 2 {3, -1, -3} has maximum 3.
- Deque front always provides the maximum element in O(1) amortized time.
When finding the maximum value in every sliding window of size K across an array, a naive scan of each window takes O(K) time, leading to O(N * K) total time. If K is large (e.g. 50,000), this quadratic complexity times out. Using a max-heap improves the window query to O(log K), giving O(N log K) time. The optimal solution uses a monotonic double-ended queue (deque) to achieve strictly O(N) time. The deque maintains candidate maximum indices in decreasing value order. For each new index, we remove stale indices that fell out of the left window boundary from the front, pop smaller elements from the back, and push the current index. The front of the deque always holds the index of the maximum element for the current window in O(1) amortized time.
Complexity discipline: stating asymptotic time and space
In technical interviews, simply writing functional code is not enough; interviewers expect a rigorous, unambiguous analysis of time and space complexity. A frequent mistake is confusing auxiliary space with output space.
Auxiliary space is the temporary working memory allocated by your algorithm to solve the problem (such as stack frames, hash sets, or pointers), excluding the memory needed to store the input and output. For example, reversing a linked list in-place has O(1) auxiliary space, whereas returning a newly created reversed list has O(N) space.
Furthermore, always account for the call stack when using recursion. A recursive traversal of a linked list or tree of depth N consumes O(N) space on the JVM call stack, which can trigger StackOverflowError on large inputs. Whenever memory is constrained, prefer iterative implementations that run with O(1) stack overhead.
Next step
Check your understanding
10 quick questions