Skip to lesson

Mixed sets: choose the structure

Real technical interviews present problems without topic hints or structure labels. We practice identifying underlying algorithmic signatures and justifying our data structure choices.

The unlabelled problem dilemma: classification framework

In online assessments and onsite coding rounds, you never receive a prompt labeled 'Use a Monotonic Stack' or 'Apply Topological Sort'. You are presented with a real-world scenario—such as scheduling dependent tasks, finding trap water between towers, or merging server request streams—and must deduce the structure independently.

You can systematically categorize any unlabelled problem by analyzing its constraint signature:

  1. N <= 10^5 and asks for range queries or running max/min -> Monotonic Deque, Segment Tree, or Fenwick Tree.
  2. Unordered pairs summing or mapping to targets -> Hash Map or Two Pointers after sorting.
  3. Directed prerequisite dependencies -> Kahn's Topological Sort (check for DAG cycles).
  4. Unweighted shortest path or level progression -> Breadth-First Search queue.

Comparing competing data structure candidates

Frequently, multiple data structures can solve the same problem, but with different trade-offs. For example, Merge K Sorted Lists can be solved by collecting all N elements and sorting (O(N log N) time), pairwise merging (O(N * K) time), or using a Min-Heap of size K (O(N log K) time).

In an interview, articulating these trade-offs before typing code demonstrates senior engineering maturity. Explain why you reject naive approaches: 'Pairwise merging takes O(N * K), which is too slow when K is large. Sorting takes O(N log N), ignoring the existing sorted property. A min-heap of size K preserves the sorted structure and minimizes memory to O(K) auxiliary space, running in optimal O(N log K) time.'

Defending your choice based on cache locality, auxiliary memory footprint, and asymptotic scalability proves you write production-ready code.

Example 1 · Merge K Sorted Lists via Min-Heap

MergeKSortedListsDemo.javaJava
import java.util.*;
public class MergeKSortedListsDemo {    static class ListNode {        int val;        ListNode next;        ListNode(int val) { this.val = val; }    }
    public static ListNode mergeKLists(ListNode[] lists) {        if (lists == null || lists.length == 0) return null;        PriorityQueue<ListNode> pq = new PriorityQueue<>((a, b) -> Integer.compare(a.val, b.val));
        for (ListNode node : lists) {            if (node != null) pq.offer(node);        }
        ListNode dummy = new ListNode(0);        ListNode tail = dummy;
        while (!pq.isEmpty()) {            ListNode smallest = pq.poll();            tail.next = smallest;            tail = tail.next;            if (smallest.next != null) pq.offer(smallest.next);        }        return dummy.next;    }
    public static void main(String[] args) {        ListNode l1 = new ListNode(1); l1.next = new ListNode(4);        ListNode l2 = new ListNode(2); l2.next = new ListNode(6);        ListNode[] lists = {l1, l2};
        ListNode merged = mergeKLists(lists);        StringBuilder sb = new StringBuilder();        while (merged != null) {            sb.append(merged.val).append(" ");            merged = merged.next;        }        System.out.println("Merged: " + sb.toString().trim());    }}
Output
Merged: 1 2 4 6

What this code does

  • Min-heap maintains the heads of all K lists.
  • Extracting the minimum and inserting its next pointer takes O(log K) time per node.
  • Processes all N total nodes in O(N log K) time and O(K) auxiliary space.

Translating messy real-world descriptions into canonical models

Real-world coding prompts deliberately disguise standard algorithmic patterns in narrative storytelling. Learning to strip away the narrative veneer reveals the underlying classic problem.

Example 2 · Trapping Rain Water via Two Pointers

TrappingRainWaterDemo.javaJava
public class TrappingRainWaterDemo {    public static int trap(int[] height) {        if (height == null || height.length <= 2) return 0;        int left = 0, right = height.length - 1;        int leftMax = 0, rightMax = 0;        int water = 0;
        while (left < right) {            if (height[left] < height[right]) {                if (height[left] >= leftMax) leftMax = height[left];                else water += leftMax - height[left];                left++;            } else {                if (height[right] >= rightMax) rightMax = height[right];                else water += rightMax - height[right];                right--;            }        }        return water;    }
    public static void main(String[] args) {        int[] h = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};        System.out.println("Trapped water: " + trap(h)); // 6    }}
Output
Trapped water: 6

What this code does

  • Left and right pointers advance inward based on the smaller wall height.
  • Traps 6 total units of water between elevation towers.
  • Achieves optimal O(N) time with strictly O(1) auxiliary space.

Example 3 · Course Schedule II: Full Topological Order

CourseScheduleTwoDemo.javaJava
import java.util.*;
public class CourseScheduleTwoDemo {    public static int[] findOrder(int numCourses, int[][] prerequisites) {        List<List<Integer>> adj = new ArrayList<>();        for (int i = 0; i < numCourses; i++) adj.add(new ArrayList<>());        int[] inDegree = new int[numCourses];
        for (int[] p : prerequisites) {            adj.get(p[1]).add(p[0]);            inDegree[p[0]]++;        }
        Queue<Integer> q = new ArrayDeque<>();        for (int i = 0; i < numCourses; i++) {            if (inDegree[i] == 0) q.offer(i);        }
        int[] order = new int[numCourses];        int idx = 0;
        while (!q.isEmpty()) {            int cur = q.poll();            order[idx++] = cur;            for (int next : adj.get(cur)) {                if (--inDegree[next] == 0) q.offer(next);            }        }        return idx == numCourses ? order : new int[0];    }
    public static void main(String[] args) {        int[][] pre = {{1, 0}};        System.out.println("Order for 2 courses: " + Arrays.toString(findOrder(2, pre)));    }}
Output
Order for 2 courses: [0, 1]

What this code does

  • Course 0 has in-degree 0 and is processed first.
  • Course 1 has prerequisite 0 and is processed second.
  • Returns valid ordering [0, 1] in O(V + E) time.

For example, 'determining if a network of computers can communicate after a cable cut' is simply Disjoint Set Union or connected component counting via DFS. 'Finding the maximum water trapped between elevation bars' is the two-pointer or monotonic stack pattern. 'Finding the alien alphabet order given a sorted dictionary' is Kahn's topological sort over character adjacency lists. When reading a prompt, immediately underline the inputs, outputs, and constraints. Rephrase the problem in pure computer science terminology before discussing your approach with the interviewer.

Interview communication and trade-off defense

Technical interviews evaluate how you think, communicate, and handle feedback just as much as your code. Follow a disciplined 5-stage communication framework:

  1. Clarify constraints: ask about nulls, empty inputs, negative values, duplicates, and scale (e.g. max N).
  2. Propose brute force first: state the naive quadratic or exponential baseline so the interviewer knows you have a working fallback.
  3. Identify the bottleneck: explain why brute force is slow (e.g. redundant recalculations or repeated scans) and introduce the optimal structure.
  4. Implement cleanly: write modular code with meaningful variable names and helper functions.
  5. Dry run edge cases: trace execution with a sample input and test boundaries before announcing you are finished.

Next step

Check your understanding

10 quick questions