Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Fundamentals 21 min read

15 Core LeetCode Patterns That Transform Problem-Solving: From Prefix Sum to Dynamic Programming

After solving 1,500+ LeetCode problems, the author distills 15 essential algorithmic patterns — each with concrete examples, step-by-step reasoning, and specific practice problems — to help developers recognize problem types instantly instead of memorizing solutions.

Prefix Sum

Core idea: build an auxiliary array where each position i stores the cumulative sum from the start to i. This enables O(1) range-sum queries via P[j] - P[i-1].

Applicable when frequent subarray sums or cumulative values are needed.

Example

Input: nums = [1, 2, 3, 4, 5, 6], query interval i = 1, j = 3. Output: 9.

Approach: preprocess into prefix array P = [1, 3, 6, 10, 15, 21]. Then compute P[3] - P[0] = 10 - 1 = 9 in O(1).

Related LeetCode: #303 Range Sum Query - Immutable, #525 Contiguous Array, #560 Subarray Sum Equals K.

Two Pointers

Technique: two indices move through a sorted array or list to find element pairs meeting a condition (e.g., sum equals target).

Best for sorted structures where pair conditions like sum, difference, or product are required.

Example

Input: nums = [1, 2, 3, 4, 6], target = 6. Output: indices [1, 3] (values 2 + 4 = 6).

Approach: left at start, right at end. If sum == target, return; if sum < target, left++; if sum > target, right--.

Related LeetCode: #167 Two Sum II, #15 3Sum, #11 Container With Most Water.

Sliding Window

Maintains a dynamic window over a sequence, adding/removing elements at the edges to evaluate contiguous subarrays or substrings in O(n) instead of O(n²).

Use when the problem asks for a contiguous segment with fixed length or a condition like max sum, unique characters, or minimum cover.

Example

Input: nums = [2, 1, 5, 1, 3, 2], k = 3. Output: 9 (subarray [5, 1, 3]).

Approach: compute sum of first k elements. Slide right by one: subtract leftmost, add new rightmost, track max.

Related LeetCode: #643 Maximum Average Subarray I, #3 Longest Substring Without Repeating Characters, #76 Minimum Window Substring.

Fast & Slow Pointers

Also called Floyd's cycle detection. Slow moves one step, fast moves two steps. If they meet, a cycle exists; if fast reaches null, no cycle.

Primary use: cycle detection in linked lists or sequences (e.g., happy number).

Example

Determine if a linked list has a cycle.

Approach: initialize slow and fast at head. Loop while fast and fast.next exist: slow = slow.next, fast = fast.next.next. If slow == fast, cycle detected.

Related LeetCode: #141 Linked List Cycle, #202 Happy Number, #287 Find the Duplicate Number.

LinkedList In-place Reversal

Reverses a sublist by pointer manipulation only, O(1) extra space.

Ideal when reversing a segment [m, n] of a singly linked list without allocating new nodes.

Example

Input: head = [1, 2, 3, 4, 5], m = 2, n = 4. Output: [1, 4, 3, 2, 5].

Approach: locate node before m (pre), then iteratively reverse next pointers for (n-m) steps, finally reconnect pre and the reversed tail.

Related LeetCode: #206 Reverse Linked List, #92 Reverse Linked List II, #24 Swap Nodes in Pairs.

Monotonic Stack

Stack maintains indices in strictly increasing or decreasing order of their values. Enables O(n) next-greater/smaller element queries.

Apply for "next greater element", "daily temperatures", or histogram rectangle problems.

Example

Input: nums = [2, 1, 2, 4, 3]. Output: [4, 2, 4, -1, -1] (next greater for each).

Approach: iterate i from 0 to n-1. While stack not empty and nums[stack.top] < nums[i], pop idx and set result[idx] = nums[i]. Push i.

Related LeetCode: #496 Next Greater Element I, #739 Daily Temperatures, #84 Largest Rectangle in Histogram.

Top K Elements

Find k largest (or smallest) items using a size-k min-heap (for largest) or max-heap (for smallest). Overall O(n log k).

Use when full sorting O(n log n) is overkill and only the top k matter.

Example

Input: nums = [3, 2, 1, 5, 6, 4], k = 2. Output: 5 (2nd largest).

Approach: push each num into min-heap; if heap size > k, pop smallest. After traversal, heap top is k-th largest.

Related LeetCode: #215 Kth Largest Element in an Array, #347 Top K Frequent Elements, #373 Find K Pairs with Smallest Sums.

Overlapping Intervals

Sort intervals by start. Merge by comparing current start with last merged end: if start <= last_end, merge (update end = max(end, last_end)); else append new interval.

Standard for merging, inserting, or removing overlaps in scheduling or range problems.

Example

Input: [[1,3],[2,6],[8,10],[15,18]]. Output: [[1,6],[8,10],[15,18]].

Approach: sort by start. Initialize merged with first. For each subsequent, if interval[0] <= merged[-1][1], merged[-1][1] = max(merged[-1][1], interval[1]); else append.

Related LeetCode: #56 Merge Intervals, #57 Insert Interval, #435 Non-Overlapping Intervals.

Modified Binary Search

Adapts binary search to rotated sorted arrays by determining which half is properly sorted, then checking if target lies in that half.

Essential for search in rotated arrays or 2D matrices with sorted rows/columns.

Example

Input: nums = [4,5,6,7,0,1,2], target = 0. Output: index 4.

Approach: while left <= right: mid = (left+right)//2. If nums[mid] == target return mid. If nums[left] <= nums[mid] (left half sorted): if nums[left] <= target < nums[mid] right = mid-1 else left = mid+1. Else (right half sorted): if nums[mid] < target <= nums[right] left = mid+1 else right = mid-1.

Related LeetCode: #33 Search in Rotated Sorted Array, #153 Find Minimum in Rotated Sorted Array, #240 Search a 2D Matrix II.

Binary Tree Traversal

Three depth-first orders: Preorder (root, left, right), Inorder (left, root, right), Postorder (left, right, root). Each suits different problems: preorder for path serialization, inorder for BST sorted output, postorder for bottom-up computations.

Example

Inorder traversal of root = [1,null,2,3] yields [1,3,2].

Approach: recursive helper(node): if not node return; helper(node.left); visit(node); helper(node.right). Iterative version uses explicit stack.

Related LeetCode: #257 Binary Tree Paths (preorder), #230 Kth Smallest Element in a BST (inorder), #124 Binary Tree Maximum Path Sum (postorder).

Depth-First Search (DFS)

Explores as deep as possible along each branch before backtracking. Natural for path enumeration, cycle detection, topological sort, and connected components.

Example

Find all root-to-leaf paths in tree [1,2,3,null,5]. Output: ["1->2->5", "1->3"].

Approach: recursive dfs(node, path): if leaf, add path to result; else dfs(left, path+node.val), dfs(right, path+node.val).

Related LeetCode: #133 Clone Graph, #113 Path Sum II, #210 Course Schedule II.

Breadth-First Search (BFS)

Visits nodes level by level using a queue. Guarantees shortest path in unweighted graphs and enables level-order tree traversal.

Example

Level-order traversal of [3,9,20,null,null,15,7] yields [[3],[9,20],[15,7]].

Approach: queue = [root]. While queue not empty: size = len(queue); level = []; for _ in range(size): node = queue.pop(0); level.append(node.val); if node.left: queue.append(node.left); if node.right: queue.append(node.right); result.append(level).

Related LeetCode: #102 Binary Tree Level Order Traversal, #994 Rotting Oranges, #127 Word Ladder.

Matrix Traversal

Applies DFS or BFS on 2D grids, treating each cell as a node with up to four neighbors. Common for flood fill, island counting, and region capture.

Example

Flood fill: image = [[1,1,1],[1,1,0],[1,0,1]], start (1,1), newColor = 2. Output: [[2,2,2],[2,2,0],[2,0,1]].

Approach: dfs(r,c): if out of bounds or color != original, return; set color = newColor; recurse on four directions. BFS alternative uses queue.

Related LeetCode: #733 Flood Fill, #200 Number of Islands, #130 Surrounded Regions.

Backtracking

Systematically builds candidates, abandoning (backtracking) when constraints fail. Generates permutations, combinations, subsets, and solves constraint satisfaction (e.g., N-Queens).

Example

Permutations of [1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]].

Approach: backtrack(path, remaining): if not remaining, add path to result; else for each x in remaining: backtrack(path+[x], remaining-{x}).

Related LeetCode: #46 Permutations, #78 Subsets, #51 N-Queens.

Dynamic Programming

Solves problems with overlapping subproblems and optimal substructure via memoization (top-down) or tabulation (bottom-up). Classic sub-patterns: Fibonacci, 0/1 Knapsack, LCS, LIS, Subset Sum, Matrix Chain Multiplication.

Example

Fibonacci n=5 -> 5. DP: dp[0]=0, dp[1]=1; for i in 2..n: dp[i] = dp[i-1] + dp[i-2].

Approach: identify state (e.g., dp[i] = max value for first i items), transition (dp[i] = max(dp[i-1], dp[i-2]+value)), base cases, and iteration order.

Related LeetCode: #70 Climbing Stairs, #198 House Robber, #322 Coin Change, #1143 Longest Common Subsequence, #300 Longest Increasing Subsequence, #416 Partition Equal Subset Sum.

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

Dynamic ProgrammingLeetCodedata structuresAlgorithmsSliding WindowTwo PointersPrefix SumProblem-Solving Patterns

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion