Skip to lesson

Frequently Asked Problem Types by Data Structure

Most coding questions are variations of a few dozen classic problems, and the interviewer's first test is whether you recognise which one they gave you. A quick "this smells like a sliding window" tells them you have practised by pattern, not by luck.

Arrays, strings, hashing, two pointers and sliding window: the fresher favourites

A sliding window is a moving range over contiguous elements, updated in O(1) per step by adding the new element and dropping the old one.

Most campus rounds ask array and string problems that avoid O(n²). Example 1 solves three in O(n): a window sum, a two-pointer palindrome check and a first-repeat search with a set.

Example 1 · Three fresher favourites in one file

FresherFavouritesDemo.javaJava
import java.util.HashSet;import java.util.Set;
public class FresherFavouritesDemo {    // Sliding window: best total sales over any k consecutive days    static int maxWindowSum(int[] a, int k) {        int window = 0;        for (int i = 0; i < k; i++) window += a[i];        int best = window;        for (int i = k; i < a.length; i++) {            window += a[i] - a[i - k];   // add the new day, drop the oldest            best = Math.max(best, window);        }        return best;    }
    // Two pointers: palindrome check    static boolean isPalindrome(String s) {        int left = 0, right = s.length() - 1;        while (left < right) {            if (s.charAt(left++) != s.charAt(right--)) return false;        }        return true;    }
    static char firstRepeated(String s) {        Set<Character> seen = new HashSet<>();        for (char c : s.toCharArray()) {            if (!seen.add(c)) return c;        }        return '_';    }
    public static void main(String[] args) {        System.out.println("max 3-day sales: " + maxWindowSum(new int[] {2, 1, 5, 1, 3, 2}, 3));        System.out.println("madam palindrome? " + isPalindrome("madam"));        System.out.println("first repeat in programming: " + firstRepeated("programming"));    }}
Output
max 3-day sales: 9
madam palindrome? true
first repeat in programming: r

What this code does

  • Each solution is O(n) and avoids the obvious O(n²) or O(n · k) brute force: the window slides, the pointers meet in the middle, and the set remembers what was seen.
  • These three shapes (slide a window, walk inwards, remember in a set) solve a large share of fresher-round questions.

Service-company and many campus rounds mostly ask these patterns and classic problem names:

  • Arrays and strings: second largest, reverse words, rotate array, move zeroes, maximum subarray (Kadane), best time to buy and sell stock.
  • Hashing: two sum, first non-repeating character, valid anagram, group anagrams, longest consecutive sequence, subarray sum equals k.
  • Two pointers: valid palindrome, pair sum in sorted array, remove duplicates from sorted array, container with most water, three sum.
  • Sliding window: maximum sum of k consecutive elements, longest substring without repeating characters, minimum window substring.

Revise: The sliding window idea (opens in a new tab), pair sum on a sorted array (opens in a new tab) and HashMap patterns (opens in a new tab).

Exact question choice varies by company and year; treat these lists as common patterns, not a guarantee.

Linked lists, stacks and queues, trees, graphs, heaps: the classic list

A monotonic stack is a stack kept in increasing or decreasing order, used to find the next greater or smaller element for every position in O(n).

Each data structure has a short list of questions that keeps coming back. Examples 2 and 3 show the core move of each: reverse a list, find its middle, next greater element, level order and top k.

Example 2 · Linked list and stack classics

ListStackClassicsDemo.javaJava
import java.util.ArrayDeque;import java.util.Arrays;import java.util.Deque;
class Node {    int val;    Node next;
    Node(int val) {        this.val = val;    }}
public class ListStackClassicsDemo {    static Node build(int... vals) {        Node dummy = new Node(0), tail = dummy;        for (int v : vals) {            tail.next = new Node(v);            tail = tail.next;        }        return dummy.next;    }
    static String show(Node head) {        StringBuilder sb = new StringBuilder();        for (Node n = head; n != null; n = n.next) sb.append(n.val).append(n.next != null ? " -> " : "");        return sb.toString();    }
    static Node reverse(Node head) {        Node prev = null;        while (head != null) {            Node next = head.next;            head.next = prev;            prev = head;            head = next;        }        return prev;    }
    static int middle(Node head) {          // slow moves 1, fast moves 2        Node slow = head, fast = head;        while (fast != null && fast.next != null) {            slow = slow.next;            fast = fast.next.next;        }        return slow.val;    }
    static int[] nextGreater(int[] a) {     // monotonic stack of indexes        int[] result = new int[a.length];        Arrays.fill(result, -1);        Deque<Integer> stack = new ArrayDeque<>();        for (int i = 0; i < a.length; i++) {            while (!stack.isEmpty() && a[stack.peek()] < a[i]) {                result[stack.pop()] = a[i];            }            stack.push(i);        }        return result;    }
    public static void main(String[] args) {        System.out.println("reversed: " + show(reverse(build(1, 2, 3, 4, 5))));        System.out.println("middle of 1..5: " + middle(build(1, 2, 3, 4, 5)) + ", of 1..6: " + middle(build(1, 2, 3, 4, 5, 6)));        System.out.println("next greater of [4, 5, 2, 25]: " + Arrays.toString(nextGreater(new int[] {4, 5, 2, 25})));    }}
Output
reversed: 5 -> 4 -> 3 -> 2 -> 1
middle of 1..5: 3, of 1..6: 4
next greater of [4, 5, 2, 25]: [5, 25, 25, -1]

What this code does

  • Reversing with three pointers (prev, head, next) and finding the middle with slow and fast pointers are the two linked-list moves most questions build on.
  • The monotonic stack keeps indexes whose next greater value is still unknown; each index is pushed and popped once, so it is O(n).

Example 3 · Tree BFS, height and a heap for k largest

TreeHeapClassicsDemo.javaJava
import java.util.ArrayDeque;import java.util.ArrayList;import java.util.List;import java.util.PriorityQueue;import java.util.Queue;
class TreeNode {    int val;    TreeNode left, right;
    TreeNode(int val, TreeNode left, TreeNode right) {        this.val = val;        this.left = left;        this.right = right;    }
    TreeNode(int val) {        this(val, null, null);    }}
public class TreeHeapClassicsDemo {    static int height(TreeNode root) {        if (root == null) return 0;        return 1 + Math.max(height(root.left), height(root.right));    }
    static List<List<Integer>> levelOrder(TreeNode root) {        List<List<Integer>> levels = new ArrayList<>();        Queue<TreeNode> queue = new ArrayDeque<>();        if (root != null) queue.offer(root);        while (!queue.isEmpty()) {            List<Integer> level = new ArrayList<>();            for (int size = queue.size(); size > 0; size--) {                TreeNode node = queue.poll();                level.add(node.val);                if (node.left != null) queue.offer(node.left);                if (node.right != null) queue.offer(node.right);            }            levels.add(level);        }        return levels;    }
    static List<Integer> kLargest(int[] a, int k) {        PriorityQueue<Integer> minHeap = new PriorityQueue<>();        for (int x : a) {            minHeap.offer(x);            if (minHeap.size() > k) minHeap.poll();   // drop the smallest        }        List<Integer> result = new ArrayList<>(minHeap);        result.sort(null);        return result;    }
    public static void main(String[] args) {        TreeNode root = new TreeNode(8,                new TreeNode(3, new TreeNode(1), new TreeNode(6)),                new TreeNode(10, null, new TreeNode(14)));        System.out.println("height: " + height(root));        System.out.println("levels: " + levelOrder(root));        System.out.println("3 largest of [3, 1, 5, 12, 2, 11]: " + kLargest(new int[] {3, 1, 5, 12, 2, 11}, 3));    }}
Output
height: 3
levels: [[8], [3, 10], [1, 6, 14]]
3 largest of [3, 1, 5, 12, 2, 11]: [5, 11, 12]

What this code does

  • Height is the standard recursive tree pattern; level order is BFS with a queue, processing one level per size loop.
  • A min-heap of size k keeps the k largest values seen so far in O(n log k), better than sorting everything when k is small.

Product companies and harder campus rounds add these classics:

  • Linked lists: reverse a list, find the middle (slow and fast pointers), detect a cycle, merge two sorted lists, remove the nth node from the end.
  • Stacks and queues: valid parentheses, next greater element (monotonic stack), min stack, implement a queue using two stacks.
  • Trees: height, level-order traversal (BFS), validate a BST, lowest common ancestor, diameter, path sum.
  • Graphs and heaps: number of islands, BFS shortest path in a grid, course schedule (topological sort); k largest elements, merge k sorted lists, top k frequent.

Revise: Fast and slow pointers (opens in a new tab), monotonic stack (opens in a new tab), BFS (opens in a new tab) and top k problems (opens in a new tab).

Predict the output

Run the classics by hand

Trace each classic on a small input, then choose what it prints.

Round 1 of 2

Brute-force next greater element. What does it print?

int[] a = {6, 8, 0, 1, 3};
int[] result = new int[a.length];
for (int i = 0; i < a.length; i++) {
result[i] = -1;
for (int j = i + 1; j < a.length; j++) {
if (a[j] > a[i]) { result[i] = a[j]; break; }
}
}
System.out.println(Arrays.toString(result));

DP and recursion questions at product companies

Dynamic programming solves a problem by combining answers to smaller, overlapping subproblems and storing them, so each one is solved only once.

A DP answer is best presented as a recurrence first. Example 4 solves stairs, coin change and longest increasing subsequence bottom-up, each with a one-line recurrence.

Example 4 · Three DP classics, bottom-up

DpClassicsDemo.javaJava
import java.util.Arrays;
public class DpClassicsDemo {    // Ways to climb n stairs taking 1 or 2 steps    static int climbStairs(int n) {        int a = 1, b = 1;                 // ways to reach steps 0 and 1        for (int i = 2; i <= n; i++) {            int c = a + b;            a = b;            b = c;        }        return b;    }
    // Fewest coins to make the amount, or -1    static int coinChange(int[] coins, int amount) {        int[] dp = new int[amount + 1];        Arrays.fill(dp, Integer.MAX_VALUE);        dp[0] = 0;        for (int x = 1; x <= amount; x++) {            for (int c : coins) {                if (c <= x && dp[x - c] != Integer.MAX_VALUE) {                    dp[x] = Math.min(dp[x], dp[x - c] + 1);                }            }        }        return dp[amount] == Integer.MAX_VALUE ? -1 : dp[amount];    }
    static int lis(int[] a) {        int[] len = new int[a.length];        int best = 0;        for (int i = 0; i < a.length; i++) {            len[i] = 1;            for (int j = 0; j < i; j++) {                if (a[j] < a[i]) len[i] = Math.max(len[i], len[j] + 1);            }            best = Math.max(best, len[i]);        }        return best;    }
    public static void main(String[] args) {        System.out.println("climb 5 stairs: " + climbStairs(5) + " ways");        System.out.println("coins {1, 2, 5} for 11: " + coinChange(new int[] {1, 2, 5}, 11));        System.out.println("coins {2} for 3: " + coinChange(new int[] {2}, 3));        System.out.println("LIS of [10, 9, 2, 5, 3, 7, 101, 18]: " + lis(new int[] {10, 9, 2, 5, 3, 7, 101, 18}));    }}
Output
climb 5 stairs: 8 ways
coins {1, 2, 5} for 11: 3
coins {2} for 3: -1
LIS of [10, 9, 2, 5, 3, 7, 101, 18]: 4

What this code does

  • Each has a one-line recurrence: ways(n) = ways(n - 1) + ways(n - 2); coins(x) = 1 + min over c of coins(x - c); lis(i) = 1 + max lis(j) for smaller earlier values.
  • Saying the recurrence first, then filling the table bottom-up, is the clearest way to present DP in an interview.

Recursion and backtracking explore choices one by one and undo them. Both they and DP appear mostly in product-company and higher-package rounds. In the interview, start with the recursive idea and its repeated subproblems, then add memoization or a bottom-up table, and state the complexity of the table. Revise: The DP recipe (opens in a new tab) and backtracking (opens in a new tab)

The usual questions:

  • 1D DP: climbing stairs, house robber, coin change (minimum coins and number of ways), longest increasing subsequence.
  • 2D DP: longest common subsequence, edit distance, unique paths in a grid, 0/1 knapsack.
  • Recursion and backtracking: subsets, permutations, combination sum, N-Queens, word search in a grid.

Order of execution

Present a DP solution

Put the spoken steps of a strong DP answer in order.

Where to practise each in Section 7 Coding Challenges

Practise by pattern, not at random. Example 5 turns a list of weak areas into a two-week plan using the Section 7 module names, a list you can adapt and keep.

Example 5 · Turning weak areas into a Section 7 practice plan

PracticePlanDemo.javaJava
import java.util.LinkedHashMap;import java.util.List;import java.util.Map;
public class PracticePlanDemo {    static final Map<String, List<String>> MODULES = new LinkedHashMap<>();
    static {        MODULES.put("sliding window", List.of("Sliding Window Challenges", "Prefix Sum & Hashing Challenges"));        MODULES.put("trees", List.of("Binary Tree Challenges", "BST Challenges"));        MODULES.put("dp", List.of("1D DP Challenges", "2D DP Challenges"));        MODULES.put("graphs", List.of("Graph Traversal Challenges", "Graph Algorithm Challenges"));        MODULES.put("recognition", List.of("Mixed Pattern Challenges", "Mixed DSA Challenges"));    }
    public static void main(String[] args) {        List<String> weakAreas = List.of("sliding window", "dp");   // from your mock rounds        int day = 1;        for (String area : weakAreas) {            for (String module : MODULES.get(area)) {                System.out.println("Days " + day + "-" + (day + 1) + ": " + module + " (" + area + ")");                day += 2;            }        }        for (String module : MODULES.get("recognition")) {            System.out.println("Day " + day + ": " + module + " (mixed, timed)");            day++;        }        System.out.println("Days " + day + "-14: redo every problem you could not solve alone");    }}
Output
Days 1-2: Sliding Window Challenges (sliding window)
Days 3-4: Prefix Sum & Hashing Challenges (sliding window)
Days 5-6: 1D DP Challenges (dp)
Days 7-8: 2D DP Challenges (dp)
Day 9: Mixed Pattern Challenges (mixed, timed)
Day 10: Mixed DSA Challenges (mixed, timed)
Days 11-14: redo every problem you could not solve alone

What this code does

  • Weak patterns get most of the days, and the mixed modules come after them to practise recognising the pattern without a hint from the module title.
  • The last four days go to redoing unsolved problems from memory, which is where most of the learning happens. Change the weak areas and day counts to fit your own calendar.

Spend most time on your weakest two patterns, and use the mixed modules to practise recognising a pattern without a hint:

  • Fresher favourites: Array & String, Two Pointer, Sliding Window, Prefix Sum & Hashing, Binary Search Challenges.
  • Data structures: Linked List, Stack & Queue, Hash Table, Binary Tree, BST, Heap & Trie, Graph Traversal Challenges.
  • Product-company level: Recursion, Backtracking, 1D DP, 2D DP, Greedy & Interval, Graph Algorithm Challenges.
  • Recognition practice: Mixed Pattern Challenges and Mixed DSA Challenges.

Revise: Spotting the pattern (opens in a new tab)

Pattern-recognition cues from the problem statement

A pattern cue is a word or shape in a problem statement that points to a standard technique, such as "sorted" pointing to two pointers or binary search.

Certain words in a statement point to a pattern. Read the statement once for meaning, then once for cues, and say the pattern you suspect aloud with the reason. Cues are hints, not rules: always check the constraints too.

  • "Contiguous subarray or substring" with a condition on its sum or contents → sliding window (or prefix sums with hashing if values can be negative).
  • "Sorted array", "pair or triplet" → two pointers; "sorted" plus "find", or "minimum value that works" → binary search.
  • "Count", "frequency", "seen before", "duplicate" → hashing; "range sum queries" → prefix sums.
  • "Next greater or smaller" → monotonic stack; "k largest", "k closest", "stream" → heap; "intervals", "meetings" → sort plus greedy.
  • "Shortest path" in an unweighted grid or graph → BFS; "dependencies" or "order of tasks" → topological sort; "all combinations or arrangements" → backtracking; "number of ways" or "minimum cost" with overlapping choices → DP.

Find the bug

Spot the wrong cue

Each list matches statements to patterns. Click the line with the wrong pattern.

One cue is wrong.

Round 1 of 3

Next step

Check your understanding

12 quick questions