Skip to main content

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 CategoryKey Sub-Techniques & Classical ProblemsDeep-Dive Guide
1ArraysTwo Pointers, Sliding Window, Kadane's Algo, Binary Search, Prefix/Suffix Sum, Dutch National Flag, Merge IntervalsArray Guide
2StringsPattern Searching (KMP), Anagrams, Sliding Window, Palindrome Verification, Hashing, StringBuilder, Longest SubstringSliding Window
3HashingFrequency Count, HashMap / HashSet, Two Sum, Group Anagrams, Subarray Sum = K, Distinct ElementsArray & Hash
4Linked ListIn-place Reversal, Cycle Detection (Floyd's Tortoise & Hare), Find Middle, Merge Two Sorted Lists, Remove Nth Node, LRU CacheLinked List Guide
5StackStack Implementation, Infix to Postfix, Postfix Evaluation, Next Greater Element, Valid Parentheses, Min Stack, Stock SpanStack Guide & Monotonic Stack
6QueueCircular Queue, Deque (Double Ended), Sliding Window Maximum, First Non-Repeating Character, BFS QueueBFS Guide
7TreesTraversals (In/Pre/Post-order), Level-Order Traversal (BFS), Tree Height/Depth, Diameter, Invert Tree, LCA, BST ValidationTree Guide
8Binary SearchIterative & Recursive, Lower / Upper Bound, Search in Rotated Sorted Array, Find Peak Element, Kth Smallest in MatrixBinary Search Guide
9RecursionFactorial, Fibonacci, Tower of Hanoi, Reverse String, Subset / Subsequence Generation, PermutationsBacktracking Guide
10BacktrackingN-Queens Problem, Sudoku Solver, Permutations, Combinations, Subset Sum, Graph Coloring, Word SearchBacktracking Guide
11Heap / Priority QueueMin / Max Heap, Heapify, Kth Largest / Smallest, Merge K Sorted Lists, Top K Frequent Elements, Heap SortHeap Guide
12GraphBFS & DFS Traversals, Cycle Detection, Topological Sort (Kahn's), Shortest Path (BFS / Dijkstra), Disjoint Set (Union-Find)Graph Guide & Union-Find
13Dynamic Programming0/1 Knapsack, Unbounded Knapsack, LCS, LIS, Edit Distance, Matrix Chain Multiplication, Coin ChangeDP Guide
14GreedyActivity Selection, Fractional Knapsack, Huffman Coding, Job Sequencing, Minimum Spanning Tree (Prim/Kruskal)Greedy Guide
15Bit ManipulationGet / Set / Clear Bit, Check Power of 2, Count Set Bits, XOR Duplicate Elimination, Swap Without TempBit Manipulation Guide
16Advanced TopicsTrie (Prefix Tree), Segment Tree, Fenwick Tree (BIT), Rolling Hash (Rabin-Karp), String Hashing, Matrix ExponentiationTrie 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 PatternClassical LeetCode ProblemDifficultyKey PatternGuide
1.12 PointersTwo Sum II - Input Array Is Sorted (#167)🟒 EasyConverging left/right pointersTwo Pointers
1.2Sliding WindowMaximum Average Subarray I (#643)🟒 EasyFixed-size window sumSliding Window
1.3Kadane's AlgoMaximum Subarray (#53)🟑 MediumRunning subarray sumArray
1.4Binary SearchSearch in Rotated Sorted Array (#33)🟑 MediumPartitioned binary searchBinary Search
1.5Prefix / Suffix SumProduct of Array Except Self (#238)🟑 MediumLeft/right prefix productsPrefix Sum
1.6Dutch National FlagSort Colors (#75)🟑 Medium3-way in-place partitioningTwo Pointers
1.7Merge IntervalsMerge Intervals (#56)🟑 MediumStart-time interval sortingIntervals

2. Strings (7 Problems)

#Handbook PatternClassical LeetCode ProblemDifficultyKey PatternGuide
2.1Pattern Searching (KMP)Find the Index of the First Occurrence (#28)🟑 MediumLPS prefix functionString Guide
2.2AnagramValid Anagram (#242)🟒 EasyFrequency array comparisonArray
2.3Sliding WindowLongest Substring Without Repeating Chars (#3)🟑 MediumDynamic window with index mapSliding Window
2.4PalindromeValid Palindrome (#125)🟒 EasyTwo pointers convergingTwo Pointers
2.5HashingGroup Anagrams (#49)🟑 MediumSorted string hash keyArray
2.6String BuilderReverse Words in a String (#151)🟑 MediumIn-place words reversalTwo Pointers
2.7Longest SubstringMinimum Window Substring (#76)πŸ”΄ HardShrinkable sliding windowSliding Window

3. Hashing (7 Problems)

#Handbook PatternClassical LeetCode ProblemDifficultyKey PatternGuide
3.1Frequency CountFirst Unique Character in a String (#387)🟒 EasyHash/Array frequency countArray
3.2HashMap / SetContains Duplicate (#217)🟒 EasySet membership lookupArray
3.3Two SumTwo Sum (#1)🟒 EasyComplement hash lookupArray
3.4Group AnagramsGroup Anagrams (#49)🟑 MediumMap with canonical keyArray
3.5Subarray Sum = KSubarray Sum Equals K (#560)🟑 MediumPrefix sum + HashMapPrefix Sum
3.6Distinct ElementsLongest Consecutive Sequence (#128)🟑 MediumHashSet sequence traversalArray
3.7Count OccurrencesTop K Frequent Elements (#347)🟑 MediumBucket sort / Min-HeapHeap

4. Linked List (7 Problems)

#Handbook PatternClassical LeetCode ProblemDifficultyKey PatternGuide
4.1ReversalReverse Linked List (#206)🟒 Easy3-pointer iterative swapLinked List
4.2Detect Cycle (Floyd)Linked List Cycle (#141)🟒 EasyTortoise and HareLinked List
4.3Find MiddleMiddle of the Linked List (#876)🟒 Easy1x vs 2x fast/slow pointerLinked List
4.4Merge Two Sorted LLMerge Two Sorted Lists (#21)🟒 EasyDummy head comparisonLinked List
4.5Remove Nth NodeRemove Nth Node From End of List (#19)🟑 MediumTwo pointers with n-gapLinked List
4.6LRU Cache (DLL + Map)LRU Cache (#146)🟑 MediumDLL sentinels + HashMapLinked List
4.7Clone Linked ListCopy List with Random Pointer (#138)🟑 MediumInterleaving / HashMapLinked List

5. Stack (7 Problems)

#Handbook PatternClassical LeetCode ProblemDifficultyKey PatternGuide
5.1ImplementationImplement Stack using Queues (#225)🟒 EasyPush-cost queue rotationStack
5.2Infix to PostfixBasic Calculator II (#227)🟑 MediumOperator precedence stackStack
5.3Postfix EvaluationEvaluate Reverse Polish Notation (#150)🟑 MediumOperand stack evaluationStack
5.4Next Greater ElementNext Greater Element I (#496)🟒 EasyMonotonic decreasing stackMonotonic Stack
5.5Valid ParenthesesValid Parentheses (#20)🟒 EasyBracket matching stackStack
5.6Min StackMin Stack (#155)🟑 MediumAuxiliary minimum stackStack
5.7Stock Span ProblemOnline Stock Span (#901)🟑 MediumMonotonic stack with spansMonotonic Stack

6. Queue (7 Problems)

#Handbook PatternClassical LeetCode ProblemDifficultyKey PatternGuide
6.1ImplementationImplement Queue using Stacks (#232)🟒 EasyIn-stack & Out-stackStack
6.2Circular QueueDesign Circular Queue (#622)🟑 MediumModulo ring bufferStack
6.3Deque (Double Ended)Design Circular Deque (#641)🟑 MediumHead/tail pointer wrapStack
6.4Sliding Window MaxSliding Window Maximum (#239)πŸ”΄ HardMonotonic dequeMonotonic Stack
6.5First Non-RepeatingFirst Unique Char in a Stream (#387)🟒 EasyQueue + frequency mapSliding Window
6.6BFS (Queue based)Binary Tree Level Order Traversal (#102)🟑 MediumFIFO level traversalBFS
6.7LRU Cache (Queue)LRU Cache (#146)🟑 MediumDoubly-ended list removalLinked List

7. Trees (7 Problems)

#Handbook PatternClassical LeetCode ProblemDifficultyKey PatternGuide
7.1Traversals (In/Pre/Post)Binary Tree Inorder Traversal (#94)🟒 EasyDFS Tree traversalTree
7.2Level Order TraversalBinary Tree Level Order Traversal (#102)🟑 MediumBFS Queue by levelBFS
7.3Height / DepthMaximum Depth of Binary Tree (#104)🟒 EasyPostorder 1 + max(L, R)Tree
7.4Diameter of TreeDiameter of Binary Tree (#543)🟒 EasyGlobal max of (L + R)Tree
7.5Invert Binary TreeInvert Binary Tree (#226)🟒 EasyRecursive child swapTree
7.6Lowest Common AncestorLowest Common Ancestor of a Binary Tree (#236)🟑 MediumBottom-up ancestor bubbleTree
7.7Binary Search TreeValidate Binary Search Tree (#98)🟑 MediumMin/max range validationTree

8. Binary Search (6 Problems)

#Handbook PatternClassical LeetCode ProblemDifficultyKey PatternGuide
8.1Binary Search (Iterative)Binary Search (#704)🟒 EasyLow, mid, high pointersBinary Search
8.2Binary Search (Recursive)Search Insert Position (#35)🟒 EasyRange insertion indexBinary Search
8.3Lower / Upper BoundFind First and Last Position (#34)🟑 MediumBound-seeking binary searchBinary Search
8.4Search in Rotated SortedSearch in Rotated Sorted Array (#33)🟑 MediumHalf-sorted range checkBinary Search
8.5Find Peak ElementFind Peak Element (#162)🟑 MediumSlope direction climbingBinary Search
8.6Kth Smallest in MatrixKth Smallest Element in a Sorted Matrix (#378)🟑 MediumBinary search on valuesBinary Search

9. Recursion (7 Problems)

#Handbook PatternClassical LeetCode ProblemDifficultyKey PatternGuide
9.1Factorial / PowerPow(x, n) (#50)🟑 MediumDivide and conquer exponentBacktracking
9.2FibonacciFibonacci Number (#509)🟒 EasyBase case + subproblemDynamic Programming
9.3Tower of HanoiRecursion Classical Tower of Hanoi🟒 Easy3-peg recursive transferBacktracking
9.4Reverse a StringReverse String (#344)🟒 EasySwap at bounds recursivelyTwo Pointers
9.5Subset / SubsequenceSubsets (#78)🟑 MediumInclude / exclude treeBacktracking
9.6PermutationPermutations (#46)🟑 MediumUnused element choice treeBacktracking
9.7Backtracking IntroCombinations (#77)🟑 MediumBounded recursion depthBacktracking

10. Backtracking (7 Problems)

#Handbook PatternClassical LeetCode ProblemDifficultyKey PatternGuide
10.1N-Queens ProblemN-Queens (#51)πŸ”΄ HardColumn/diagonal attack setsBacktracking
10.2Sudoku SolverSudoku Solver (#37)πŸ”΄ HardRow, column, 3x3 block checkBacktracking
10.3PermutationsPermutations II (#47)🟑 MediumSort & skip duplicatesBacktracking
10.4CombinationsCombination Sum (#39)🟑 MediumTarget reduction with reuseBacktracking
10.5Subset SumPartition Equal Subset Sum (#416)🟑 MediumTarget half-sum checkDynamic Programming
10.6Graph ColoringIs Graph Bipartite? (#785)🟑 Medium2-color DFS/BFS validationGraph
10.7Word SearchWord Search (#79)🟑 Medium4-directional grid DFSDFS

11. Heap / Priority Queue (6 Problems)

#Handbook PatternClassical LeetCode ProblemDifficultyKey PatternGuide
11.1Min / Max HeapKth Largest Element in an Array (#215)🟑 MediumSize-k Min-HeapHeap
11.2HeapifySort an Array (#912)🟑 MediumIn-place sift-down treeHeap
11.3Kth Largest / SmallestKth Largest Element in a Stream (#703)🟒 EasyStreaming Min-HeapHeap
11.4Merge K Sorted ListsMerge K Sorted Lists (#23)πŸ”΄ HardPriorityQueue of list headsHeap
11.5Top K Frequent ElementsTop K Frequent Elements (#347)🟑 MediumFrequency min-heap of size kHeap
11.6Heap SortSort an Array (#912)🟑 MediumBuild max-heap + swap topSorting

12. Graph (7 Problems)

#Handbook PatternClassical LeetCode ProblemDifficultyKey PatternGuide
12.1BFS TraversalWord Ladder (#127)πŸ”΄ HardShortest transformation stepsBFS
12.2DFS TraversalNumber of Islands (#200)🟑 MediumConnected component flood-fillDFS
12.3Detect CycleCourse Schedule (#207)🟑 Medium3-state DFS cycle detectionGraph
12.4Topological SortCourse Schedule II (#210)🟑 MediumKahn's in-degree BFSGraph
12.5Shortest Path (BFS)Shortest Path in Binary Matrix (#1091)🟑 Medium8-direction BFS queueBFS
12.6Dijkstra's AlgorithmNetwork Delay Time (#743)🟑 MediumMin-Heap edge relaxationGraph
12.7Disjoint Set (Union-Find)Number of Provinces (#547)🟑 MediumPath compression & rankUnion-Find

13. Dynamic Programming (7 Problems)

#Handbook PatternClassical LeetCode ProblemDifficultyKey PatternGuide
13.10/1 KnapsackPartition Equal Subset Sum (#416)🟑 Medium1D reverse boolean arrayDP
13.2Unbounded KnapsackCoin Change (#322)🟑 MediumMin coins forward loopDP
13.3Longest Common SubseqLongest Common Subsequence (#1143)🟑 Medium2D DP matching gridDP
13.4Longest Increasing SubseqLongest Increasing Subsequence (#300)🟑 MediumO(n log n) Patience sortingDP
13.5Edit DistanceEdit Distance (#72)πŸ”΄ HardInsert/Delete/Replace gridDP
13.6Matrix Chain MultBurst Balloons (#312)πŸ”΄ HardInterval DP dp[i][j]DP
13.7Coin Change ProblemCoin Change II (#518)🟑 MediumNumber of coin combinationsDP

14. Greedy (6 Problems)

#Handbook PatternClassical LeetCode ProblemDifficultyKey PatternGuide
14.1Activity SelectionNon-overlapping Intervals (#435)🟑 MediumSort by end-time greedilyGreedy
14.2Fractional KnapsackMaximum Units on a Truck (#1710)🟒 EasySort by unit value ratioGreedy
14.3Huffman CodingOptimal Code Length (Greedy)🟑 MediumPriorityQueue merge lowestGreedy
14.4Job SequencingTask Scheduler (#621)🟑 MediumMost frequent task firstHeap
14.5Minimum Spanning TreeMin Cost to Connect All Points (#1584)🟑 MediumPrim's / Kruskal's algorithmGraph
14.6Dijkstra (Greedy)Path with Minimum Effort (#1631)🟑 MediumMin-Heap greedy frontierGraph

15. Bit Manipulation (6 Problems)

#Handbook PatternClassical LeetCode ProblemDifficultyKey PatternGuide
15.1Get / Set / Clear BitSingle Number (#136)🟒 EasyBitmask bit shifts (1 << k)Bit Manipulation
15.2Check Power of 2Power of Two (#231)🟒 Easy(n & (n - 1)) == 0Bit Manipulation
15.3Count Set BitsNumber of 1 Bits (#191)🟒 EasyBrian Kernighan's algorithmBit Manipulation
15.4XOR TricksMissing Number (#268)🟒 EasyXOR self-cancellation propertyBit Manipulation
15.5Find Odd OccurringSingle Number II (#137)🟑 MediumBit sum modulo 3Bit Manipulation
15.6Swap without tempReverse Bits (#190)🟒 EasyIn-place XOR bit swappingBit Manipulation

16. Advanced Topics (6 Problems)

#Handbook PatternClassical LeetCode ProblemDifficultyKey PatternGuide
16.1Trie (Prefix Tree)Implement Trie (#208)🟑 Medium26-child character treeTrie
16.2Segment TreeRange Sum Query - Mutable (#307)🟑 MediumRange query & point updateTree
16.3Fenwick Tree (BIT)Range Sum Query 2D - Mutable (#308)πŸ”΄ HardLow-bit index manipulationTree
16.4Rolling HashRepeated DNA Sequences (#187)🟑 MediumRabin-Karp polynomial hashSliding Window
16.5String HashingShortest Palindrome (#214)πŸ”΄ HardPrefix vs Suffix rolling hashSliding Window
16.6Matrix ExponentiationClimbing Stairs in O(log n)πŸ”΄ HardFast matrix power multiplicationDynamic Programming

Part 3: 20+ Canonical LeetCode Pattern Templates


1. Two Sum (LeetCode #1)

Problem: Given an array nums and integer target, return indices of two numbers such that they add up to target.
Example: nums = [2, 7, 11, 15], target = 9 β†’\rightarrow Output: [0, 1]

πŸ’‘ Strategy & Intuition​

  • Use a HashMap<Integer, Integer> storing (element -> index).
  • For each element, compute rem = target - nums[i].
  • Check if rem already 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: O(n)\mathcal{O}(n) β€” We traverse the array once and each map lookup/insertion is O(1)\mathcal{O}(1) on average.
  • Space Complexity: O(n)\mathcal{O}(n) β€” Extra memory for storing up to nn 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] β†’\rightarrow 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: O(n)\mathcal{O}(n) β€” Single linear pass over the price list.
  • Space Complexity: O(1)\mathcal{O}(1) β€” Only two scalar variables (min and max).

3. Maximum Subarray β€” Kadane's Algorithm (LeetCode #53)

Problem: Find the contiguous subarray within nums with the largest sum.
Example: nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4] β†’\rightarrow Output: 6 ([4, -1, 2, 1])

πŸ’‘ Strategy & Intuition​

  • Use Kadane's Algorithm: Maintain curr (current subarray sum) and maxSoFar.
  • For each element, choose whether to extend the previous subarray or start fresh: curr = Math.max(num, curr + num).
  • If curr drops below 0, it won't benefit any future subarray, so resetting/choosing num naturally 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: O(n)\mathcal{O}(n) β€” Single pass through the array.
  • Space Complexity: O(1)\mathcal{O}(1) β€” Constant extra space.

4. Rotate Array by K (LeetCode #189)

Problem: Rotate an array to the right by k steps.
Example: nums = [1, 2, 3, 4, 5, 6, 7], k = 3 β†’\rightarrow Output: [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 k elements (0 to k - 1).
  • Step 3: Reverse the remaining n - k elements (k to n - 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: O(n)\mathcal{O}(n) β€” Each element is swapped a constant number of times.
  • Space Complexity: O(1)\mathcal{O}(1) β€” 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] β†’\rightarrow 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. When nums[j] != nums[i], advance i and overwrite nums[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: O(n)\mathcal{O}(n) β€” Single pass with two pointers.
  • Space Complexity: O(1)\mathcal{O}(1) β€” 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]] β†’\rightarrow 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: expand last[1] = Math.max(last[1], curr[1]).
  • Otherwise, no overlap: append curr to 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: O(nlog⁑n)\mathcal{O}(n \log n) β€” Dominated by the initial sort step. Linear merge pass takes O(n)\mathcal{O}(n).
  • Space Complexity: O(n)\mathcal{O}(n) β€” 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 = 3 β†’\rightarrow Output: 9 ([5, 1, 3])

πŸ’‘ Strategy & Intuition​

  • Calculate the sum of the first k elements to initialize the window.
  • Slide the window forward one position at a time: Add the incoming element nums[i] and subtract the outgoing element nums[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: O(n)\mathcal{O}(n) β€” Every element is added and removed at most once.
  • Space Complexity: O(1)\mathcal{O}(1) β€” 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 = 6 β†’\rightarrow Output: true ([2, 4])

πŸ’‘ Strategy & Intuition​

  • Place left pointer at index 0 and right pointer at arr.length - 1.
  • If sum == target, target found!
  • If sum < target, advance left++ to increase sum.
  • If sum > target, retreat right-- 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: O(n)\mathcal{O}(n) β€” Pointers converge monotonically inwards; at most nn iterations.
  • Space Complexity: O(1)\mathcal{O}(1) β€” Constant two-pointer indices.

9. Binary Search (LeetCode #704)

Problem: Search for target in a sorted array. Return its index, or -1 if absent.
Example: nums = [1, 3, 5, 7, 9, 11], target = 7 β†’\rightarrow Output: 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: O(log⁑n)\mathcal{O}(\log n) β€” Halves remaining search candidate range at every decision branch.
  • Space Complexity: O(1)\mathcal{O}(1) β€” Iterative pointer updates.

10. Merge Two Sorted Arrays (LeetCode #88)

Problem: Merge two sorted arrays a and b into a single sorted array.
Example: a = [1, 3, 5], b = [2, 4, 6] β†’\rightarrow Output: [1, 2, 3, 4, 5, 6]

πŸ’‘ Strategy & Intuition​

  • Maintain two read pointers i and j for arrays a and b, and write pointer k.
  • Compare a[i] and b[j], place the smaller into res[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: O(n+m)\mathcal{O}(n + m) β€” Each element is read and copied exactly once.
  • Space Complexity: O(n+m)\mathcal{O}(n + m) β€” 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) β†’\rightarrow Output: true

πŸ’‘ Strategy & Intuition​

  • slow moves 1 node at a time (slow.next).
  • fast moves 2 nodes at a time (fast.next.next).
  • If there is a cycle, the relative speed difference will cause fast to lap and meet slow.
  • If fast or fast.next reaches null, 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: O(n)\mathcal{O}(n) β€” If cycle exists, fast catches slow within ≀cycleΒ length\le \text{cycle length} iterations.
  • Space Complexity: O(1)\mathcal{O}(1) β€” 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" β†’\rightarrow 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), jump left = 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: O(n)\mathcal{O}(n) β€” right iterates from 00 to nβˆ’1n-1; left only moves forward.
  • Space Complexity: O(k)\mathcal{O}(k) β€” Size of the character alphabet/charset (k≀128k \le 128 for ASCII).

13. Longest Palindromic Substring (LeetCode #5)

Problem: Find the longest contiguous substring in s that reads the same forwards and backwards.
Example: s = "babad" β†’\rightarrow 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: O(n2)\mathcal{O}(n^2) β€” 2nβˆ’12n - 1 centers, expanding each center takes up to O(n)\mathcal{O}(n).
  • Space Complexity: O(1)\mathcal{O}(1) β€” 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"] β†’\rightarrow 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 use new 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: O(nβ‹…klog⁑k)\mathcal{O}(n \cdot k \log k) β€” Where nn is number of words, and kk is maximum word length (sorting each takes klog⁑kk \log k).
  • Space Complexity: O(nβ‹…k)\mathcal{O}(n \cdot k) β€” Storing all characters inside the map buckets.

15. Top K Frequent Elements (LeetCode #347)

Problem: Return the k most frequent elements from an integer array.
Example: nums = [1, 1, 1, 2, 2, 3], k = 2 β†’\rightarrow Output: [1, 2]

πŸ’‘ Strategy & Intuition​

  • Build frequency map: map.put(n, count + 1).
  • Maintain a Min-Heap of size kk ordered by frequency (a[1] - b[1]).
  • If heap size exceeds kk, evict the least frequent (pq.poll()). The top kk 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: O(nlog⁑k)\mathcal{O}(n \log k) β€” Pushing into a heap bounded at size kk costs O(log⁑k)\mathcal{O}(\log k) per element.
  • Space Complexity: O(n+k)\mathcal{O}(n + k) β€” Map stores nn entries, heap stores kk items.

16. Kth Largest Element in an Array (LeetCode #215)

Problem: Find the kk-th largest element in an unsorted array.
Example: nums = [3, 2, 1, 5, 6, 4], k = 2 β†’\rightarrow Output: 5

πŸ’‘ Strategy & Intuition​

  • Maintain a Min-Heap of size kk.
  • When inserting elements, if size exceeds kk, poll the minimum.
  • After processing all numbers, the root peek() holds the smallest of the top kk elements, which is exactly the kk-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: O(nlog⁑k)\mathcal{O}(n \log k) β€” Inserting nn elements into a heap of capacity kk.
  • Space Complexity: O(k)\mathcal{O}(k) β€” Bounded min-heap holding exactly kk elements.

17. Product of Array Except Self (LeetCode #238)

Problem: Return an array res such that res[i] is the product of all elements of nums except nums[i], without using division.
Example: nums = [1, 2, 3, 4] β†’\rightarrow Output: [24, 12, 8, 6]

πŸ’‘ Strategy & Intuition​

  • Left pass: res[i] stores the running product of all elements to the left of i.
  • Right pass: Maintain a running scalar right product; multiply res[i] by right while 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: O(n)\mathcal{O}(n) β€” Two linear passes over the array.
  • Space Complexity: O(1)\mathcal{O}(1) β€” Output array res does not count towards auxiliary space.

18. Merge K Sorted Lists (LeetCode #23)

Problem: Merge k sorted linked lists into one consolidated sorted list.
Example: lists = [[1, 4, 5], [1, 3, 4], [2, 6]] β†’\rightarrow Output: [1, 1, 2, 3, 4, 4, 5, 6]

πŸ’‘ Strategy & Intuition​

  • Use a Min-Heap (PriorityQueue) storing the current heads of the k lists.
  • Extract minimum node: pq.poll(). Attach it to curr.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: O(Nlog⁑k)\mathcal{O}(N \log k) β€” Where NN is the total number of nodes across all lists and kk is the number of lists.
  • Space Complexity: O(k)\mathcal{O}(k) β€” Priority queue holds at most one active head per list (kk elements).

19. LRU Cache Design (LeetCode #146)

Problem: Design a data structure that follows the Least Recently Used (LRU) eviction constraint with O(1)\mathcal{O}(1) get and put.
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 O(1)\mathcal{O}(1) lookup) with a Doubly Linked List (for O(1)\mathcal{O}(1) node removal and insertion at head).
  • Use dummy head and tail sentinels to eliminate null checks.
  • When accessed (get or put), 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: O(1)\mathcal{O}(1) for both get() and put() β€” Map provides constant lookup; doubly-linked list pointer swaps run in constant time.
  • Space Complexity: O(capacity)\mathcal{O}(\text{capacity}) β€” Map and doubly linked list hold at most capacity items.

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 u→vu \to v, uu appears before vv.
Example: V = 4, edges = [[1, 0], [2, 0], [3, 1], [3, 2]] β†’\rightarrow Output: [0, 1, 2, 3]

πŸ’‘ Strategy & Intuition​

  • Calculate in-degree (incoming edge count) for every vertex.
  • Enqueue all nodes with in-degree == 0 into a BFS Queue.
  • 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 <V< V, 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: O(V+E)\mathcal{O}(V + E) β€” Every vertex is visited once and each directed edge is relaxed once.
  • Space Complexity: O(V+E)\mathcal{O}(V + E) β€” Adjacency list and in-degree array.

21. Dijkstra's Shortest Path Algorithm (LeetCode #743)

Problem: Find the shortest distance from a single source node src to all other nodes in a weighted graph with non-negative edge weights.

πŸ’‘ Strategy & Intuition​

  • Initialize distances array: dist[src] = 0, all other dist[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], update dist[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: O((V+E)log⁑V)\mathcal{O}((V + E) \log V) β€” Each vertex and edge can trigger a log-time priority queue heap operation.
  • Space Complexity: O(V)\mathcal{O}(V) β€” Heap entries and distances table.

22. Trie (Prefix Tree) (LeetCode #208)

Problem: Implement a Trie with insert(word), search(word), and startsWith(prefix) operations.

πŸ’‘ Strategy & Intuition​

  • Each TrieNode has an array of 26 child references (TrieNode[26]) and an isEnd boolean flag.
  • Fast lookup without string hashing collisions: time depends strictly on string length LL, 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: O(L)\mathcal{O}(L) for insert, search, and startsWith, where LL is the length of the query string.
  • Space Complexity: O(Nβ‹…L)\mathcal{O}(N \cdot L) worst-case, where NN is number of words and LL is average word length. Nodes share common prefixes in practice.

Quick Decision Matrix

When you see this problem clue...Choose this patternPrimary Java Tool
Find pair/triplet summing to target in sorted arrayTwo Pointersleft = 0, right = n - 1
Subarray sum, substring with at most kk distinct charsSliding WindowMap<Character, Integer>
Contiguous maximum sum subarrayKadane's Algorithmcurr = Math.max(num, curr + num)
Search in sorted array or monotonically changing functionBinary Searchmid = low + (high - low) / 2
Top kk elements, median of stream, merge sorted listsHeap / PriorityQueuePriorityQueue<Integer>
Detect cycle in linked list or array sequenceFloyd's Fast & Slowslow.next, fast.next.next
String anagrams, word groupingsHashing with Sorted KeyArrays.sort(s.toCharArray())
Dependency ordering, course schedule, build systemTopological SortIn-degree array + BFS Queue
Shortest path with positive weightsDijkstra's AlgorithmMin-Heap on distance
String prefix search, dictionary autocompleteTrieTrieNode[26]
Overlapping ranges, meeting rooms, interval mergesInterval SortingArrays.sort(intervals, (a, b) -> a[0] - b[0])
πŸ“–
Track Page Progress0 / 635 Read
Knowledge Base Completion0%