Quick 2 Knowledge: Handbook for All Patterns of DSA
"Master these 16 core patterns and 20+ canonical LeetCode templates before walking into any technical coding interview."
This handbook organizes the complete pattern taxonomy from foundational arrays to advanced trees, heaps, and graphs. Each pattern card provides the core intuition, clean Java implementation, time & space complexity, and the underlying "Why?" explanation.
Part 1: The 16 Core DSA Patterns Taxonomy
Complete Pattern Breakdown
| # | Pattern Category | Key Sub-Techniques & Classical Problems | Deep-Dive Guide |
|---|---|---|---|
| 1 | Arrays | Two Pointers, Sliding Window, Kadane's Algo, Binary Search, Prefix/Suffix Sum, Dutch National Flag, Merge Intervals | Array Guide |
| 2 | Strings | Pattern Searching (KMP), Anagrams, Sliding Window, Palindrome Verification, Hashing, StringBuilder, Longest Substring | Sliding Window |
| 3 | Hashing | Frequency Count, HashMap / HashSet, Two Sum, Group Anagrams, Subarray Sum = K, Distinct Elements | Array & Hash |
| 4 | Linked List | In-place Reversal, Cycle Detection (Floyd's Tortoise & Hare), Find Middle, Merge Two Sorted Lists, Remove Nth Node, LRU Cache | Linked List Guide |
| 5 | Stack | Stack Implementation, Infix to Postfix, Postfix Evaluation, Next Greater Element, Valid Parentheses, Min Stack, Stock Span | Stack Guide & Monotonic Stack |
| 6 | Queue | Circular Queue, Deque (Double Ended), Sliding Window Maximum, First Non-Repeating Character, BFS Queue | BFS Guide |
| 7 | Trees | Traversals (In/Pre/Post-order), Level-Order Traversal (BFS), Tree Height/Depth, Diameter, Invert Tree, LCA, BST Validation | Tree Guide |
| 8 | Binary Search | Iterative & Recursive, Lower / Upper Bound, Search in Rotated Sorted Array, Find Peak Element, Kth Smallest in Matrix | Binary Search Guide |
| 9 | Recursion | Factorial, Fibonacci, Tower of Hanoi, Reverse String, Subset / Subsequence Generation, Permutations | Backtracking Guide |
| 10 | Backtracking | N-Queens Problem, Sudoku Solver, Permutations, Combinations, Subset Sum, Graph Coloring, Word Search | Backtracking Guide |
| 11 | Heap / Priority Queue | Min / Max Heap, Heapify, Kth Largest / Smallest, Merge K Sorted Lists, Top K Frequent Elements, Heap Sort | Heap Guide |
| 12 | Graph | BFS & DFS Traversals, Cycle Detection, Topological Sort (Kahn's), Shortest Path (BFS / Dijkstra), Disjoint Set (Union-Find) | Graph Guide & Union-Find |
| 13 | Dynamic Programming | 0/1 Knapsack, Unbounded Knapsack, LCS, LIS, Edit Distance, Matrix Chain Multiplication, Coin Change | DP Guide |
| 14 | Greedy | Activity Selection, Fractional Knapsack, Huffman Coding, Job Sequencing, Minimum Spanning Tree (Prim/Kruskal) | Greedy Guide |
| 15 | Bit Manipulation | Get / Set / Clear Bit, Check Power of 2, Count Set Bits, XOR Duplicate Elimination, Swap Without Temp | Bit Manipulation Guide |
| 16 | Advanced Topics | Trie (Prefix Tree), Segment Tree, Fenwick Tree (BIT), Rolling Hash (Rabin-Karp), String Hashing, Matrix Exponentiation | Trie Guide |
Part 2: Master 80+ Core DSA Questions Checklist
This master index maps all 80+ classical interview questions & sub-patterns from the 16 handbook categories directly to their LeetCode problem numbers, difficulty levels, core patterns, and workspace guides.
1. Arrays (7 Problems)
| # | Handbook Pattern | Classical LeetCode Problem | Difficulty | Key Pattern | Guide |
|---|---|---|---|---|---|
| 1.1 | 2 Pointers | Two Sum II - Input Array Is Sorted (#167) | π’ Easy | Converging left/right pointers | Two Pointers |
| 1.2 | Sliding Window | Maximum Average Subarray I (#643) | π’ Easy | Fixed-size window sum | Sliding Window |
| 1.3 | Kadane's Algo | Maximum Subarray (#53) | π‘ Medium | Running subarray sum | Array |
| 1.4 | Binary Search | Search in Rotated Sorted Array (#33) | π‘ Medium | Partitioned binary search | Binary Search |
| 1.5 | Prefix / Suffix Sum | Product of Array Except Self (#238) | π‘ Medium | Left/right prefix products | Prefix Sum |
| 1.6 | Dutch National Flag | Sort Colors (#75) | π‘ Medium | 3-way in-place partitioning | Two Pointers |
| 1.7 | Merge Intervals | Merge Intervals (#56) | π‘ Medium | Start-time interval sorting | Intervals |
2. Strings (7 Problems)
| # | Handbook Pattern | Classical LeetCode Problem | Difficulty | Key Pattern | Guide |
|---|---|---|---|---|---|
| 2.1 | Pattern Searching (KMP) | Find the Index of the First Occurrence (#28) | π‘ Medium | LPS prefix function | String Guide |
| 2.2 | Anagram | Valid Anagram (#242) | π’ Easy | Frequency array comparison | Array |
| 2.3 | Sliding Window | Longest Substring Without Repeating Chars (#3) | π‘ Medium | Dynamic window with index map | Sliding Window |
| 2.4 | Palindrome | Valid Palindrome (#125) | π’ Easy | Two pointers converging | Two Pointers |
| 2.5 | Hashing | Group Anagrams (#49) | π‘ Medium | Sorted string hash key | Array |
| 2.6 | String Builder | Reverse Words in a String (#151) | π‘ Medium | In-place words reversal | Two Pointers |
| 2.7 | Longest Substring | Minimum Window Substring (#76) | π΄ Hard | Shrinkable sliding window | Sliding Window |
3. Hashing (7 Problems)
| # | Handbook Pattern | Classical LeetCode Problem | Difficulty | Key Pattern | Guide |
|---|---|---|---|---|---|
| 3.1 | Frequency Count | First Unique Character in a String (#387) | π’ Easy | Hash/Array frequency count | Array |
| 3.2 | HashMap / Set | Contains Duplicate (#217) | π’ Easy | Set membership lookup | Array |
| 3.3 | Two Sum | Two Sum (#1) | π’ Easy | Complement hash lookup | Array |
| 3.4 | Group Anagrams | Group Anagrams (#49) | π‘ Medium | Map with canonical key | Array |
| 3.5 | Subarray Sum = K | Subarray Sum Equals K (#560) | π‘ Medium | Prefix sum + HashMap | Prefix Sum |
| 3.6 | Distinct Elements | Longest Consecutive Sequence (#128) | π‘ Medium | HashSet sequence traversal | Array |
| 3.7 | Count Occurrences | Top K Frequent Elements (#347) | π‘ Medium | Bucket sort / Min-Heap | Heap |
4. Linked List (7 Problems)
| # | Handbook Pattern | Classical LeetCode Problem | Difficulty | Key Pattern | Guide |
|---|---|---|---|---|---|
| 4.1 | Reversal | Reverse Linked List (#206) | π’ Easy | 3-pointer iterative swap | Linked List |
| 4.2 | Detect Cycle (Floyd) | Linked List Cycle (#141) | π’ Easy | Tortoise and Hare | Linked List |
| 4.3 | Find Middle | Middle of the Linked List (#876) | π’ Easy | 1x vs 2x fast/slow pointer | Linked List |
| 4.4 | Merge Two Sorted LL | Merge Two Sorted Lists (#21) | π’ Easy | Dummy head comparison | Linked List |
| 4.5 | Remove Nth Node | Remove Nth Node From End of List (#19) | π‘ Medium | Two pointers with n-gap | Linked List |
| 4.6 | LRU Cache (DLL + Map) | LRU Cache (#146) | π‘ Medium | DLL sentinels + HashMap | Linked List |
| 4.7 | Clone Linked List | Copy List with Random Pointer (#138) | π‘ Medium | Interleaving / HashMap | Linked List |
5. Stack (7 Problems)
| # | Handbook Pattern | Classical LeetCode Problem | Difficulty | Key Pattern | Guide |
|---|---|---|---|---|---|
| 5.1 | Implementation | Implement Stack using Queues (#225) | π’ Easy | Push-cost queue rotation | Stack |
| 5.2 | Infix to Postfix | Basic Calculator II (#227) | π‘ Medium | Operator precedence stack | Stack |
| 5.3 | Postfix Evaluation | Evaluate Reverse Polish Notation (#150) | π‘ Medium | Operand stack evaluation | Stack |
| 5.4 | Next Greater Element | Next Greater Element I (#496) | π’ Easy | Monotonic decreasing stack | Monotonic Stack |
| 5.5 | Valid Parentheses | Valid Parentheses (#20) | π’ Easy | Bracket matching stack | Stack |
| 5.6 | Min Stack | Min Stack (#155) | π‘ Medium | Auxiliary minimum stack | Stack |
| 5.7 | Stock Span Problem | Online Stock Span (#901) | π‘ Medium | Monotonic stack with spans | Monotonic Stack |
6. Queue (7 Problems)
| # | Handbook Pattern | Classical LeetCode Problem | Difficulty | Key Pattern | Guide |
|---|---|---|---|---|---|
| 6.1 | Implementation | Implement Queue using Stacks (#232) | π’ Easy | In-stack & Out-stack | Stack |
| 6.2 | Circular Queue | Design Circular Queue (#622) | π‘ Medium | Modulo ring buffer | Stack |
| 6.3 | Deque (Double Ended) | Design Circular Deque (#641) | π‘ Medium | Head/tail pointer wrap | Stack |
| 6.4 | Sliding Window Max | Sliding Window Maximum (#239) | π΄ Hard | Monotonic deque | Monotonic Stack |
| 6.5 | First Non-Repeating | First Unique Char in a Stream (#387) | π’ Easy | Queue + frequency map | Sliding Window |
| 6.6 | BFS (Queue based) | Binary Tree Level Order Traversal (#102) | π‘ Medium | FIFO level traversal | BFS |
| 6.7 | LRU Cache (Queue) | LRU Cache (#146) | π‘ Medium | Doubly-ended list removal | Linked List |
7. Trees (7 Problems)
| # | Handbook Pattern | Classical LeetCode Problem | Difficulty | Key Pattern | Guide |
|---|---|---|---|---|---|
| 7.1 | Traversals (In/Pre/Post) | Binary Tree Inorder Traversal (#94) | π’ Easy | DFS Tree traversal | Tree |
| 7.2 | Level Order Traversal | Binary Tree Level Order Traversal (#102) | π‘ Medium | BFS Queue by level | BFS |
| 7.3 | Height / Depth | Maximum Depth of Binary Tree (#104) | π’ Easy | Postorder 1 + max(L, R) | Tree |
| 7.4 | Diameter of Tree | Diameter of Binary Tree (#543) | π’ Easy | Global max of (L + R) | Tree |
| 7.5 | Invert Binary Tree | Invert Binary Tree (#226) | π’ Easy | Recursive child swap | Tree |
| 7.6 | Lowest Common Ancestor | Lowest Common Ancestor of a Binary Tree (#236) | π‘ Medium | Bottom-up ancestor bubble | Tree |
| 7.7 | Binary Search Tree | Validate Binary Search Tree (#98) | π‘ Medium | Min/max range validation | Tree |
8. Binary Search (6 Problems)
| # | Handbook Pattern | Classical LeetCode Problem | Difficulty | Key Pattern | Guide |
|---|---|---|---|---|---|
| 8.1 | Binary Search (Iterative) | Binary Search (#704) | π’ Easy | Low, mid, high pointers | Binary Search |
| 8.2 | Binary Search (Recursive) | Search Insert Position (#35) | π’ Easy | Range insertion index | Binary Search |
| 8.3 | Lower / Upper Bound | Find First and Last Position (#34) | π‘ Medium | Bound-seeking binary search | Binary Search |
| 8.4 | Search in Rotated Sorted | Search in Rotated Sorted Array (#33) | π‘ Medium | Half-sorted range check | Binary Search |
| 8.5 | Find Peak Element | Find Peak Element (#162) | π‘ Medium | Slope direction climbing | Binary Search |
| 8.6 | Kth Smallest in Matrix | Kth Smallest Element in a Sorted Matrix (#378) | π‘ Medium | Binary search on values | Binary Search |
9. Recursion (7 Problems)
| # | Handbook Pattern | Classical LeetCode Problem | Difficulty | Key Pattern | Guide |
|---|---|---|---|---|---|
| 9.1 | Factorial / Power | Pow(x, n) (#50) | π‘ Medium | Divide and conquer exponent | Backtracking |
| 9.2 | Fibonacci | Fibonacci Number (#509) | π’ Easy | Base case + subproblem | Dynamic Programming |
| 9.3 | Tower of Hanoi | Recursion Classical Tower of Hanoi | π’ Easy | 3-peg recursive transfer | Backtracking |
| 9.4 | Reverse a String | Reverse String (#344) | π’ Easy | Swap at bounds recursively | Two Pointers |
| 9.5 | Subset / Subsequence | Subsets (#78) | π‘ Medium | Include / exclude tree | Backtracking |
| 9.6 | Permutation | Permutations (#46) | π‘ Medium | Unused element choice tree | Backtracking |
| 9.7 | Backtracking Intro | Combinations (#77) | π‘ Medium | Bounded recursion depth | Backtracking |
10. Backtracking (7 Problems)
| # | Handbook Pattern | Classical LeetCode Problem | Difficulty | Key Pattern | Guide |
|---|---|---|---|---|---|
| 10.1 | N-Queens Problem | N-Queens (#51) | π΄ Hard | Column/diagonal attack sets | Backtracking |
| 10.2 | Sudoku Solver | Sudoku Solver (#37) | π΄ Hard | Row, column, 3x3 block check | Backtracking |
| 10.3 | Permutations | Permutations II (#47) | π‘ Medium | Sort & skip duplicates | Backtracking |
| 10.4 | Combinations | Combination Sum (#39) | π‘ Medium | Target reduction with reuse | Backtracking |
| 10.5 | Subset Sum | Partition Equal Subset Sum (#416) | π‘ Medium | Target half-sum check | Dynamic Programming |
| 10.6 | Graph Coloring | Is Graph Bipartite? (#785) | π‘ Medium | 2-color DFS/BFS validation | Graph |
| 10.7 | Word Search | Word Search (#79) | π‘ Medium | 4-directional grid DFS | DFS |
11. Heap / Priority Queue (6 Problems)
| # | Handbook Pattern | Classical LeetCode Problem | Difficulty | Key Pattern | Guide |
|---|---|---|---|---|---|
| 11.1 | Min / Max Heap | Kth Largest Element in an Array (#215) | π‘ Medium | Size-k Min-Heap | Heap |
| 11.2 | Heapify | Sort an Array (#912) | π‘ Medium | In-place sift-down tree | Heap |
| 11.3 | Kth Largest / Smallest | Kth Largest Element in a Stream (#703) | π’ Easy | Streaming Min-Heap | Heap |
| 11.4 | Merge K Sorted Lists | Merge K Sorted Lists (#23) | π΄ Hard | PriorityQueue of list heads | Heap |
| 11.5 | Top K Frequent Elements | Top K Frequent Elements (#347) | π‘ Medium | Frequency min-heap of size k | Heap |
| 11.6 | Heap Sort | Sort an Array (#912) | π‘ Medium | Build max-heap + swap top | Sorting |
12. Graph (7 Problems)
| # | Handbook Pattern | Classical LeetCode Problem | Difficulty | Key Pattern | Guide |
|---|---|---|---|---|---|
| 12.1 | BFS Traversal | Word Ladder (#127) | π΄ Hard | Shortest transformation steps | BFS |
| 12.2 | DFS Traversal | Number of Islands (#200) | π‘ Medium | Connected component flood-fill | DFS |
| 12.3 | Detect Cycle | Course Schedule (#207) | π‘ Medium | 3-state DFS cycle detection | Graph |
| 12.4 | Topological Sort | Course Schedule II (#210) | π‘ Medium | Kahn's in-degree BFS | Graph |
| 12.5 | Shortest Path (BFS) | Shortest Path in Binary Matrix (#1091) | π‘ Medium | 8-direction BFS queue | BFS |
| 12.6 | Dijkstra's Algorithm | Network Delay Time (#743) | π‘ Medium | Min-Heap edge relaxation | Graph |
| 12.7 | Disjoint Set (Union-Find) | Number of Provinces (#547) | π‘ Medium | Path compression & rank | Union-Find |
13. Dynamic Programming (7 Problems)
| # | Handbook Pattern | Classical LeetCode Problem | Difficulty | Key Pattern | Guide |
|---|---|---|---|---|---|
| 13.1 | 0/1 Knapsack | Partition Equal Subset Sum (#416) | π‘ Medium | 1D reverse boolean array | DP |
| 13.2 | Unbounded Knapsack | Coin Change (#322) | π‘ Medium | Min coins forward loop | DP |
| 13.3 | Longest Common Subseq | Longest Common Subsequence (#1143) | π‘ Medium | 2D DP matching grid | DP |
| 13.4 | Longest Increasing Subseq | Longest Increasing Subsequence (#300) | π‘ Medium | O(n log n) Patience sorting | DP |
| 13.5 | Edit Distance | Edit Distance (#72) | π΄ Hard | Insert/Delete/Replace grid | DP |
| 13.6 | Matrix Chain Mult | Burst Balloons (#312) | π΄ Hard | Interval DP dp[i][j] | DP |
| 13.7 | Coin Change Problem | Coin Change II (#518) | π‘ Medium | Number of coin combinations | DP |
14. Greedy (6 Problems)
| # | Handbook Pattern | Classical LeetCode Problem | Difficulty | Key Pattern | Guide |
|---|---|---|---|---|---|
| 14.1 | Activity Selection | Non-overlapping Intervals (#435) | π‘ Medium | Sort by end-time greedily | Greedy |
| 14.2 | Fractional Knapsack | Maximum Units on a Truck (#1710) | π’ Easy | Sort by unit value ratio | Greedy |
| 14.3 | Huffman Coding | Optimal Code Length (Greedy) | π‘ Medium | PriorityQueue merge lowest | Greedy |
| 14.4 | Job Sequencing | Task Scheduler (#621) | π‘ Medium | Most frequent task first | Heap |
| 14.5 | Minimum Spanning Tree | Min Cost to Connect All Points (#1584) | π‘ Medium | Prim's / Kruskal's algorithm | Graph |
| 14.6 | Dijkstra (Greedy) | Path with Minimum Effort (#1631) | π‘ Medium | Min-Heap greedy frontier | Graph |
15. Bit Manipulation (6 Problems)
| # | Handbook Pattern | Classical LeetCode Problem | Difficulty | Key Pattern | Guide |
|---|---|---|---|---|---|
| 15.1 | Get / Set / Clear Bit | Single Number (#136) | π’ Easy | Bitmask bit shifts (1 << k) | Bit Manipulation |
| 15.2 | Check Power of 2 | Power of Two (#231) | π’ Easy | (n & (n - 1)) == 0 | Bit Manipulation |
| 15.3 | Count Set Bits | Number of 1 Bits (#191) | π’ Easy | Brian Kernighan's algorithm | Bit Manipulation |
| 15.4 | XOR Tricks | Missing Number (#268) | π’ Easy | XOR self-cancellation property | Bit Manipulation |
| 15.5 | Find Odd Occurring | Single Number II (#137) | π‘ Medium | Bit sum modulo 3 | Bit Manipulation |
| 15.6 | Swap without temp | Reverse Bits (#190) | π’ Easy | In-place XOR bit swapping | Bit Manipulation |
16. Advanced Topics (6 Problems)
| # | Handbook Pattern | Classical LeetCode Problem | Difficulty | Key Pattern | Guide |
|---|---|---|---|---|---|
| 16.1 | Trie (Prefix Tree) | Implement Trie (#208) | π‘ Medium | 26-child character tree | Trie |
| 16.2 | Segment Tree | Range Sum Query - Mutable (#307) | π‘ Medium | Range query & point update | Tree |
| 16.3 | Fenwick Tree (BIT) | Range Sum Query 2D - Mutable (#308) | π΄ Hard | Low-bit index manipulation | Tree |
| 16.4 | Rolling Hash | Repeated DNA Sequences (#187) | π‘ Medium | Rabin-Karp polynomial hash | Sliding Window |
| 16.5 | String Hashing | Shortest Palindrome (#214) | π΄ Hard | Prefix vs Suffix rolling hash | Sliding Window |
| 16.6 | Matrix Exponentiation | Climbing Stairs in O(log n) | π΄ Hard | Fast matrix power multiplication | Dynamic Programming |
Part 3: 20+ Canonical LeetCode Pattern Templates
1. Two Sum (LeetCode #1)
Problem: Given an array
numsand integertarget, return indices of two numbers such that they add up totarget.
Example:nums = [2, 7, 11, 15], target = 9Output: [0, 1]
π‘ Strategy & Intuitionβ
- Use a
HashMap<Integer, Integer>storing(element -> index). - For each element, compute
rem = target - nums[i]. - Check if
remalready exists in the map. If yes, return current and stored indices. - Otherwise, record
(nums[i], i)and proceed.
β Java Implementationβ
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int rem = target - nums[i];
if (map.containsKey(rem)) {
return new int[]{map.get(rem), i};
}
map.put(nums[i], i);
}
return new int[]{};
}
β±οΈ Complexity & Whyβ
- Time Complexity: β We traverse the array once and each map lookup/insertion is on average.
- Space Complexity: β Extra memory for storing up to elements in the
HashMap.
2. Best Time to Buy and Sell Stock (LeetCode #121)
Problem: Find the maximum profit achievable by buying and selling a stock exactly once.
Example:prices = [7, 1, 5, 3, 6, 4]Output: 5(Buy at 1, sell at 6)
π‘ Strategy & Intuitionβ
- Maintain a running minimum price seen so far (
min). - For each price, calculate potential profit:
price - min. - Update running maximum profit (
max).
β Java Implementationβ
public int maxProfit(int[] prices) {
int min = Integer.MAX_VALUE, max = 0;
for (int price : prices) {
min = Math.min(min, price);
max = Math.max(max, price - min);
}
return max;
}
β±οΈ Complexity & Whyβ
- Time Complexity: β Single linear pass over the price list.
- Space Complexity: β Only two scalar variables (
minandmax).
3. Maximum Subarray β Kadane's Algorithm (LeetCode #53)
Problem: Find the contiguous subarray within
numswith the largest sum.
Example:nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]Output: 6([4, -1, 2, 1])
π‘ Strategy & Intuitionβ
- Use Kadane's Algorithm: Maintain
curr(current subarray sum) andmaxSoFar. - For each element, choose whether to extend the previous subarray or start fresh:
curr = Math.max(num, curr + num). - If
currdrops below 0, it won't benefit any future subarray, so resetting/choosingnumnaturally restarts.
β Java Implementationβ
public int maxSubArray(int[] nums) {
int maxSoFar = nums[0], curr = 0;
for (int num : nums) {
curr = Math.max(num, curr + num);
maxSoFar = Math.max(maxSoFar, curr);
}
return maxSoFar;
}
β±οΈ Complexity & Whyβ
- Time Complexity: β Single pass through the array.
- Space Complexity: β Constant extra space.
4. Rotate Array by K (LeetCode #189)
Problem: Rotate an array to the right by
ksteps.
Example:nums = [1, 2, 3, 4, 5, 6, 7], k = 3Output: [5, 6, 7, 1, 2, 3, 4]
π‘ Strategy & Intuitionβ
- Normalize
k:k = k % nums.length. - Step 1: Reverse the entire array.
- Step 2: Reverse the first
kelements (0tok - 1). - Step 3: Reverse the remaining
n - kelements (kton - 1).
β Java Implementationβ
public void rotate(int[] nums, int k) {
k = k % nums.length;
reverse(nums, 0, nums.length - 1);
reverse(nums, 0, k - 1);
reverse(nums, k, nums.length - 1);
}
private void reverse(int[] nums, int l, int r) {
while (l < r) {
int t = nums[l];
nums[l] = nums[r];
nums[r] = t;
l++;
r--;
}
}
β±οΈ Complexity & Whyβ
- Time Complexity: β Each element is swapped a constant number of times.
- Space Complexity: β In-place array mutation without extra buffers.
5. Remove Duplicates from Sorted Array (LeetCode #26)
Problem: Remove duplicates in-place from a sorted array and return the new length.
Example:nums = [1, 1, 2, 2, 3, 3, 4]Output: 4, nums = [1, 2, 3, 4, ...]
π‘ Strategy & Intuitionβ
- Use Fast & Slow Two Pointers.
-
slow(i): tracks the tail of the unique sorted sequence. -
fast(j): scans forward. Whennums[j] != nums[i], advanceiand overwritenums[i] = nums[j].
β Java Implementationβ
public int removeDuplicates(int[] nums) {
if (nums.length == 0) return 0;
int i = 0;
for (int j = 1; j < nums.length; j++) {
if (nums[j] != nums[i]) {
nums[++i] = nums[j];
}
}
return i + 1;
}
β±οΈ Complexity & Whyβ
- Time Complexity: β Single pass with two pointers.
- Space Complexity: β In-place overwrite.
6. Merge Intervals (LeetCode #56)
Problem: Given an array of intervals, merge all overlapping intervals.
Example:intervals = [[1, 3], [2, 6], [8, 10], [15, 18]]Output: [[1, 6], [8, 10], [15, 18]]
π‘ Strategy & Intuitionβ
- Sort intervals by their start time:
Arrays.sort(intervals, (a, b) -> a[0] - b[0]). - Maintain a merged list. Compare each interval with the last interval in the result.
- If
curr[0] <= last[1], overlap occurs: expandlast[1] = Math.max(last[1], curr[1]). - Otherwise, no overlap: append
currto the result list.
β Java Implementationβ
public int[][] merge(int[][] intervals) {
Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
List<int[]> res = new ArrayList<>();
res.add(intervals[0]);
for (int[] in : intervals) {
int[] last = res.get(res.size() - 1);
if (in[0] <= last[1]) {
last[1] = Math.max(last[1], in[1]);
} else {
res.add(in);
}
}
return res.toArray(new int[res.size()][]);
}
β±οΈ Complexity & Whyβ
- Time Complexity: β Dominated by the initial sort step. Linear merge pass takes .
- Space Complexity: β Auxiliary list holding merged intervals.
7. Sliding Window (Fixed Size: Maximum Sum Subarray)
Problem: Find the maximum sum of any contiguous subarray of fixed size
k.
Example:nums = [2, 1, 5, 1, 3, 2], k = 3Output: 9([5, 1, 3])
π‘ Strategy & Intuitionβ
- Calculate the sum of the first
kelements to initialize the window. - Slide the window forward one position at a time: Add the incoming element
nums[i]and subtract the outgoing elementnums[i - k]. - Update
maxSum = Math.max(maxSum, windowSum).
β Java Implementationβ
public int maxSum(int[] nums, int k) {
int windowSum = 0, maxSum = Integer.MIN_VALUE;
for (int i = 0; i < k; i++) windowSum += nums[i];
maxSum = windowSum;
for (int i = k; i < nums.length; i++) {
windowSum += nums[i] - nums[i - k];
maxSum = Math.max(maxSum, windowSum);
}
return maxSum;
}
β±οΈ Complexity & Whyβ
- Time Complexity: β Every element is added and removed at most once.
- Space Complexity: β Only scalar window sum accumulators.
8. Two Pointers (Pair Sum in Sorted Array) (LeetCode #167)
Problem: Given a 1-indexed sorted array, determine if two numbers sum to
target.
Example:arr = [1, 2, 3, 4, 6], target = 6Output: true([2, 4])
π‘ Strategy & Intuitionβ
- Place
leftpointer at index0andrightpointer atarr.length - 1. - If
sum == target, target found! - If
sum < target, advanceleft++to increase sum. - If
sum > target, retreatright--to decrease sum.
β Java Implementationβ
public boolean pairSum(int[] arr, int target) {
int left = 0, right = arr.length - 1;
while (left < right) {
int sum = arr[left] + arr[right];
if (sum == target) return true;
else if (sum < target) left++;
else right--;
}
return false;
}
β±οΈ Complexity & Whyβ
- Time Complexity: β Pointers converge monotonically inwards; at most iterations.
- Space Complexity: β Constant two-pointer indices.
9. Binary Search (LeetCode #704)
Problem: Search for
targetin a sorted array. Return its index, or-1if absent.
Example:nums = [1, 3, 5, 7, 9, 11], target = 7Output: 3
π‘ Strategy & Intuitionβ
- Initialize search space:
low = 0,high = arr.length - 1. - Calculate
mid = low + (high - low) / 2(prevents integer overflow vs(low + high) / 2). - Narrow down by halving the search space each step.
β Java Implementationβ
public int binarySearch(int[] arr, int target) {
int low = 0, high = arr.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == target) return mid;
else if (arr[mid] < target) low = mid + 1;
else high = mid - 1;
}
return -1;
}
β±οΈ Complexity & Whyβ
- Time Complexity: β Halves remaining search candidate range at every decision branch.
- Space Complexity: β Iterative pointer updates.
10. Merge Two Sorted Arrays (LeetCode #88)
Problem: Merge two sorted arrays
aandbinto a single sorted array.
Example:a = [1, 3, 5], b = [2, 4, 6]Output: [1, 2, 3, 4, 5, 6]
π‘ Strategy & Intuitionβ
- Maintain two read pointers
iandjfor arraysaandb, and write pointerk. - Compare
a[i]andb[j], place the smaller intores[k++]. - Drain remaining elements once one array runs out.
β Java Implementationβ
public int[] merge(int[] a, int[] b) {
int n = a.length, m = b.length;
int[] res = new int[n + m];
int i = 0, j = 0, k = 0;
while (i < n && j < m) {
res[k++] = (a[i] <= b[j]) ? a[i++] : b[j++];
}
while (i < n) res[k++] = a[i++];
while (j < m) res[k++] = b[j++];
return res;
}
β±οΈ Complexity & Whyβ
- Time Complexity: β Each element is read and copied exactly once.
- Space Complexity: β Output array storing combined elements.
11. Fast & Slow Pointer (Floyd's Cycle Detection) (LeetCode #141)
Problem: Detect whether a linked list contains a cycle.
Example:1 -> 2 -> 3 -> 4 -> 2 (cycle)Output: true
π‘ Strategy & Intuitionβ
-
slowmoves 1 node at a time (slow.next). -
fastmoves 2 nodes at a time (fast.next.next). - If there is a cycle, the relative speed difference will cause
fastto lap and meetslow. - If
fastorfast.nextreachesnull, no cycle exists.
β Java Implementationβ
public boolean hasCycle(ListNode head) {
if (head == null || head.next == null) return false;
ListNode slow = head, fast = head.next;
while (fast != null && fast.next != null) {
if (slow == fast) return true;
slow = slow.next;
fast = fast.next.next;
}
return false;
}
β±οΈ Complexity & Whyβ
- Time Complexity: β If cycle exists,
fastcatchesslowwithin iterations. - Space Complexity: β No extra nodes or hash sets allocated.
12. Longest Substring Without Repeating Characters (LeetCode #3)
Problem: Find the length of the longest substring with all unique characters.
Example:s = "abcabcbb"Output: 3("abc")
π‘ Strategy & Intuitionβ
- Use a variable-size sliding window:
[left, right]. - Store character last seen index in
map. - If duplicate character seen inside current window (
map.get(c) >= left), jumpleft = map.get(c) + 1. - Update max window length:
right - left + 1.
β Java Implementationβ
public int lengthOfLongestSubstring(String s) {
Map<Character, Integer> map = new HashMap<>();
int left = 0, max = 0;
for (int right = 0; right < s.length(); right++) {
char c = s.charAt(right);
if (map.containsKey(c) && map.get(c) >= left) {
left = map.get(c) + 1;
}
map.put(c, right);
max = Math.max(max, right - left + 1);
}
return max;
}
β±οΈ Complexity & Whyβ
- Time Complexity: β
rightiterates from to ;leftonly moves forward. - Space Complexity: β Size of the character alphabet/charset ( for ASCII).
13. Longest Palindromic Substring (LeetCode #5)
Problem: Find the longest contiguous substring in
sthat reads the same forwards and backwards.
Example:s = "babad"Output: "bab"or"aba"
π‘ Strategy & Intuitionβ
- A palindrome mirrors around its center.
- Expand around center for odd length (
expand(s, i, i)) and even length (expand(s, i, i + 1)). - Keep track of starting index and maximum length found.
β Java Implementationβ
public String longestPalindrome(String s) {
if (s == null || s.isEmpty()) return "";
int start = 0, maxLen = 1;
for (int i = 0; i < s.length(); i++) {
int len1 = expand(s, i, i); // odd length palindrome (center: i)
int len2 = expand(s, i, i + 1); // even length palindrome (center: i, i+1)
int len = Math.max(len1, len2);
if (len > maxLen) {
maxLen = len;
start = i - (len - 1) / 2;
}
}
return s.substring(start, start + maxLen);
}
private int expand(String s, int l, int r) {
while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) {
l--;
r++;
}
return r - l - 1; // valid length
}
β±οΈ Complexity & Whyβ
- Time Complexity: β centers, expanding each center takes up to .
- Space Complexity: β Constant pointers and boundary variables.
14. Group Anagrams (LeetCode #49)
Problem: Group an array of strings such that anagrams are grouped together.
Example:strs = ["eat", "tea", "tan", "ate", "nat", "bat"]Output: [["bat"], ["nat", "tan"], ["ate", "eat", "tea"]]
π‘ Strategy & Intuitionβ
- Anagrams contain identical character frequencies. Sorting an anagram produces an identical canonical string key.
- Use a
HashMap<String, List<String>>. - Convert string to
char[], sort it, and usenew String(arr)as the map key.
β Java Implementationβ
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> map = new HashMap<>();
for (String s : strs) {
char[] arr = s.toCharArray();
Arrays.sort(arr);
String key = new String(arr);
map.computeIfAbsent(key, k -> new ArrayList<>()).add(s);
}
return new ArrayList<>(map.values());
}
β±οΈ Complexity & Whyβ
- Time Complexity: β Where is number of words, and is maximum word length (sorting each takes ).
- Space Complexity: β Storing all characters inside the map buckets.
15. Top K Frequent Elements (LeetCode #347)
Problem: Return the
kmost frequent elements from an integer array.
Example:nums = [1, 1, 1, 2, 2, 3], k = 2Output: [1, 2]
π‘ Strategy & Intuitionβ
- Build frequency map:
map.put(n, count + 1). - Maintain a Min-Heap of size ordered by frequency (
a[1] - b[1]). - If heap size exceeds , evict the least frequent (
pq.poll()). The top elements remain.
β Java Implementationβ
public int[] topKFrequent(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap<>();
for (int n : nums) map.put(n, map.getOrDefault(n, 0) + 1);
// Min-heap ordered by frequency
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[1] - b[1]);
for (int key : map.keySet()) {
pq.offer(new int[]{key, map.get(key)});
if (pq.size() > k) pq.poll();
}
int[] res = new int[k];
int i = k - 1;
while (!pq.isEmpty()) {
res[i--] = pq.poll()[0];
}
return res;
}
β±οΈ Complexity & Whyβ
- Time Complexity: β Pushing into a heap bounded at size costs per element.
- Space Complexity: β Map stores entries, heap stores items.
16. Kth Largest Element in an Array (LeetCode #215)
Problem: Find the -th largest element in an unsorted array.
Example:nums = [3, 2, 1, 5, 6, 4], k = 2Output: 5
π‘ Strategy & Intuitionβ
- Maintain a Min-Heap of size .
- When inserting elements, if size exceeds , poll the minimum.
- After processing all numbers, the root
peek()holds the smallest of the top elements, which is exactly the -th largest element!
β Java Implementationβ
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> pq = new PriorityQueue<>(); // default min-heap
for (int n : nums) {
pq.offer(n);
if (pq.size() > k) {
pq.poll();
}
}
return pq.peek();
}
β±οΈ Complexity & Whyβ
- Time Complexity: β Inserting elements into a heap of capacity .
- Space Complexity: β Bounded min-heap holding exactly elements.
17. Product of Array Except Self (LeetCode #238)
Problem: Return an array
ressuch thatres[i]is the product of all elements ofnumsexceptnums[i], without using division.
Example:nums = [1, 2, 3, 4]Output: [24, 12, 8, 6]
π‘ Strategy & Intuitionβ
- Left pass:
res[i]stores the running product of all elements to the left ofi. - Right pass: Maintain a running scalar
rightproduct; multiplyres[i]byrightwhile moving backwards.
β Java Implementationβ
public int[] productExceptSelf(int[] nums) {
int n = nums.length;
int[] res = new int[n];
// Left prefix product pass
res[0] = 1;
for (int i = 1; i < n; i++) {
res[i] = res[i - 1] * nums[i - 1];
}
// Right suffix product pass
int right = 1;
for (int i = n - 1; i >= 0; i--) {
res[i] *= right;
right *= nums[i];
}
return res;
}
β±οΈ Complexity & Whyβ
- Time Complexity: β Two linear passes over the array.
- Space Complexity: β Output array
resdoes not count towards auxiliary space.
18. Merge K Sorted Lists (LeetCode #23)
Problem: Merge
ksorted linked lists into one consolidated sorted list.
Example:lists = [[1, 4, 5], [1, 3, 4], [2, 6]]Output: [1, 1, 2, 3, 4, 4, 5, 6]
π‘ Strategy & Intuitionβ
- Use a Min-Heap (PriorityQueue) storing the current heads of the
klists. - Extract minimum node:
pq.poll(). Attach it tocurr.next. - If that extracted node has a
.next, insert its next node into the priority queue.
β Java Implementationβ
public ListNode mergeKLists(ListNode[] lists) {
if (lists == null || lists.length == 0) return null;
PriorityQueue<ListNode> pq = new PriorityQueue<>((a, b) -> a.val - b.val);
for (ListNode node : lists) {
if (node != null) pq.offer(node);
}
ListNode dummy = new ListNode(0), curr = dummy;
while (!pq.isEmpty()) {
ListNode node = pq.poll();
curr.next = node;
curr = curr.next;
if (node.next != null) {
pq.offer(node.next);
}
}
return dummy.next;
}
β±οΈ Complexity & Whyβ
- Time Complexity: β Where is the total number of nodes across all lists and is the number of lists.
- Space Complexity: β Priority queue holds at most one active head per list ( elements).
19. LRU Cache Design (LeetCode #146)
Problem: Design a data structure that follows the Least Recently Used (LRU) eviction constraint with
getandput.
Operations:get(key)returns value or-1;put(key, value)inserts or updates value, evicting LRU when exceeding capacity.
π‘ Strategy & Intuitionβ
- Combine a
HashMap<Integer, Node>(for lookup) with a Doubly Linked List (for node removal and insertion at head). - Use dummy
headandtailsentinels to eliminate null checks. - When accessed (
getorput), move node to head (Most Recently Used). - When capacity overflows, remove node right before
tail(Least Recently Used).
β Java Implementationβ
class LRUCache {
class Node {
int key, val;
Node prev, next;
Node(int k, int v) { this.key = k; this.val = v; }
}
private final int capacity;
private final Map<Integer, Node> map = new HashMap<>();
private final Node head = new Node(0, 0);
private final Node tail = new Node(0, 0);
public LRUCache(int capacity) {
this.capacity = capacity;
head.next = tail;
tail.prev = head;
}
public int get(int key) {
if (!map.containsKey(key)) return -1;
Node node = map.get(key);
remove(node);
insertAtHead(node);
return node.val;
}
public void put(int key, int value) {
if (map.containsKey(key)) {
remove(map.get(key));
}
if (map.size() >= capacity) {
map.remove(tail.prev.key);
remove(tail.prev);
}
Node node = new Node(key, value);
insertAtHead(node);
map.put(key, node);
}
private void remove(Node node) {
node.prev.next = node.next;
node.next.prev = node.prev;
}
private void insertAtHead(Node node) {
node.next = head.next;
node.next.prev = node;
head.next = node;
node.prev = head;
}
}
β±οΈ Complexity & Whyβ
- Time Complexity: for both
get()andput()β Map provides constant lookup; doubly-linked list pointer swaps run in constant time. - Space Complexity: β Map and doubly linked list hold at most
capacityitems.
20. Topological Sort β Kahn's Algorithm (LeetCode #207, #210)
Problem: Find a valid linear ordering of vertices in a Directed Acyclic Graph (DAG) such that for every directed edge , appears before .
Example:V = 4, edges = [[1, 0], [2, 0], [3, 1], [3, 2]]Output: [0, 1, 2, 3]
π‘ Strategy & Intuitionβ
- Calculate in-degree (incoming edge count) for every vertex.
- Enqueue all nodes with
in-degree == 0into a BFSQueue. - Pop node from queue, add to topological order, and decrement in-degree for all adjacent neighbors.
- If neighbor's in-degree drops to
0, enqueue it. If processed count , graph contains a cycle!
β Java Implementationβ
public int[] topoSort(int V, int[][] edges) {
List<List<Integer>> adj = new ArrayList<>();
for (int i = 0; i < V; i++) adj.add(new ArrayList<>());
int[] indegree = new int[V];
for (int[] e : edges) {
adj.get(e[0]).add(e[1]);
indegree[e[1]]++;
}
Queue<Integer> q = new LinkedList<>();
for (int i = 0; i < V; i++) {
if (indegree[i] == 0) q.offer(i);
}
int[] res = new int[V];
int idx = 0;
while (!q.isEmpty()) {
int node = q.poll();
res[idx++] = node;
for (int nei : adj.get(node)) {
if (--indegree[nei] == 0) {
q.offer(nei);
}
}
}
return idx == V ? res : new int[0]; // empty array if graph has a cycle
}
β±οΈ Complexity & Whyβ
- Time Complexity: β Every vertex is visited once and each directed edge is relaxed once.
- Space Complexity: β Adjacency list and in-degree array.
21. Dijkstra's Shortest Path Algorithm (LeetCode #743)
Problem: Find the shortest distance from a single source node
srcto all other nodes in a weighted graph with non-negative edge weights.
π‘ Strategy & Intuitionβ
- Initialize distances array:
dist[src] = 0, all otherdist[v] = Integer.MAX_VALUE. - Use a Min-Heap (PriorityQueue) storing
[distance, node]. - Greedily pick the node with smallest known distance: if
d > dist[u], skip (stale entry). - Relax all outgoing edges: if
d + weight < dist[v], updatedist[v]and offer[dist[v], v]to heap.
β Java Implementationβ
public int[] dijkstra(int V, List<List<int[]>> adj, int src) {
int[] dist = new int[V];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[src] = 0;
// Min-heap: [distance, node]
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]);
pq.offer(new int[]{0, src});
while (!pq.isEmpty()) {
int[] cur = pq.poll();
int d = cur[0], u = cur[1];
if (d > dist[u]) continue; // Stale heap entry
for (int[] nei : adj.get(u)) {
int v = nei[0], wt = nei[1];
if (d + wt < dist[v]) {
dist[v] = d + wt;
pq.offer(new int[]{dist[v], v});
}
}
}
return dist;
}
β±οΈ Complexity & Whyβ
- Time Complexity: β Each vertex and edge can trigger a log-time priority queue heap operation.
- Space Complexity: β Heap entries and distances table.
22. Trie (Prefix Tree) (LeetCode #208)
Problem: Implement a Trie with
insert(word),search(word), andstartsWith(prefix)operations.
π‘ Strategy & Intuitionβ
- Each
TrieNodehas an array of 26 child references (TrieNode[26]) and anisEndboolean flag. - Fast lookup without string hashing collisions: time depends strictly on string length , regardless of total dictionary size.
- Fundamental foundation for autocomplete, spellcheckers, and Boggle word search solvers.
β Java Implementationβ
class Trie {
static class TrieNode {
TrieNode[] child = new TrieNode[26];
boolean isEnd = false;
}
private final TrieNode root = new TrieNode();
public void insert(String word) {
TrieNode node = root;
for (char c : word.toCharArray()) {
int i = c - 'a';
if (node.child[i] == null) {
node.child[i] = new TrieNode();
}
node = node.child[i];
}
node.isEnd = true;
}
public boolean search(String word) {
TrieNode node = find(word);
return node != null && node.isEnd;
}
public boolean startsWith(String prefix) {
return find(prefix) != null;
}
private TrieNode find(String s) {
TrieNode node = root;
for (char c : s.toCharArray()) {
int i = c - 'a';
if (node.child[i] == null) return null;
node = node.child[i];
}
return node;
}
}
β±οΈ Complexity & Whyβ
- Time Complexity: for
insert,search, andstartsWith, where is the length of the query string. - Space Complexity: worst-case, where is number of words and is average word length. Nodes share common prefixes in practice.
Quick Decision Matrix
| When you see this problem clue... | Choose this pattern | Primary Java Tool |
|---|---|---|
| Find pair/triplet summing to target in sorted array | Two Pointers | left = 0, right = n - 1 |
| Subarray sum, substring with at most distinct chars | Sliding Window | Map<Character, Integer> |
| Contiguous maximum sum subarray | Kadane's Algorithm | curr = Math.max(num, curr + num) |
| Search in sorted array or monotonically changing function | Binary Search | mid = low + (high - low) / 2 |
| Top elements, median of stream, merge sorted lists | Heap / PriorityQueue | PriorityQueue<Integer> |
| Detect cycle in linked list or array sequence | Floyd's Fast & Slow | slow.next, fast.next.next |
| String anagrams, word groupings | Hashing with Sorted Key | Arrays.sort(s.toCharArray()) |
| Dependency ordering, course schedule, build system | Topological Sort | In-degree array + BFS Queue |
| Shortest path with positive weights | Dijkstra's Algorithm | Min-Heap on distance |
| String prefix search, dictionary autocomplete | Trie | TrieNode[26] |
| Overlapping ranges, meeting rooms, interval merges | Interval Sorting | Arrays.sort(intervals, (a, b) -> a[0] - b[0]) |
