LeetCode Pattern Map — Interactive

Quick Access Problems

Study Roadmap & Pattern Recognition Guide

1. Sum / Pair Patterns (Two Sum Family)

In-Depth Explanation

This pattern focuses on finding pairs or groups of numbers in an array summing to a target. It's a cornerstone for FAANG interviews due to its versatility.

  • Core Concept: Identify pairs (2-sum), triplets (3-sum), or k-elements summing to a target. Start with brute force O(n²) for pairs, optimize to O(n) using hash maps (store complements: target - num) or O(n log n) with sorting + two pointers.
  • Extensions: k-sum reduces to (k-1)-sum recursively. Handle duplicates via sorting and skipping identical elements or using sets for unique results.
  • FAANG Focus: Variations like closest sum, count occurrences, or handling negatives. Tests ability to optimize and manage edge cases (duplicates, zeros).
Recognition Cues & Interviewer Hints
  • Cues: Look for phrases like "find pairs/triplets summing to target," "unique combinations," or "closest sum to target."
  • Interviewer Hints:
    • "Can you do better than O(n²)?" → Suggests hash map or sort + pointers.
    • "How do you handle duplicates?" → Skip identical values after sorting.
    • "Is the array sorted?" → If yes, use pointers; if no, hash or sort first.
  • Break the Problem: Ask clarifying questions like:
    • Are negative numbers allowed?
    • Return indices or values?
    • Handle duplicates or ensure unique results?
What Interviewer Will Ask
  • Compare time/space trade-offs (hash vs. pointers).
  • Handle large inputs (avoid O(n^k) for k>2).
  • Prove correctness of duplicate handling.
  • Modify for counting solutions or finding closest sum.
Revision Routine
  • Start with brute force O(n²) nested loops.
  • Optimize to hash map or sort + two pointers.
  • Dry-run: [2,7,11,15] target=9 → [(2,7)].
  • Analyze: O(n) time (hash), O(n) space or O(n log n) time (sort), O(1) space.
  • Edges: All zeros, negatives, no solution, duplicates.
Problem Description Approach Comparison Complexity LeetCode Link Blog Reference
Two Sum (LC1) Find indices of two numbers summing to target (one solution).
  • Brute: Nested loops check all pairs O(n²).
  • Hash: One-pass complement lookup (target-num) O(n) time/space.
  • Sort+Pointers: O(n log n) but loses indices.
O(n) time, O(n) space (hash) LC1 Two Sum Pattern (LC1)
Two Sum II (LC167) Sorted array, return 1-indexed positions.
  • Hash: O(n) time but O(n) space.
  • Pointers: Converge from ends, O(n) time, O(1) space.
  • Brute: O(n²) too slow.
O(n) time, O(1) space (pointers) LC167 Two Sum II (LC167)
3Sum (LC15) Unique triplets summing to 0.
  • Brute: O(n³) check all triplets.
  • Sort+Pointers: Fix i, use pointers for -nums[i], skip dups O(n²).
  • Hash: O(n²) time but O(n) space for pairs.
O(n²) time, O(1) space LC15 3Sum (LC15)
3Sum Closest (LC16) Triplet sum closest to target.
  • Brute: O(n³) check all.
  • Sort+Pointers: Track min diff, O(n²).
  • Hash: Less efficient due to space.
O(n²) time, O(1) space LC16 3Sum Closest (LC16)
4Sum (LC18) Unique quadruplets to target.
  • Brute: O(n⁴) check all.
  • Sort+Double Loops: Fix two, pointers for rest O(n³).
  • Recursive k-sum: Flexible but same complexity.
O(n³) time, O(1) space LC18 DSA Prep Guide (Medium)

FAANG Prep Tips: Generalize to k-sum via recursion or loops. Discuss trade-offs for large k (time vs. readability). Practice edge cases like duplicates, negatives, or no solutions to ensure robust code.

2. Sliding Window (Fixed & Variable)

In-Depth Explanation

Optimizes subarray or substring problems by maintaining a window, avoiding redundant scans. Critical for FAANG due to O(n) efficiency.

  • Fixed Window: Constant size k, slide right, update by subtracting left, adding right (e.g., max sum of k elements).
  • Variable Window: Expand right, shrink left when condition fails (e.g., duplicates, sum > target). Use hashmap for counts, deque for monotonic order.
  • FAANG Focus: Combines with prefix sums or monotonic queues. Tests ability to adapt to min/max windows, handle constraints like character sets.
Recognition Cues & Interviewer Hints
  • Cues: "Longest/shortest subarray with property," "max sum of k elements," "substring with no repeats."
  • Interviewer Hints:
    • "Can you solve in one pass?" → Single-pass window.
    • "What if k is given?" → Fixed window.
    • "Handle dynamic size?" → Variable window with hash/deque.
  • Break the Problem: Ask:
    • Fixed or variable window?
    • Constraints on elements (chars, numbers)?
    • Return length or substring?
What Interviewer Will Ask
  • Prove O(n) (each element added/removed once).
  • Handle invalid windows or edge cases.
  • Adapt to min/max or 2D windows.
  • Space trade-offs for hash/deque.
Revision Routine
  • Brute: O(n²) check all substrings.
  • Optimize: Window single pass O(n).
  • Dry-run: "abcabcbb" no repeat → "abc" (len=3).
  • Analyze: O(n) time, O(1) space (fixed alphabet).
  • Edges: All same chars, empty input, single char.
Problem Description Approach Comparison Complexity LeetCode Link Blog Reference
Max Sum Subarray of Size K Max sum in fixed k subarray.
  • Brute: Sum each k-window O(nk).
  • Fixed Window: Maintain sum, slide O(n).
O(n) time, O(1) space GFG DSA Prep Guide (Easy)
Find All Anagrams (LC438) Indices of anagrams of p in s.
  • Brute: Sort each window O(n k log k).
  • Fixed Window: Count hash, slide update O(n).
O(n) time, O(1) space LC438 Anagrams in a String (LC438)
Min Window Substring (LC76) Shortest substring with all chars from t.
  • Brute: Check all substrings O(n²).
  • Variable Window: Expand/shrink with hash O(n).
O(n) time, O(1) space LC76 Min Window Substring (LC76)
Longest No Repeat (LC3) Longest substring no repeats.
  • Set+Window: Shrink on dup O(n).
  • Hash+Jump: Move left to last dup O(n).
O(n) time, O(1) space LC3 DSA Prep Guide (Medium)

FAANG Prep Tips: Master variable windows for strings, fixed for arrays. Combine with monotonic queues for max/min. Interviewers may ask for 2D windows or constrained sums (e.g., sum <= k).

3. Prefix Sum & Monotonic Queue

In-Depth Explanation

Optimizes range-based or window-based array problems. Frequently used in FAANG for subarray sums or window extrema.

  • Prefix Sum: Precompute cumulative sums for O(1) range queries (sum[i..j] = prefix[j] - prefix[i-1]).
  • Monotonic Queue: Deque maintaining increasing/decreasing order for window max/min, pop invalid or smaller elements.
  • FAANG Focus: Combines with hash for sum = k, or with sliding windows for dynamic ranges. Tests optimization and edge handling.
Recognition Cues & Interviewer Hints
  • Cues: "Count subarrays with sum = k," "range sum queries," "max in sliding window."
  • Interviewer Hints:
    • "Can you precompute?" → Prefix sum.
    • "Efficient window max?" → Monotonic deque.
    • "Handle multiple queries?" → Prefix or segment tree.
  • Break the Problem: Ask:
    • Multiple range queries?
    • Negative numbers or modulo?
    • Window size fixed or variable?
What Interviewer Will Ask
  • Prove O(n) for deque (each element pushed/popped once).
  • Handle negatives/zero in prefix sums.
  • Extend to 2D prefix sums for matrices.
  • Space trade-offs for hash or deque.
Revision Routine
  • Brute: O(n²) nested sums.
  • Optimize: Prefix O(n) build, O(1) query; deque O(n).
  • Dry-run: [1,2,3] range 1-2 → 5.
  • Analyze: O(n) time, O(n) space (prefix/deque).
  • Edges: Negatives, k=0, empty array.
Problem Description Approach Comparison Complexity LeetCode Link Blog Reference
Subarray Sum = K (LC560) Count subarrays summing to k.
  • Brute: O(n²) check all subarrays.
  • Prefix+Hash: Count (prefix - k) O(n).
O(n) time, O(n) space LC560 Subarray Sum Equals K (LC560)
Range Sum Query (LC303) Multiple range sum queries.
  • Brute: O(n) per query.
  • Prefix: O(n) build, O(1) query.
O(1) query, O(n) space LC303 DSA Prep Guide (Easy)
Sliding Window Max (LC239) Max in k-windows.
  • Heap: O(n log k).
  • Monotonic Deque: O(n), pop smaller/out-window.
O(n) time, O(k) space LC239 Sliding Window Maximum (LC239)
Continuous Subarray Sum (LC523) Subarray sum multiple of k.
  • Brute: O(n²) check all.
  • Prefix Mod+Hash: Store first mod k O(n).
O(n) time, O(k) space LC523 DSA Prep Guide (Medium)

FAANG Prep Tips: Extend prefix to 2D for matrix problems. For monotonic, practice both increasing/decreasing deques. Interviewers test proof of O(n) (each element processed once).

4. Two-Pointer Family & k-Sum

In-Depth Explanation

Uses two pointers converging on sorted data (or same start for unsorted). Key for FAANG due to O(n) or O(n²) efficiency.

  • Two Pointers: Start at ends (sorted) or same (unsorted), move based on sum/condition (e.g., sum < target → move left).
  • k-Sum: Sort, fix k-2 elements, solve 2-sum with pointers. Skip duplicates for unique results.
  • FAANG Focus: Often requires sorting unsorted inputs. Tests ability to handle duplicates, closest sums, or extensions to k>2.
Recognition Cues & Interviewer Hints
  • Cues: "Find pairs in sorted array," "unique triplets," "closest sum."
  • Interviewer Hints:
    • "Use sorted property?" → Pointers.
    • "Handle duplicates?" → Skip identical values.
    • "Unsorted input?" → Sort first, discuss O(n log n).
  • Break the Problem: Ask:
    • Is input sorted?
    • Return count, values, or indices?
    • Handle large k?
What Interviewer Will Ask
  • Why sort first? (Enables pointers).
  • Handle duplicates/overflow.
  • Extend to k-sum for k>4 (recursive).
  • Time complexity for large n.
Revision Routine
  • Brute: O(n^k) combinations.
  • Optimize: Sort+Pointers O(n^{k-1}).
  • Dry-run: [1,3,4,6] sum=7 → [(1,6)].
  • Analyze: O(n²) for 3-sum, O(1) space.
  • Edges: All same, negatives, no solution.
Problem Description Approach Comparison Complexity LeetCode Link Blog Reference
Container Water (LC11) Max area between height lines.
  • Brute: O(n²) check all pairs.
  • Pointers: Move shorter height O(n).
O(n) time, O(1) space LC11 DSA Prep Guide (Medium)
Two Sum II (LC167) Sorted, indices for target.
  • Hash: O(n) time, O(n) space.
  • Pointers: O(n) time, O(1) space.
O(n) time, O(1) space LC167 Two Sum II (LC167)
3Sum (LC15) Unique triplets to 0.
  • Hash: O(n²) time, O(n) space.
  • Sort+Pointers: O(n²) time, O(1) space, skip dups.
O(n²) time, O(1) space LC15 3Sum (LC15)
3Sum Closest (LC16) Triplet sum closest to target.
  • Brute: O(n³).
  • Sort+Pointers: Track min diff O(n²).
O(n²) time, O(1) space LC16 3Sum Closest (LC16)

FAANG Prep Tips: Discuss recursive k-sum vs. loop-based for readability vs. performance. Handle unsorted inputs by justifying sort cost (O(n log n)).

5. Backtracking / Permutations

In-Depth Explanation

Explores all possible solutions via recursive DFS, backtracking on invalid branches. Common in FAANG for combinatorial problems.

  • Core Concept: Build solutions incrementally, revert on failure. Perms: Swap elements or use used flags. Subsets: Include/exclude choices.
  • Optimization: Prune branches early (constraints, duplicates). Sort for unique results.
  • FAANG Focus: Tests recursion depth, pruning, and sometimes DP overlap for memoization.
Recognition Cues & Interviewer Hints
  • Cues: "Generate all perms/combinations," "solve without libraries," small n (10-20).
  • Interviewer Hints:
    • "Explore all branches?" → Backtracking.
    • "Avoid duplicates?" → Sort or use set.
    • "Can you prune?" → Early constraint checks.
  • Break the Problem: Ask:
    • Unique or all solutions?
    • Constraints on n?
    • Duplicates in input?
What Interviewer Will Ask
  • Pruning techniques to reduce branches.
  • Handle duplicates for unique results.
  • Stack overflow for large n.
  • Convert to iterative approach.
Revision Routine
  • Brute: Recursive build all solutions.
  • Optimize: Prune dups, early checks.
  • Dry-run: [1,2] perms → [[1,2],[2,1]].
  • Analyze: O(n!) time, O(n) space.
  • Edges: Duplicates, large n, empty input.
Problem Description Approach Comparison Complexity LeetCode Link Blog Reference
Permutations (LC46) All unique permutations.
  • Swap: In-place swaps O(n!) time, O(1) space.
  • Build: Used array O(n!) time, O(n) space.
O(n!) time, O(n) space LC46 DSA Prep Guide (Medium)
Subsets (LC78) All unique subsets.
  • Backtrack: Include/exclude O(2^n).
  • Bitmask: O(2^n) iterative, faster for n≤20.
O(2^n) time, O(n) space LC78 DSA Prep Guide (Medium)
Letter Combinations (LC17) Phone digits to letters.
  • Backtrack: Per digit O(4^n).
  • BFS Queue: Build levels, same complexity.
O(4^n) time, O(n) space LC17 DSA Prep Guide (Medium)
N-Queens (LC51) Place n queens no attack.
  • Backtrack: Row-by-row, check cols/diags O(n!).
  • Bitmask: Optimized for small n.
O(n!) time, O(n) space LC51 DSA Prep Guide (Medium)

FAANG Prep Tips: Practice pruning (e.g., early constraint checks) to optimize. Interviewers may ask for memoization if subproblems overlap (DP transition).

6. Binary Search & Search-on-Answer

In-Depth Explanation

Binary search efficiently finds a target or boundary in sorted data or a monotonic search space. Critical for FAANG due to O(log n) efficiency.

  • Core Concept: Divide search space in half, leveraging sorted property or monotonicity. For search-on-answer, apply binary search to a range of possible answers (e.g., min capacity, max distance).
  • Variations: Standard (find target), boundary (find first/last occurrence), or answer search (test feasibility of mid value).
  • FAANG Focus: Tests ability to identify monotonicity in abstract problems (e.g., min days, max profit) and handle edge cases like duplicates or no solution.
Recognition Cues & Interviewer Hints
  • Cues: "Find target in sorted array," "minimum value satisfying condition," "first/last occurrence."
  • Interviewer Hints:
    • "Can you use the sorted property?" → Standard binary search.
    • "What if you guess the answer?" → Search-on-answer.
    • "Handle duplicates?" → Find first/last position.
  • Break the Problem: Ask:
    • Is input sorted?
    • Find exact target or boundary?
    • Monotonic condition in problem?
What Interviewer Will Ask
  • Prove O(log n) time (halving search space).
  • Handle edge cases (no target, duplicates).
  • Define monotonic function for search-on-answer.
  • Adapt to unsorted data (sort first or other approach).
Revision Routine
  • Brute: Linear scan O(n).
  • Optimize: Binary search O(log n).
  • Dry-run: [1,3,5,6] target=5 → index 2.
  • Analyze: O(log n) time, O(1) space.
  • Edges: Target not found, duplicates, single element.
Problem Description Approach Comparison Complexity LeetCode Link Blog Reference
Binary Search (LC704) Find target in sorted array.
  • Linear: O(n) scan.
  • Binary Search: O(log n) halve search space.
O(log n) time, O(1) space LC704 DSA Prep Guide (Easy)
First Bad Version (LC278) Find first bad version in range.
  • Linear: O(n) check each.
  • Binary Search: O(log n) find first true.
O(log n) time, O(1) space LC278 DSA Prep Guide (Easy)
Search Insert Position (LC35) Find target or insert position.
  • Linear: O(n) scan.
  • Binary Search: O(log n) return low pointer.
O(log n) time, O(1) space LC35 DSA Prep Guide (Easy)
Find Min in Rotated Array (LC153) Min in rotated sorted array.
  • Linear: O(n) scan.
  • Binary Search: O(log n) find pivot.
O(log n) time, O(1) space LC153 DSA Prep Guide (Medium)
Capacity to Ship (LC1011) Min capacity to ship in D days.
  • Brute: O(n*max) try all capacities.
  • Search-on-Answer: O(n log max) binary search capacity.
O(n log max) time, O(1) space LC1011 DSA Prep Guide (Medium)

FAANG Prep Tips: Practice search-on-answer for abstract problems (e.g., min days, max profit). Interviewers test ability to define monotonic function and handle edge cases like duplicates or no target.

7. Dynamic Programming 1D → 2D

In-Depth Explanation

Dynamic Programming (DP) solves problems by breaking them into overlapping subproblems, storing results to avoid recomputation. Essential for FAANG optimization problems.

  • 1D DP: Single state variable (e.g., index or sum). Build bottom-up or top-down (memoized recursion).
  • 2D DP: Two variables (e.g., row+col, index+state). Common for strings, matrices, or knapsack variants.
  • FAANG Focus: Tests state definition, transition logic, and space optimization (e.g., rolling arrays).
Recognition Cues & Interviewer Hints
  • Cues: "Optimal value," "count ways," "longest/shortest sequence," "matrix path."
  • Interviewer Hints:
    • "Break into smaller problems?" → DP subproblems.
    • "Store intermediate results?" → Memoization or bottom-up.
    • "Reduce space?" → Optimize to 1D array or variables.
  • Break the Problem: Ask:
    • Optimal or count all solutions?
    • Single or multiple states?
    • Constraints allow memoization?
What Interviewer Will Ask
  • Define state and transition formula.
  • Prove correctness of recurrence.
  • Optimize space (e.g., 1D instead of 2D).
  • Handle edge cases (empty, single element).
Revision Routine
  • Brute: Recursive O(2^n).
  • Optimize: DP table or memo O(n).
  • Dry-run: Climb stairs n=3 → 3 ways.
  • Analyze: O(n) time, O(n) or O(1) space.
  • Edges: Large n, constraints, base cases.
Problem Description Approach Comparison Complexity LeetCode Link Blog Reference
Climbing Stairs (LC70) Count ways to climb n stairs (1 or 2 steps).
  • Recursive: O(2^n) exponential.
  • 1D DP: dp[i] = dp[i-1] + dp[i-2] O(n).
  • Variables: O(1) space using two vars.
O(n) time, O(1) space LC70 DSA Prep Guide (Easy)
House Robber (LC198) Max money without robbing adjacent houses.
  • Recursive: O(2^n).
  • 1D DP: dp[i] = max(dp[i-1], dp[i-2] + nums[i]) O(n).
O(n) time, O(1) space LC198 DSA Prep Guide (Medium)
Longest Common Subsequence (LC1143) Longest common subsequence of two strings.
  • Recursive: O(2^n).
  • 2D DP: dp[i][j] based on match O(nm).
  • Rolling Array: O(min(n,m)) space.
O(nm) time, O(min(n,m)) space LC1143 DSA Prep Guide (Medium)
Knapsack 0/1 Max value within weight limit.
  • Recursive: O(2^n).
  • 2D DP: dp[i][w] include/exclude O(nW).
O(nW) time, O(W) space GFG DSA Prep Guide (Medium)
Unique Paths (LC62) Count paths in m×n grid.
  • Recursive: O(2^(m+n)).
  • 2D DP: dp[i][j] = dp[i-1][j] + dp[i][j-1] O(mn).
O(mn) time, O(mn) space LC62 DSA Prep Guide (Medium)

FAANG Prep Tips: Practice state transitions and space optimization (e.g., rolling arrays). Interviewers test ability to derive recurrence and handle large inputs or constraints.

8. Graphs — BFS / DFS Patterns

In-Depth Explanation

Graph traversal algorithms explore nodes and edges, critical for FAANG connectivity and path problems.

  • BFS: Level-order traversal using queue, ideal for shortest paths in unweighted graphs.
  • DFS: Deep exploration using recursion or stack, suited for detecting cycles, components, or paths.
  • FAANG Focus: Tests graph representation (adj list/matrix), traversal efficiency, and modifications (e.g., bipartite, shortest path).
Recognition Cues & Interviewer Hints
  • Cues: "Find shortest path," "detect cycle," "connected components," "flood fill."
  • Interviewer Hints:
    • "Need shortest path?" → BFS.
    • "Explore all paths?" → DFS.
    • "Graph representation?" → List vs. matrix trade-offs.
  • Break the Problem: Ask:
    • Weighted or unweighted graph?
    • Directed or undirected?
    • Sparse or dense graph?
What Interviewer Will Ask
  • Choose BFS vs. DFS based on problem.
  • Handle cycles or disconnected graphs.
  • Space/time trade-offs for adj list vs. matrix.
  • Modify for weighted graphs or constraints.
Revision Routine
  • Brute: Explore all paths O(V^V).
  • Optimize: BFS/DFS O(V+E).
  • Dry-run: 3-node cycle, detect cycle → true.
  • Analyze: O(V+E) time, O(V) space.
  • Edges: Disconnected, single node, cycles.
Problem Description Approach Comparison Complexity LeetCode Link Blog Reference
Number of Islands (LC200) Count islands in grid.
  • DFS: Flood fill sink islands O(mn).
  • BFS: Same complexity, level-order.
O(mn) time, O(mn) space LC200 DSA Prep Guide (Medium)
Course Schedule (LC207) Detect cycle in course prereqs.
  • DFS: Detect cycle via recursion stack O(V+E).
  • BFS: Topological sort with indegree O(V+E).
O(V+E) time, O(V) space LC207 DSA Prep Guide (Medium)
Rotting Oranges (LC994) Time to rot all oranges.
  • BFS: Level-order spread O(mn).
  • DFS: Less intuitive, same complexity.
O(mn) time, O(mn) space LC994 DSA Prep Guide (Medium)
Clone Graph (LC133) Deep copy of graph.
  • DFS: Recurse with hash map O(V+E).
  • BFS: Queue-based, same complexity.
O(V+E) time, O(V) space LC133 DSA Prep Guide (Medium)
Word Ladder (LC127) Shortest word transformation sequence.
  • BFS: Shortest path in word graph O(26*L*N).
  • DFS: Incorrect for shortest path.
O(26*L*N) time, O(N) space LC127 DSA Prep Guide (Medium)

FAANG Prep Tips: Master both BFS and DFS implementations. Interviewers test graph representation choice and modifications like weighted edges or bipartite checks.

9. Greedy Algorithms

In-Depth Explanation

Greedy algorithms make locally optimal choices to achieve a global optimum, common in FAANG for optimization problems.

  • Core Concept: At each step, choose the best option (e.g., max profit, min cost) without reconsidering past choices.
  • Key Insight: Works when local optimum leads to global (e.g., interval scheduling, fractional knapsack).
  • FAANG Focus: Tests ability to prove greedy choice is optimal and handle edge cases where greedy fails.
Recognition Cues & Interviewer Hints
  • Cues: "Maximize/minimize value," "schedule tasks," "select non-overlapping intervals."
  • Interviewer Hints:
    • "Best choice at each step?" → Greedy.
    • "Prove it’s optimal?" → Justify greedy property.
    • "When does greedy fail?" → Compare with DP.
  • Break the Problem: Ask:
    • Is local optimum globally optimal?
    • Sort input by what criterion?
    • Handle overlapping cases?
What Interviewer Will Ask
  • Prove greedy choice leads to global optimum.
  • Compare with DP for correctness.
  • Handle edge cases (e.g., equal intervals).
  • Optimize sorting or selection logic.
Revision Routine
  • Brute: Try all combinations O(2^n).
  • Optimize: Greedy O(n log n) with sorting.
  • Dry-run: Intervals [[1,2],[2,3]] → select 2.
  • Analyze: O(n log n) time, O(1) space.
  • Edges: Overlapping intervals, empty input.
Problem Description Approach Comparison Complexity LeetCode Link Blog Reference
Jump Game (LC55) Can reach last index via jumps.
  • DP: O(n²) check all jumps.
  • Greedy: Track max reach O(n).
O(n) time, O(1) space LC55 DSA Prep Guide (Medium)
Non-overlapping Intervals (LC435) Remove min intervals to avoid overlap.
  • DP: O(n²) select subsets.
  • Greedy: Sort by end, select non-overlap O(n log n).
O(n log n) time, O(1) space LC435 DSA Prep Guide (Medium)
Meeting Rooms II (LC253) Min rooms for meetings.
  • Brute: O(n²) check overlaps.
  • Greedy: Sort start/end, track rooms O(n log n).
O(n log n) time, O(n) space LC253 DSA Prep Guide (Medium)
Gas Station (LC134) Find starting point for circuit.
  • Brute: O(n²) try all starts.
  • Greedy: Track total and curr gas O(n).
O(n) time, O(1) space LC134 DSA Prep Guide (Medium)
Fractional Knapsack Max value with weight limit.
  • DP: O(nW) like 0/1 knapsack.
  • Greedy: Sort value/weight O(n log n).
O(n log n) time, O(1) space GFG DSA Prep Guide (Medium)

FAANG Prep Tips: Practice proving greedy choice (e.g., why earliest end works for intervals). Interviewers may ask to compare with DP or handle cases where greedy fails.

10. Heap / Priority Queue

In-Depth Explanation

Heap maintains max/min elements efficiently, ideal for problems requiring dynamic ordering. Common in FAANG for top-k or scheduling problems.

  • Core Concept: Min/max heap for O(log n) insert/delete, O(1) peek. Priority queue abstracts heap for custom ordering.
  • Applications: Top-k elements, merge sorted lists, scheduling tasks by priority.
  • FAANG Focus: Tests heap operations, custom comparators, and combining with other patterns (e.g., sliding window).
Recognition Cues & Interviewer Hints
  • Cues: "Top k elements," "merge sorted lists," "schedule tasks by priority."
  • Interviewer Hints:
    • "Need smallest/largest k?" → Heap.
    • "Dynamic updates?" → Priority queue.
    • "Custom ordering?" → Define comparator.
  • Break the Problem: Ask:
    • Min or max heap?
    • Size of k relative to n?
    • Dynamic insertions?
What Interviewer Will Ask
  • Why heap over sorting?
  • Handle custom priorities or ties.
  • Optimize for small k (e.g., selection).
  • Combine with other patterns (e.g., sliding window).
Revision Routine
  • Brute: Sort O(n log n).
  • Optimize: Heap O(n + k log n).
  • Dry-run: Top k=[4,5,6] k=2 → [5,6].
  • Analyze: O(n + k log n) time, O(n) space.
  • Edges: k=n, duplicates, empty input.
Problem Description Approach Comparison Complexity LeetCode Link Blog Reference
Kth Largest Element (LC215) Find kth largest in array.
  • Sort: O(n log n).
  • Min Heap: O(n + k log n).
  • Quickselect: O(n) average.
O(n + k log n) time, O(n) space LC215 DSA Prep Guide (Medium)
Merge k Sorted Lists (LC23) Merge k sorted linked lists.
  • Brute: Merge one-by-one O(kN).
  • Min Heap: O(N log k) for N total nodes.
O(N log k) time, O(k) space LC23 DSA Prep Guide (Medium)
Top K Frequent Elements (LC347) Top k frequent numbers.
  • Sort: O(n log n).
  • Heap: O(n log k) with frequency map.
O(n log k) time, O(n) space LC347 DSA Prep Guide (Medium)
Task Scheduler (LC621) Min time to complete tasks with cooldown.
  • Greedy: O(n log n) sort frequencies.
  • Heap: O(n log n) track tasks.
O(n log n) time, O(n) space LC621 DSA Prep Guide (Medium)
Find Median from Stream (LC295) Median of streaming numbers.
  • Sort: O(n log n) per insert.
  • Two Heaps: O(log n) insert, O(1) median.
O(log n) insert, O(n) space LC295 DSA Prep Guide (Medium)

FAANG Prep Tips: Practice custom comparators for priority queues. Interviewers test heap vs. sorting trade-offs and combinations with sliding windows or greedy approaches.

11. Trie

In-Depth Explanation

Trie (prefix tree) is a tree structure for efficient string operations, critical for FAANG problems involving prefixes or word searches.

  • Core Concept: Each node represents a character, paths form strings. Supports O(m) insert/search/delete, where m is string length.
  • Applications: Autocomplete, spell checker, prefix matching, word search in grids.
  • FAANG Focus: Tests ability to implement trie node structure, optimize space (e.g., bitmaps), and combine with DFS/BFS.
Recognition Cues & Interviewer Hints
  • Cues: "Search words with prefix," "autocomplete suggestions," "word search in grid."
  • Interviewer Hints:
    • "Efficient prefix search?" → Trie.
    • "Handle large dictionary?" → Optimize node structure.
    • "Combine with grid?" → Trie + DFS.
  • Break the Problem: Ask:
    • Prefix-based or full word?
    • Case-sensitive strings?
    • Space constraints?
What Interviewer Will Ask
  • Implement trie node and operations.
  • Optimize space (e.g., array vs. hash for children).
  • Handle edge cases (empty strings, no prefix).
  • Combine with other patterns (e.g., DFS for word search).
Revision Routine
  • Brute: Linear search O(n*m).
  • Optimize: Trie O(m) per operation.
  • Dry-run: Insert "cat", search "ca" → true.
  • Analyze: O(m) time, O(ALPHABET*m*N) space.
  • Edges: Empty strings, no matches, large alphabet.
Problem Description Approach Comparison Complexity LeetCode Link Blog Reference
Implement Trie (LC208) Insert, search, prefix search.
  • HashSet: O(m*n) search.
  • Trie: O(m) insert/search.
O(m) time, O(m*N) space LC208 DSA Prep Guide (Medium)
Word Search II (LC212) Find words in grid.
  • Brute: DFS per word O(mn*4^len).
  • Trie+DFS: O(mn*4^len) with prefix pruning.
O(mn*4^len) time, O(N) space LC212 DSA Prep Guide (Medium)
Add and Search Word (LC211) Search with wildcards.
  • Brute: Check all words O(n*m).
  • Trie+DFS: O(26^m) for wildcard.
O(26^m) time, O(m*N) space LC211 DSA Prep Guide (Medium)
Autocomplete System (LC642) Return top 3 suggestions.
  • Brute: Scan all O(n*m).
  • Trie+Heap: O(m + k log k) per query.
O(m + k log k) time, O(m*N) space LC642 DSA Prep Guide (Medium)
Prefix and Suffix Search (LC745) Search words by prefix/suffix.
  • Brute: O(n*m) scan.
  • Trie: O(m²) preprocessing, O(m) query.
O(m) query, O(m²*N) space LC745 DSA Prep Guide (Medium)

FAANG Prep Tips: Practice trie implementation with array vs. hash children. Interviewers test pruning (prefix-based) and combining with DFS or heap for complex queries.

12. Union-Find

In-Depth Explanation

Union-Find (Disjoint Set Union) efficiently manages group connectivity, vital for FAANG graph and clustering problems.

  • Core Concept: Maintains sets with union (merge) and find (root) operations. Optimizes with path compression and rank union for near O(1) operations.
  • Applications: Detect cycles, connected components, Kruskal’s MST, or grid percolation.
  • FAANG Focus: Tests implementation (array-based), optimization (path compression), and application to dynamic connectivity.
Recognition Cues & Interviewer Hints
  • Cues: "Detect cycle in graph," "group connected components," "merge regions."
  • Interviewer Hints:
    • "Track group membership?" → Union-Find.
    • "Optimize operations?" → Path compression, rank.
    • "Dynamic connectivity?" → Union-Find over DFS.
  • Break the Problem: Ask:
    • Number of merge operations?
    • Directed or undirected graph?
    • Need component sizes?
What Interviewer Will Ask
  • Implement Union-Find with optimizations.
  • Prove near O(1) with path compression.
  • Handle edge cases (single node, no merges).
  • Extend to weighted unions or component size.
Revision Routine
  • Brute: DFS per query O(V+E).
  • Optimize: Union-Find O(α(V)) amortized.
  • Dry-run: Merge 1-2, 2-3, check 1-3 → connected.
  • Analyze: O(α(V)) time, O(V) space.
  • Edges: Single node, all disconnected, large V.
Problem Description Approach Comparison Complexity LeetCode Link Blog Reference
Number of Provinces (LC547) Count connected components in graph.
  • DFS: O(V+E) traverse.
  • Union-Find: O(α(V)) merge/query.
O(α(V)) time, O(V) space LC547 DSA Prep Guide (Medium)
Graph Valid Tree (LC261) Check if edges form a valid tree.
  • DFS: O(V+E) cycle check.
  • Union-Find: O(α(V)) cycle detection.
O(α(V)) time, O(V) space LC261 DSA Prep Guide (Medium)
Redundant Connection (LC684) Find edge causing cycle.
  • DFS: O(V+E) complex.
  • Union-Find: O(α(V)) detect cycle.
O(α(V)) time, O(V) space LC684 DSA Prep Guide (Medium)
Accounts Merge (LC721) Merge accounts by emails.
  • DFS: O(N*K) traverse emails.
  • Union-Find: O(N*α(N)) group accounts.
O(N*α(N)) time, O(N) space LC721 DSA Prep Guide (Medium)
Number of Islands (LC200) Count islands in grid.
  • DFS: O(mn) flood fill.
  • Union-Find: O(mn*α(mn)) merge cells.
O(mn*α(mn)) time, O(mn) space LC200 DSA Prep Guide (Medium)

FAANG Prep Tips: Master path compression and rank union. Interviewers test applications like Kruskal’s MST or dynamic connectivity with large graphs.

13. Stack

In-Depth Explanation

Stack operates on LIFO (Last In, First Out), ideal for FAANG problems involving reversal, matching, or monotonic properties.

  • Core Concept: Push/pop in O(1). Used for parentheses matching, monotonic stacks (next greater/smaller), or backtracking.
  • Applications: Expression evaluation, validating sequences, finding next elements.
  • FAANG Focus: Tests stack implementation, monotonic stack optimization, and combining with other patterns (e.g., histograms).
Recognition Cues & Interviewer Hints
  • Cues: "Validate parentheses," "next greater element," "evaluate expression."
  • Interviewer Hints:
    • "Track last elements?" → Stack.
    • "Monotonic property?" → Monotonic stack.
    • "Reverse order processing?" → Stack.
  • Break the Problem: Ask:
    • Order of processing (LIFO)?
    • Monotonic requirement?
    • Combine with other structures?
What Interviewer Will Ask
  • Why stack over queue?
  • Optimize for monotonic stacks.
  • Handle edge cases (empty stack, invalid input).
  • Combine with other patterns (e.g., sliding window).
Revision Routine
  • Brute: O(n²) scan for each element.
  • Optimize: Stack O(n).
  • Dry-run: [2,1,5] next greater → [5,5,-1].
  • Analyze: O(n) time, O(n) space.
  • Edges: Empty stack, all equal elements.
Problem Description Approach Comparison Complexity LeetCode Link Blog Reference
Valid Parentheses (LC20) Check valid parentheses string.
  • Brute: O(n²) match pairs.
  • Stack: O(n) push/pop matching.
O(n) time, O(n) space LC20 DSA Prep Guide (Easy)
Next Greater Element I (LC496) Find next greater for each element.
  • Brute: O(n²) scan.
  • Monotonic Stack: O(n) pop smaller.
O(n) time, O(n) space LC496 DSA Prep Guide (Easy)
Largest Rectangle in Histogram (LC84) Max rectangle area in histogram.
  • Brute: O(n²) check all bars.
  • Monotonic Stack: O(n) track increasing heights.
O(n) time, O(n) space LC84 DSA Prep Guide (Medium)
Min Stack (LC155) Stack with O(1) min.
  • Brute: O(n) scan for min.
  • Two Stacks: O(1) track min.
O(1) operations, O(n) space LC155 DSA Prep Guide (Easy)
Evaluate Reverse Polish Notation (LC150) Evaluate postfix expression.
  • Brute: O(n²) parse.
  • Stack: O(n) process operands.
O(n) time, O(n) space LC150 DSA Prep Guide (Medium)

FAANG Prep Tips: Master monotonic stacks for next greater/smaller. Interviewers test stack vs. other structures and combinations with histograms or windows.

14. Divide and Conquer

In-Depth Explanation

Divide and Conquer splits problems into smaller subproblems, solves them, and combines results, common in FAANG for recursive algorithms.

  • Core Concept: Divide into subproblems, conquer recursively, merge solutions. Often used in sorting, tree, or array problems.
  • Applications: Merge sort, quicksort, binary tree processing, matrix multiplication.
  • FAANG Focus: Tests recursion design, merge logic, and optimization (e.g., in-place quicksort).
Recognition Cues & Interviewer Hints
  • Cues: "Sort array," "process tree recursively," "divide array into halves."
  • Interviewer Hints:
    • "Split into smaller problems?" → Divide and Conquer.
    • "How to merge results?" → Define merge step.
    • "Optimize recursion?" → Tail recursion or iterative.
  • Break the Problem: Ask:
    • How to split data?
    • Merge complexity?
    • Recursive depth constraints?
What Interviewer Will Ask
  • Define divide and merge steps.
  • Prove correctness of recursion.
  • Optimize space (e.g., in-place).
  • Handle edge cases (single element, unbalanced splits).
Revision Routine
  • Brute: O(n²) naive solution.
  • Optimize: Divide and Conquer O(n log n).
  • Dry-run: Merge sort [3,1,4] → [1,3,4].
  • Analyze: O(n log n) time, O(n) space.
  • Edges: Single element, sorted input, duplicates.
Problem Description Approach Comparison Complexity LeetCode Link Blog Reference
Merge Sort Sort array using divide and conquer.
  • Bubble Sort: O(n²).
  • Merge Sort: O(n log n) divide/merge.
O(n log n) time, O(n) space GFG DSA Prep Guide (Medium)
Majority Element (LC169) Find element appearing > n/2 times.
  • Hash: O(n) count.
  • Boyer-Moore (Divide): O(n) cancel pairs.
O(n) time, O(1) space LC169 DSA Prep Guide (Easy)
Construct BT from Pre/Inorder (LC105) Build binary tree from traversals.
  • Brute: O(n²) search.
  • Divide and Conquer: O(n) with hash.
O(n) time, O(n) space LC105 DSA Prep Guide (Medium)
Merge k Sorted Lists (LC23) Merge k sorted linked lists.
  • Brute: O(kN) merge one-by-one.
  • Divide and Conquer: O(N log k) pairwise merge.
O(N log k) time, O(1) space LC23 DSA Prep Guide (Medium)
Quickselect (LC215) Find kth smallest element.
  • Sort: O(n log n).
  • Quickselect: O(n) average divide.
O(n) average time, O(1) space LC215 DSA Prep Guide (Medium)

FAANG Prep Tips: Practice merge step optimization (e.g., in-place quicksort). Interviewers test recursion depth and handling unbalanced splits.

15. Bit Manipulation

In-Depth Explanation

Bit manipulation uses bitwise operations (AND, OR, XOR, shifts) for efficient computation, common in FAANG for low-level optimization.

  • Core Concept: Manipulate bits for arithmetic, set operations, or state encoding. XOR is key for finding unique elements, toggling bits.
  • Applications: Find missing numbers, count bits, subset generation, or power set.
  • FAANG Focus: Tests understanding of bitwise operators, optimization (e.g., O(1) space), and edge cases (e.g., negative numbers).
Recognition Cues & Interviewer Hints
  • Cues: "Find unique number," "count 1s," "generate subsets," "bitwise operations."
  • Interviewer Hints:
    • "Use bitwise operations?" → Bit manipulation.
    • "Avoid extra space?" → XOR or bit shifts.
    • "Handle large numbers?" → Consider sign bits.
  • Break the Problem: Ask:
    • Signed or unsigned numbers?
    • Single or multiple passes?
    • Bitwise constraints?
What Interviewer Will Ask
  • Explain bitwise operations (e.g., XOR properties).
  • Optimize space (e.g., O(1) with XOR).
  • Handle negative numbers or edge cases.
  • Combine with other patterns (e.g., DP).
Revision Routine
  • Brute: O(n) scan or hash.
  • Optimize: Bitwise O(n) or O(1).
  • Dry-run: [1,1,2] single number → 2 (XOR).
  • Analyze: O(n) time, O(1) space.
  • Edges: Negative numbers, zeros, single element.
Problem Description Approach Comparison Complexity LeetCode Link Blog Reference
Single Number (LC136) Find number appearing once.
  • Hash: O(n) space.
  • XOR: O(n) time, O(1) space.
O(n) time, O(1) space LC136 DSA Prep Guide (Easy)
Number of 1 Bits (LC191) Count 1s in binary number.
  • Loop: O(32) check each bit.
  • Bit Trick: O(1) using n&(n-1).
O(1) time, O(1) space LC191 DSA Prep Guide (Easy)
Reverse Bits (LC190) Reverse bits of 32-bit integer.
  • Brute: O(32) swap bits.
  • Bit Shift: O(1) optimized shifts.
O(1) time, O(1) space LC190 DSA Prep Guide (Easy)
Subset (LC78) Generate all subsets.
  • Backtrack: O(2^n).
  • Bitmask: O(2^n) using bits for include/exclude.
O(2^n) time, O(n) space LC78 DSA Prep Guide (Medium)
Sum of Two Integers (LC371) Add without + operator.
  • Math: O(1) standard add.
  • Bitwise: O(1) XOR for sum, AND for carry.
O(1) time, O(1) space LC371 DSA Prep Guide (Easy)

FAANG Prep Tips: Master XOR properties (e.g., a^a=0) and bit tricks (e.g., n&(n-1)). Interviewers test optimization and handling signed integers.