Skip to main content
127 Atomic Patterns 12 Comprehensive Sections FAANG & Top Tier-1

127 Core Coding Interview Patterns

The battle-tested map of Data Structures & Algorithms. Unlike high-level umbrellas, these 127 atomic patterns dissect the exact invariant, interview variations, company focus, and curated problems you need to recognize in technical rounds.

Your Progress: 0 / 127 0%

Click the checkbox next to any pattern to track your mastery. Stored locally in your browser.

Showing: 127 of 127 patterns
Section:
Company:
1

Array & String Patterns

Pointers, Sliding Windows, Prefixes, and In-place Subarrays

15 patterns
#1

Two Pointers (Opposite Direction)

Deep Dive Guide

Array & String Patterns

Core Invariant: Initialize one pointer at the start and another at the end, moving inward based on pairwise comparisons.
Why It Matters: Reduces brute-force O(n²) pair comparisons to O(n) in sorted arrays. Key for palindromes and two-sum variants.
Common Interview Variations:
Palindromes validation Sorted pair summation Dutch National Flag / Array partitioning
#2

Two Pointers (Same Direction / Fast-Slow)

Deep Dive Guide

Array & String Patterns

Core Invariant: Move two pointers in the same direction at varying speeds or conditions to inspect relative state without extra space.
Why It Matters: Fundamental for in-place array modification, cycle detection, and midpoint calculation in linear sequences.
Common Interview Variations:
Find midpoint of list In-place duplicate removal Cycle detection (Floyd's algorithm)
#3

Sliding Window (Fixed Size)

Deep Dive Guide

Array & String Patterns

Core Invariant: Slide a window of constant length k across an array, computing the incoming and outgoing difference in O(1) per step.
Why It Matters: Essential for real-time telemetry, sliding rate limiters, moving averages, and streaming analytics.
Common Interview Variations:
Max/Min sum of k-sized subarray Moving average calculations Windowed product and vowel counts
#4

Sliding Window (Dynamic Size)

Deep Dive Guide

Array & String Patterns

Core Invariant: Expand the right pointer to capture elements until a constraint is violated, then shrink the left pointer until valid again.
Why It Matters: Converts O(n³) substring search into O(n). Appears constantly in string parsing, token allocation, and compression.
Common Interview Variations:
Longest substring with unique characters Minimum window containing pattern At most K distinct elements
#5

Prefix Sum / Difference Array

Deep Dive Guide

Array & String Patterns

Core Invariant: Precompute cumulative running totals so any range query sum(i, j) can be resolved in O(1) time via prefix[j+1] - prefix[i].
Why It Matters: Eliminates nested loops when computing range queries or batch range additions in databases and image processing.
Common Interview Variations:
Subarray sum equals K Pivot index detection Difference arrays for range batch updates
#6

Hashing for Lookup

Deep Dive Guide

Array & String Patterns

Core Invariant: Map values to memory keys using HashMaps or HashSets for instant amortized O(1) containment checks.
Why It Matters: Foundational trade-off of memory for speed. Used across duplicate detection, frequency counts, and complement finding.
Common Interview Variations:
Two-Sum complement lookup Duplicate detection Anagram character count match
#7

Binary Search (Standard)

Deep Dive Guide

Array & String Patterns

Core Invariant: Repeatedly halve the search boundary in a sorted array by checking mid, achieving logarithmic O(log n) efficiency.
Why It Matters: Foundational for file system indexing, database B-trees, and search optimization.
Common Interview Variations:
First & last position of element Search in rotated sorted array Search insert position
#8

Binary Search (Answer Space / Range Search)

Deep Dive Guide

Array & String Patterns

Core Invariant: Binary search over the range of possible answers [min_ans, max_ans] using a monotonic feasibility check function.
Why It Matters: Used for capacity planning, throughput optimization, and resource allocation problems.
Common Interview Variations:
Koko Eating Bananas Split array largest sum Capacity to ship packages in D days
#9

Two Sum Family (2Sum, 3Sum, 4Sum, K-Sum)

Deep Dive Guide

Array & String Patterns

Core Invariant: Sort the array, fix (k - 2) pointers with loops, and reduce the inner problem to a two-pointer scan with duplicate pruning.
Why It Matters: Tests sorting, multi-pointer coordination, and rigorous avoidance of duplicate combinations.
Common Interview Variations:
Find any pair/triplet All unique triplets summing to 0 K-Sum generalization
#10

Monotonic Stack (Arrays & Spans)

Deep Dive Guide

Array & String Patterns

Core Invariant: Maintain an explicitly sorted stack (increasing or decreasing) while iterating to find the next/previous greater or smaller elements in linear O(n) time.
Why It Matters: Solves span, geometric layout, temperature, and histogram problems that would otherwise be quadratic.
Common Interview Variations:
Next greater element Daily temperatures / stock span Largest rectangle in histogram
#11

Merge Intervals

Deep Dive Guide

Array & String Patterns

Core Invariant: Sort intervals by start time. Compare adjacent intervals; if current.start <= prev.end, merge them into [prev.start, max(prev.end, current.end)].
Why It Matters: Core to calendar scheduling, resource allocation, and memory range management.
Common Interview Variations:
Merge overlapping intervals Insert into sorted interval list Non-overlapping interval removals
#12

In-Place Array Rearrangement (Cyclic Sort)

Deep Dive Guide

Array & String Patterns

Core Invariant: When array contains numbers from 1 to n, use values as indices. Swap each number into its target slot arr[i] == i + 1 without auxiliary memory.
Why It Matters: Achieves O(n) time and O(1) space for missing and duplicate numbers in integer arrays.
Common Interview Variations:
Cyclic sort placement Negation marking for visited items First missing positive
#13

Kadane’s Algorithm (Max Subarray Sum)

Deep Dive Guide

Array & String Patterns

Core Invariant: Maintain current_sum = max(num, current_sum + num). Discard negative prefix sums as they can never improve subsequent subarrays.
Why It Matters: Classic 1D DP optimization problem asked repeatedly across all top tech firms.
Common Interview Variations:
Standard maximum contiguous sum Circular subarray max sum K-concatenation max sum
#14

String Reversal Techniques

Deep Dive Guide

Array & String Patterns

Core Invariant: Swap characters in-place using two pointers converging inward. Reverse words by reversing the full string then reversing each word individually.
Why It Matters: Tests clean in-place memory mutations, word boundary parsing, and index control.
Common Interview Variations:
Reverse full character array Reverse words in a sentence Cyclic string rotation
#15

Anagram Grouping

Deep Dive Guide

Array & String Patterns

Core Invariant: Normalize words into canonical keys (either sorted character string or 26-element character frequency tuple) to group identical anagram sets.
Why It Matters: Applied in search engines, spell checkers, dictionary deduplication, and linguistic grouping.
Common Interview Variations:
Group anagrams by sorted key Frequency-tuple grouping Valid anagram verification
2

Linked List Patterns

Classic recursion, two-pointer tricks, and state-saving

6 patterns
#16

Reverse Linked List

Deep Dive Guide

Linked List Patterns

Core Invariant: Maintain prev, curr, and next pointers. Reorient curr.next = prev on each step while traversing iteratively or recursively.
Why It Matters: Appears as a foundational sub-step in palindrome checks, addition of linked numbers, and reverse-in-k-groups.
Common Interview Variations:
Full list reversal Reverse sublist between indices m and n Reverse nodes in k-Group
#17

Detect Cycle in Linked List (Floyd’s Tortoise & Hare)

Deep Dive Guide

Linked List Patterns

Core Invariant: Advance slow by 1 step and fast by 2 steps. If they meet, a cycle exists. Reset one pointer to head and move both by 1 to find cycle entry.
Why It Matters: Memory leak detection, circular reference checks, and detecting endless loops in OS process chains.
Common Interview Variations:
Cycle presence check Find cycle start node Calculate cycle length
#18

Merge Two / K Sorted Linked Lists

Deep Dive Guide

Linked List Patterns

Core Invariant: Use a dummy head and compare node values to stitch links in-place. For K lists, use a Min-Heap or divide-and-conquer pair merges.
Why It Matters: Direct real-world analogue to external merge sort and log aggregation across distributed nodes.
Common Interview Variations:
Merge two sorted lists in-place Merge K sorted lists with Min-Heap Divide and conquer pair merging
#19

Find Middle of Linked List

Deep Dive Guide

Linked List Patterns

Core Invariant: Advance fast pointer 2 steps and slow pointer 1 step. When fast reaches the end, slow is positioned exactly at the midpoint.
Why It Matters: Essential preprocessing step for linked list merge sort and palindrome checks without auxiliary arrays.
Common Interview Variations:
Find exact middle Pre-middle pointer for splitting lists Fast/slow parity handling
Apple Amazon Meta
#20

Remove N-th Node From End

Deep Dive Guide

Linked List Patterns

Core Invariant: Maintain two pointers separated by a distance of N steps. Advance both until fast reaches null; slow is now positioned at the deletion target.
Why It Matters: Tests clean pointer offset management and dummy head pattern to prevent null pointer exceptions.
Common Interview Variations:
Single-pass removal Dummy head edge case handling Double-pass length computation
Google Amazon Microsoft
#21

Palindrome Linked List

Deep Dive Guide

Linked List Patterns

Core Invariant: Find list middle using slow/fast pointers, reverse the second half in-place, compare values with the first half, then restore original order.
Why It Matters: Combines three fundamental techniques: slow/fast midpoint, in-place reversal, and dual pointer traversal in O(1) space.
Common Interview Variations:
O(1) space in-place reversal Stack-based comparison Restoring original list structure
Meta Amazon Apple
3

Heaps, Stacks & Toolkits

Real-time ranking, expression evaluation, spans, and hash maps

9 patterns
#22

Top K Elements using Min/Max Heap

Deep Dive Guide

Heaps, Stacks & Toolkits

Core Invariant: Maintain a min-heap of size K. When processing elements, insert each; if heap size exceeds K, pop the minimum so the top K largest remain.
Why It Matters: Solves streaming top-K queries in O(n log k) instead of full sorting O(n log n). Ubiquitous in log ranking.
Common Interview Variations:
Top K frequent elements Kth largest/smallest in stream Partially sorted streams
#23

Merge K Sorted Lists (Min Heap)

Deep Dive Guide

Heaps, Stacks & Toolkits

Core Invariant: Push the head node of each sorted list into a Min-Heap. Repeatedly extract the minimum node and push its next successor.
Why It Matters: Fundamental for external sorting, distributed database merge joins, and time-series aggregation.
Common Interview Variations:
Merge K linked lists Find K pairs with smallest sums Smallest range covering elements from K lists
#24

Sliding Window Median / Max / Min (Two Heaps & Deque)

Deep Dive Guide

Heaps, Stacks & Toolkits

Core Invariant: Maintain two balanced heaps (max-heap for lower half, min-heap for upper half) or a monotonic deque to track extremes dynamically.
Why It Matters: Core pattern for algorithmic trading pricing engines, running percentiles, and dynamic window analytics.
Common Interview Variations:
Find median from continuous data stream Sliding window median Sliding window maximum (monotonic deque)
#25

Next Greater Element (Monotonic Stack)

Deep Dive Guide

Heaps, Stacks & Toolkits

Core Invariant: Traverse array while popping items from stack that are smaller than current element; the current element becomes their next greater.
Why It Matters: Reduces quadratic lookups to single-pass linear time. Applied in stock charts, UI layout engines, and span tracking.
Common Interview Variations:
Next greater element I & II Online stock span Circular array scans
#26

Valid Parentheses / Expression Matching

Deep Dive Guide

Heaps, Stacks & Toolkits

Core Invariant: Push open brackets onto stack; on closing bracket, pop and verify type match. Empty stack at end denotes valid nesting.
Why It Matters: Basis of code linters, compilers, JSON/XML parsers, and mathematical calculators.
Common Interview Variations:
Matching open/close pairs Minimum removals to make valid parentheses Minimum insertions to balance
#27

Implement Stack / Queue using Other

Deep Dive Guide

Heaps, Stacks & Toolkits

Core Invariant: Use two stacks (input & output) for an amortized O(1) FIFO queue, or two queues for a LIFO stack.
Why It Matters: Probes deep understanding of abstract data type invariants, amortized complexity, and memory management.
Common Interview Variations:
Implement queue using two stacks Implement stack using queues Min-Stack with O(1) getMin
#28

Frequency Counters (Char / Word / Num)

Deep Dive Guide

Heaps, Stacks & Toolkits

Core Invariant: Count occurrences in a single pass into a Map or fixed array, then inspect counts to filter or sort items.
Why It Matters: Ubiquitous for character counting, majority element identification, and first-unique element lookups.
Common Interview Variations:
First unique character Sort characters by frequency Majority element (Boyer-Moore voting)
#29

Grouping and Bucketing using HashMap

Deep Dive Guide

Heaps, Stacks & Toolkits

Core Invariant: Use a transformed key (like string length, sorted anagram, or frequency count) to accumulate items into array buckets.
Why It Matters: Core pattern for clustering, bucket sort, log bucketing, and anagram grouping.
Common Interview Variations:
Group anagrams Top K frequent words with bucket sort Histogram binning
#30

Ordered HashMap (TreeMap, LinkedHashMap)

Deep Dive Guide

Heaps, Stacks & Toolkits

Core Invariant: Combine hash lookup with order preservation (insertion order via doubly linked list, or sorted order via Red-Black Tree).
Why It Matters: Powers cache eviction (LRU), ordered range queries, floor/ceiling lookups, and sliding window median.
Common Interview Variations:
LRU Cache eviction Sorted key range queries Sliding window range tracking
4

Recursion & Divide/Conquer

Recursive decision trees, memoization, binary split, and sorting

10 patterns
#31

Classic Recursion (Top-Down Decision Tree)

Deep Dive Guide

Recursion & Divide/Conquer

Core Invariant: Express problem in terms of smaller subproblems; establish a base condition and branch into all valid decisions.
Why It Matters: Foundational mental model for backtracking, DFS, and top-down dynamic programming.
Common Interview Variations:
Fibonacci / Climbing stairs branching Maximum depth of trees Recursive string inversion
#32

Recursion with Memoization (Top-Down DP)

Deep Dive Guide

Recursion & Divide/Conquer

Core Invariant: Attach a memoization cache (HashMap or 2D array) to a recursive function to return precomputed answers for overlapping states.
Why It Matters: Transforms exponential O(2^n) brute force trees into polynomial O(n) or O(n·m) execution.
Common Interview Variations:
Grid path counting with obstacles House robber decisions Decode ways
#33

Divide & Conquer (Binary Split Recursion)

Deep Dive Guide

Recursion & Divide/Conquer

Core Invariant: Split input into two equal halves (mid = (l+r)/2), solve both independently, and merge results in O(n) time.
Why It Matters: Enables logarithmic O(log n) tree depth, multi-threading parallelization, and master theorem analysis.
Common Interview Variations:
Counting inversions Expression parenthesization Merge K sorted lists
#34

Merge Sort

Deep Dive Guide

Recursion & Divide/Conquer

Core Invariant: Recursively split array into halves until singletons, then merge two sorted halves using two pointers in O(n log n) time.
Why It Matters: Guaranteed stable O(n log n) sort that operates naturally on linked lists without extra node allocation.
Common Interview Variations:
Count smaller numbers after self Sort linked list in O(n log n) Count reverse pairs
#35

Quick Sort (Partitioning Recursion)

Deep Dive Guide

Recursion & Divide/Conquer

Core Invariant: Pick a pivot element, partition array so elements smaller are left and larger are right, then recurse on partitions.
Why It Matters: In-place sorting standard used in C++ std::sort and Java dual-pivot primitive sorting. Basis for QuickSelect O(n).
Common Interview Variations:
QuickSelect for Kth smallest in O(n) 3-way Dutch National Flag partitioning Randomized pivot selection
#36

Binary Search (Divide & Search in Rotated / 2D Space)

Deep Dive Guide

Recursion & Divide/Conquer

Core Invariant: Determine which half is sorted in a rotated array or treat a 2D matrix as an unfolded sorted 1D array with row = mid/cols and col = mid%cols.
Why It Matters: Frequent interview test of boundary handling and coordinate mapping.
Common Interview Variations:
Search in rotated sorted array Find minimum in rotated sorted array Search a 2D matrix
#37

Modified Binary Search (Optimization on Monotonic Function)

Deep Dive Guide

Recursion & Divide/Conquer

Core Invariant: When an answer f(x) produces a monotonic boolean predicate (e.g. FFFTTT), binary search for the first boundary position.
Why It Matters: Turns difficult optimization problems into a sequence of straightforward feasibility checks.
Common Interview Variations:
Min capacity to ship packages Koko eating bananas Aggressive cows partition
#38

Recursive Backtracking (Combinations & Permutations)

Deep Dive Guide

Recursion & Divide/Conquer

Core Invariant: State choice tree: Make a decision → recurse deeper → undo decision (backtrack) to explore alternate permutations/subsets.
Why It Matters: Core mechanism for exhaustive search, combinatorial generation, and constraint satisfaction.
Common Interview Variations:
Permutations with duplicates Subsets / Power set Combinations with target sum
#39

Recursive DFS in Graphs & 2D Grids

Deep Dive Guide

Recursion & Divide/Conquer

Core Invariant: Traverse adjacent cells in 4 directions (dx, dy). Mark visited in-place or via set; recurse until boundaries or walls are hit.
Why It Matters: Powers island counting, flood fills, connected components, and maze traversal.
Common Interview Variations:
Number of islands Max area of island Flood fill replacement
#40

Tree Recursion (Bottom-Up Postorder Computations)

Deep Dive Guide

Recursion & Divide/Conquer

Core Invariant: Base case returns null/0. Recurse left and right subtrees; synthesize parent state from child results (e.g. max(left, right) + 1).
Why It Matters: Fundamental for tree height, diameter, maximum path sums, and balanced tree checks.
Common Interview Variations:
Binary tree diameter Binary tree maximum path sum Path sum existence
5

Dynamic Programming (Part 1)

0/1 Knapsack, Subsets, Unbounded, Min/Max paths, and Sequences

8 patterns
#41

DP – 0/1 Knapsack Pattern

Deep Dive Guide

Dynamic Programming (Part 1)

Core Invariant: For each item with weight and value, decide to either INCLUDE it (capacity - weight) or EXCLUDE it. State: dp[i][w].
Why It Matters: The foundational baseline for all resource-constrained optimization decisions.
Common Interview Variations:
Partition equal subset sum Target sum with signs Subset sum equals target
#42

DP – Subset / Boolean Reachability DP

Deep Dive Guide

Dynamic Programming (Part 1)

Core Invariant: Maintain boolean state dp[s] indicating if sum s is achievable using any combination of elements processed so far.
Why It Matters: Solves feasibility decisions where exact count or profit is irrelevant—only possibility matters.
Common Interview Variations:
Word break dictionary matching Partition to K equal sum subsets Last stone weight II
#43

DP – Unbounded Knapsack

Deep Dive Guide

Dynamic Programming (Part 1)

Core Invariant: Like 0/1 Knapsack, but each item can be chosen infinitely many times. Inner capacity loop runs forward from weight to target.
Why It Matters: Heavily tested in currency systems, token generation, and rod-cutting optimization.
Common Interview Variations:
Fewest coins to make sum (Coin Change I) Number of coin combinations (Coin Change II) Rod cutting
#44

DP – Minimum / Maximum Cost Path (Grid DP)

Deep Dive Guide

Dynamic Programming (Part 1)

Core Invariant: Fill a 2D table where dp[r][c] = cost[r][c] + min(dp[r-1][c], dp[r][c-1]), accumulating optimal costs to reach bottom-right.
Why It Matters: Direct application in pathfinding, robot navigation, string edit distance, and circuit layout.
Common Interview Variations:
Minimum path sum in grid Minimum falling path sum Edit distance
#45

DP – Count All Possibilities

Deep Dive Guide

Dynamic Programming (Part 1)

Core Invariant: Sum possibilities from all preceding valid states: dp[i] = dp[i-1] + dp[i-2] + ...
Why It Matters: Standard combinatorial recurrence pattern applied in dice rolls, step counting, and character decodings.
Common Interview Variations:
Climbing stairs Decode ways Unique paths in grid Combination sum IV
#46

DP – Longest Common Subsequence (LCS)

Deep Dive Guide

Dynamic Programming (Part 1)

Core Invariant: Compare characters from two strings: if s1[i] == s2[j], dp[i][j] = 1 + dp[i-1][j-1]; else max(dp[i-1][j], dp[i][j-1]).
Why It Matters: The core engine behind diff engines, Git merge conflicts, DNA sequence alignment, and spell checkers.
Common Interview Variations:
LCS string length Delete operations for two strings Minimum ASCII delete sum
#47

DP – Longest Palindromic Subsequence

Deep Dive Guide

Dynamic Programming (Part 1)

Core Invariant: Find LCS between original string s and its reverse reverse(s), or use 2D interval DP: if s[i]==s[j] dp[i][j]=2+dp[i+1][j-1].
Why It Matters: Demonstrates symmetry exploitation and string transformation in interview rounds.
Common Interview Variations:
Longest palindromic subsequence Minimum insertions to make palindrome Count palindromic subsequences
#48

DP – Longest Increasing Subsequence (LIS)

Deep Dive Guide

Dynamic Programming (Part 1)

Core Invariant: Quadratic DP: dp[i] = max(dp[j]) + 1 for j < i. Optimized with binary search (Patience Sorting): tails array in O(n log n).
Why It Matters: High-frequency optimization question asked at Google. Basis for 2D coordinate envelope stacking.
Common Interview Variations:
Standard LIS in O(n log n) Number of LIS Russian Doll Envelopes (2D sorting + LIS)
6

Dynamic Programming (Part 2)

Palindromes, Digit DP, Bitmasks, Interval DP, and Greedy Hybrids

8 patterns
#49

Palindrome Partitioning (Recursive + DP)

Deep Dive Guide

Dynamic Programming (Part 2)

Core Invariant: Precompute all substring palindromes with a 2D boolean table, then find minimum cuts using dp[i] = min(dp[j-1] + 1).
Why It Matters: Combines string preprocessing, interval checks, and multi-stage dynamic optimization.
Common Interview Variations:
Minimum cuts needed Generate all valid palindrome partitionings
#50

Digit DP (Number-Based DP)

Deep Dive Guide

Dynamic Programming (Part 2)

Core Invariant: Count integers <= N satisfying a property by placing digits from left to right with state: (index, count, is_tight, is_leading_zero).
Why It Matters: The premier framework for Google bar-raiser math/counting problems with huge bounds (N up to 10^18).
Common Interview Variations:
Count numbers with digit one Numbers without consecutive ones Numbers with repeated digits
#51

Bitmask DP (State Compression)

Deep Dive Guide

Dynamic Programming (Part 2)

Core Invariant: Represent subsets of selected items as integer bitmasks (e.g. 1<<i). Transitions iterate over unvisited bits in O(n·2^n) time.
Why It Matters: Solves NP-hard problems with small constraints (N <= 20) like Travelling Salesperson and team formation.
Common Interview Variations:
Travelling Salesperson (TSP) Shortest path visiting all nodes Smallest sufficient team
#52

DP with State + Position (Multi-Variable Finite States)

Deep Dive Guide

Dynamic Programming (Part 2)

Core Invariant: Track discrete system state alongside index: dp[i][state] (e.g. hold=0, hold=1, cooldown=2 for stock trading).
Why It Matters: Core modeling technique for financial simulations, cooldowns, transaction limits, and multi-day state machines.
Common Interview Variations:
Best time to buy/sell stock with cooldown Stock with transaction fee House robber in circular street
#53

DP on Strings – Pattern Matching (Regex & Wildcard)

Deep Dive Guide

Dynamic Programming (Part 2)

Core Invariant: Construct a 2D boolean grid dp[i][j] matching prefix text[0..i] against pattern[0..j]. Handle * as either 0 or multiple chars.
Why It Matters: Crucial for regex compilers, text search matching engines, and rule-based query parsers.
Common Interview Variations:
Regular Expression Matching (.*) Wildcard Matching (?*) Distinct subsequences count
#54

Matrix Chain Multiplication (Interval DP)

Deep Dive Guide

Dynamic Programming (Part 2)

Core Invariant: Solve subproblems over intervals [i, j] by trying every partition point k between i and j: dp[i][j] = min(dp[i][k] + dp[k+1][j] + cost).
Why It Matters: Essential for compiler expression parsing, query optimizer join order, and burst balloons.
Common Interview Variations:
Burst Balloons Minimum cost to merge stones Matrix chain multiplication
#55

Palindromic Substrings (Expand Around Center + DP)

Deep Dive Guide

Dynamic Programming (Part 2)

Core Invariant: Expand outward from all 2n-1 possible centers (single characters for odd, adjacent pairs for even) in O(n²) time and O(1) extra space.
Why It Matters: Significantly faster and simpler than 2D DP for palindromic substring extraction.
Common Interview Variations:
Longest palindromic substring Count of all palindromic substrings Minimum cuts to partition
#56

DP + Greedy Hybrid (Interval Weight Scheduling)

Deep Dive Guide

Dynamic Programming (Part 2)

Core Invariant: Sort items greedily (e.g. by end time), then apply DP + binary search: dp[i] = max(dp[i-1], profit[i] + dp[prev_compatible]).
Why It Matters: Combines the speed of greedy sorting with the optimality of dynamic programming for weighted intervals.
Common Interview Variations:
Maximum profit in job scheduling Minimum number of taps to water garden Word break II
7

Tree Traversals & Structures

Inorder, Preorder, Postorder, BFS, Diameter, LCA, and Tree building

11 patterns
#57

Tree Traversals – Inorder (Left → Root → Right)

Deep Dive Guide

Tree Traversals & Structures

Core Invariant: Traverse left subtree, visit current node, then traverse right subtree. In a BST, this yields strictly ascending sorted values.
Why It Matters: Validating BST properties, rank queries, and Kth smallest element extraction in O(k) time.
Common Interview Variations:
Validate Binary Search Tree Kth smallest element in BST Inorder successor in BST
#58

Tree Traversals – Preorder (Root → Left → Right)

Deep Dive Guide

Tree Traversals & Structures

Core Invariant: Visit root first, then recursively traverse left and right subtrees.
Why It Matters: Ideal for tree copying, prefix expression serialization, and cloning hierarchical file structures.
Common Interview Variations:
Tree serialization / deserialization Construct tree from preorder + inorder Path prefix accumulation
#59

Tree Traversals – Postorder (Left → Right → Root)

Deep Dive Guide

Tree Traversals & Structures

Core Invariant: Traverse left and right subtrees completely before processing the parent node.
Why It Matters: Essential for bottom-up aggregation: subtree size, subtree sum, deleting nodes, and computing tree height.
Common Interview Variations:
Postorder traversal Bottom-up subtree deletion LCA evaluation
Amazon Adobe Microsoft
#60

Tree Traversals – Level Order (Breadth-First Search)

Deep Dive Guide

Tree Traversals & Structures

Core Invariant: Use a FIFO queue. Record queue size at start of each iteration to process nodes strictly level-by-level.
Why It Matters: Powers hierarchical grouping, depth classification, zigzag serialization, and comment threads.
Common Interview Variations:
Level-order arrays Zigzag level order Right side view of binary tree
#61

Binary Tree Diameter

Deep Dive Guide

Tree Traversals & Structures

Core Invariant: At each node, compute left_height and right_height. Update global diameter = max(diameter, left + right), return max(left, right) + 1.
Why It Matters: Tests post-order return versus global update pattern, tracking longest path between any two nodes.
Common Interview Variations:
Tree diameter in edges or nodes Longest path passing through root N-ary tree diameter
Meta Google Amazon
#62

Lowest Common Ancestor (LCA)

Deep Dive Guide

Tree Traversals & Structures

Core Invariant: Binary Tree: DFS returns non-null when target found; when left and right both return nodes, current node is LCA. BST: Use value comparison.
Why It Matters: Applied in class inheritance resolution, file directory parent resolution, and distributed consensus trees.
Common Interview Variations:
LCA in Binary Tree LCA in Binary Search Tree LCA in deep DAGs
#63

Symmetric Tree / Mirror Check

Deep Dive Guide

Tree Traversals & Structures

Core Invariant: Check if two subtrees are mirrors: root1.val == root2.val AND isMirror(root1.left, root2.right) AND isMirror(root1.right, root2.left).
Why It Matters: Classic structural recursion evaluating cross-pointer traversal and reflection handling.
Common Interview Variations:
Symmetric binary tree Flip equivalent binary trees Same tree verification
#64

Invert / Flip Binary Tree

Deep Dive Guide

Tree Traversals & Structures

Core Invariant: Recursively swap left and right pointers of every node in the binary tree in-place.
Why It Matters: Famous litmus test for recursive pointer operations and tree transformations.
Common Interview Variations:
Invert binary tree Flip binary tree to match mirror
LinkedIn Uber Google
#65

Path Sum Variants (I, II, III)

Deep Dive Guide

Tree Traversals & Structures

Core Invariant: Root-to-leaf: Subtract node value from target sum. Any path (III): Combine tree traversal with prefix sum map to count paths in O(n).
Why It Matters: Demonstrates ability to generalize DFS from root-leaf paths to arbitrary internal paths using prefix maps.
Common Interview Variations:
Path sum exists (I) Return all path lists (II) Count paths sum to target anywhere (III)
#66

Serialize and Deserialize Binary Tree

Deep Dive Guide

Tree Traversals & Structures

Core Invariant: Serialize: Preorder traversal printing values with null delimiters ("#"). Deserialize: Split tokens and reconstruct recursively.
Why It Matters: Essential for RPC network serialization, database storage, and tree caching.
Common Interview Variations:
Preorder serialization with null markers Level order serialization with queue
#67

Construct Tree from Traversals

Deep Dive Guide

Tree Traversals & Structures

Core Invariant: Preorder provides root; locate root in inorder to partition left and right subtree lengths; recurse on sliced ranges.
Why It Matters: Tests array indexing, hash map index lookups, and divide-and-conquer tree rebuilding.
Common Interview Variations:
Preorder + Inorder construction Inorder + Postorder construction
8

Graphs & Backtracking

DFS, BFS, Topo Sort, Union-Find, Constraints, and Shortest Paths

10 patterns
#68

Depth-First Search (DFS) on Graphs

Deep Dive Guide

Graphs & Backtracking

Core Invariant: Explore deeply along an edge before backtracking. Track visited nodes using a Set or color array (unvisited/visiting/visited).
Why It Matters: Underpins connected component detection, maze traversal, cycle detection, and topological sorting.
Common Interview Variations:
Connected components in undirected graph Surrounded regions capture Pacific Atlantic water flow
#69

Breadth-First Search (BFS) & Multi-Source BFS

Deep Dive Guide

Graphs & Backtracking

Core Invariant: Use a FIFO queue to visit all neighbors at distance d before moving to d+1. Guarantees shortest path in unweighted graphs.
Why It Matters: Essential for networking latency hops, disease/rot propagation, and proximity routing.
Common Interview Variations:
Multi-source BFS (Rotting Oranges) Shortest path in binary matrix 01 Matrix nearest distance
#70

Topological Sort (Kahn’s Algorithm & DFS)

Deep Dive Guide

Graphs & Backtracking

Core Invariant: Compute in-degrees for all nodes. Push in-degree 0 nodes to queue; pop, append to order, decrement neighbors. If processed != N, cycle exists.
Why It Matters: Key in package managers (npm, pip), course prerequisites, and build task scheduling.
Common Interview Variations:
Course schedule prerequisites Course schedule order Alien dictionary character order
#71

Union Find (Disjoint Set with Path Compression)

Deep Dive Guide

Graphs & Backtracking

Core Invariant: Represent sets by root parents. find(x) flattens tree via path compression; union(x, y) attaches smaller rank tree to larger root.
Why It Matters: Near-O(1) amortized operations via Inverse Ackermann function. Core for network connectivity and Kruskal's MST.
Common Interview Variations:
Redundant connection detection Number of operations to make network connected Accounts merge
#72

Backtracking (Subsets & Combinations)

Deep Dive Guide

Graphs & Backtracking

Core Invariant: Systematically explore combination tree using index pointers: loop from start_idx to end, append element, recurse, then pop element.
Why It Matters: Standard framework for powerset, combination sum, and constraint optimization.
Common Interview Variations:
Combinations of size K Combination sum with reusable items Subsets with duplicate elements
#73

Backtracking (Constraint-Based Grid Solvers)

Deep Dive Guide

Graphs & Backtracking

Core Invariant: Traverse 2D board state. Place candidate piece, verify row/column/box validity in O(1); recurse. If dead end, backtrack.
Why It Matters: Tests pruning efficiency, state encoding, and clean constraint verification in complex search spaces.
Common Interview Variations:
N-Queens board placement Sudoku Solver Word Search on grid
#74

Graph Cycle Detection (DFS & Union-Find)

Deep Dive Guide

Graphs & Backtracking

Core Invariant: Directed: Track recursion stack (visiting state). Undirected: Detect edge to an already-visited non-parent node or use Union-Find find(u)==find(v).
Why It Matters: Crucial for deadlocks in operating systems, circular build dependency checks, and transaction trees.
Common Interview Variations:
Directed graph cycle via 3-color DFS Undirected graph cycle via Union-Find Bipartite graph coloring
#75

Shortest Path Algorithms (Dijkstra & Bellman-Ford)

Deep Dive Guide

Graphs & Backtracking

Core Invariant: Dijkstra: Min-Heap prioritizing shortest tentative distance in non-negative weighted graphs (O((V+E) log V)). Bellman-Ford: Handles negative edges.
Why It Matters: The foundation of network packet routing (OSPF), GPS navigation, and flight booking pricing systems.
Common Interview Variations:
Dijkstra with Min-Heap Cheapest flights within K stops (Bellman-Ford / BFS) Path with minimum effort (binary search or Dijkstra)
#76

Word Ladder Pattern (Implicit Graph Modeling)

Deep Dive Guide

Graphs & Backtracking

Core Invariant: Treat words as graph vertices. Adjacent words differ by 1 letter. Run BFS (or bidirectional BFS) to find shortest transformation sequence.
Why It Matters: Tests candidate's ability to model an abstract state space into a graph where edges are calculated on-the-fly.
Common Interview Variations:
Shortest word transformation length (Word Ladder I) Find all shortest transformation sequences (Word Ladder II) Open the Lock simulation
#77

Maze / Grid BFS/DFS Hybrid

Deep Dive Guide

Graphs & Backtracking

Core Invariant: Roll in a direction until hitting a wall before turning (ball physics). State is (row, col) upon stopping, not every single step.
Why It Matters: Combines continuous physics simulation with discrete graph shortest path traversals.
Common Interview Variations:
The Maze (Stop at walls) The Maze II (Shortest distance with rolling stops) Longest Increasing Path in Matrix (DFS + Memo)
9

Greedy, Bit Manipulation & Math

Interval scheduling, Jumps, Gas station, XOR tricks, and Primes

9 patterns
#78

Greedy – Interval Scheduling

Deep Dive Guide

Greedy, Bit Manipulation & Math

Core Invariant: Sort intervals by end time. Greedily pick the next compatible interval that finishes earliest to maximize total non-overlapping intervals.
Why It Matters: Optimal room scheduling, job processing, and ad insertion allocation.
Common Interview Variations:
Max non-overlapping intervals Minimum arrows to burst balloons Meeting Rooms II (Min rooms needed)
#79

Greedy – Jump Game Pattern

Deep Dive Guide

Greedy, Bit Manipulation & Math

Core Invariant: Track the maximum reachable index max_reach = max(max_reach, i + nums[i]). If i > max_reach, return false.
Why It Matters: Models boundary progression and decision horizons under limited step budgets.
Common Interview Variations:
Can reach the end? (Jump Game I) Minimum jumps to reach end (Jump Game II) Jump game BFS on indices
#80

Greedy – Gas Station Loop

Deep Dive Guide

Greedy, Bit Manipulation & Math

Core Invariant: Track total_surplus and current_tank. If current_tank drops below 0 at station i, restart starting station from i + 1.
Why It Matters: Demonstrates single-pass mathematical proof that if sum(gas) >= sum(cost), a unique starting point must exist.
Common Interview Variations:
Circular gas station tour Circular subarray max sum
#81

Greedy – Monotonic Stack (Span & Trapping Problems)

Deep Dive Guide

Greedy, Bit Manipulation & Math

Core Invariant: Use stack to maintain monotonically decreasing heights to compute trapped water between walls or largest bounded rectangle.
Why It Matters: Solves complex geometry and physical fluid simulation problems in a single linear pass.
Common Interview Variations:
Trapping rain water Largest rectangle in histogram Stock span
#82

Greedy – Change Making & Greedy Failure Recognition

Deep Dive Guide

Greedy, Bit Manipulation & Math

Core Invariant: When coin denominations are canonical (e.g. US currency), largest-coin-first works greedily; when arbitrary, prove where greedy fails and DP is required.
Why It Matters: Interviewers intentionally ask this to test whether a candidate blindly applies greedy without mathematical proof.
Common Interview Variations:
Canonical coins (Greedy) Arbitrary coin denominations (DP fallback) Candy distribution dual-pass
#83

Bit Manipulation – Single Number & XOR Invariants

Deep Dive Guide

Greedy, Bit Manipulation & Math

Core Invariant: Leverage XOR properties: a ^ a = 0 and a ^ 0 = a. All duplicate pairs cancel out in O(1) space, leaving unique values.
Why It Matters: Eliminates hash table memory overhead in streaming systems and embedded chips.
Common Interview Variations:
One unique among duplicates Two unique numbers (partitioning by lowest set bit) Bitwise AND of numbers range
#84

Bit Manipulation – Subsets by Masking

Deep Dive Guide

Greedy, Bit Manipulation & Math

Core Invariant: Loop from 0 to (2^n - 1). Check if bit (1 << i) is set in mask to decide whether to include element i in the current subset.
Why It Matters: Non-recursive, iterative powerset generation that avoids stack recursion overhead.
Common Interview Variations:
All subsets generation Bitmask DP states Minimum work sessions
#85

Math – GCD / LCM & Euclidean Algorithm

Deep Dive Guide

Greedy, Bit Manipulation & Math

Core Invariant: gcd(a, b) = gcd(b, a % b). lcm(a, b) = (a * b) / gcd(a, b). Normalize 2D coordinate slope as (dy / gcd, dx / gcd).
Why It Matters: Essential for fraction simplification, slope collinearity checks, and string periodicity.
Common Interview Variations:
Greatest common divisor of strings Max points on a line (slope normalization) Periodic array alignment
#86

Math – Sieve of Eratosthenes

Deep Dive Guide

Greedy, Bit Manipulation & Math

Core Invariant: Initialize boolean array is_prime[0..N] = true. Mark multiples of each prime starting from p*p up to N in O(N log log N) time.
Why It Matters: Fundamental for cryptography, prime factorization, and number theory queries.
Common Interview Variations:
Count primes up to N Prime arrangements Goldbach conjecture verification
Amazon Google Microsoft
10

Advanced Strings, Tries & Segment Trees

KMP, Rabin-Karp, Prefix/Bitwise Tries, and Range Query trees

10 patterns
#87

String Sliding Window with Frequency Maps

Deep Dive Guide

Advanced Strings, Tries & Segment Trees

Core Invariant: Maintain character frequencies in a moving window. Track matched_chars count to avoid re-scanning the entire dictionary on each shift.
Why It Matters: Reduces substring search to strictly O(n) runtime. Highly tested in parsing and spellcheckers.
Common Interview Variations:
Minimum window substring Find all anagrams in string Longest substring with at most K distinct chars
#88

Two-Pass String Processing

Deep Dive Guide

Advanced Strings, Tries & Segment Trees

Core Invariant: Pass 1 collects counts or positions; Pass 2 builds or modifies string using the precomputed state.
Why It Matters: Avoids complex backtracking in balanced parenthesis removals, string compression, and run-length encoding.
Common Interview Variations:
In-place string compression Minimum removals to make valid parentheses Expanding and collapsing strings
#89

String Builder & Parsing Optimization

Deep Dive Guide

Advanced Strings, Tries & Segment Trees

Core Invariant: Use mutable character arrays or StringBuilder buffers to prevent quadratic O(n²) memory allocations caused by string immutability.
Why It Matters: Crucial in Java/Python/JS where naive `str += char` recreates the entire string on every loop iteration.
Common Interview Variations:
Run-length encoding Decode nested bracket string expressions Zigzag conversion
#90

KMP (Knuth-Morris-Pratt) Pattern Matching

Deep Dive Guide

Advanced Strings, Tries & Segment Trees

Core Invariant: Construct Longest Prefix Suffix (LPS) array in O(m). When a mismatch occurs, skip redundant re-checks using the LPS fallback index in O(n) total time.
Why It Matters: Massive speedup for genomic DNA search, text editors, and stream pattern matching without backtracking.
Common Interview Variations:
First index of occurrence Repeated substring pattern check Cyclic string rotations
#91

Rabin-Karp + Rolling Hash

Deep Dive Guide

Advanced Strings, Tries & Segment Trees

Core Invariant: Convert substrings into polynomial rolling hash values: hash = (hash * base + new_char - old_char * power) % mod in O(1) per step.
Why It Matters: Used in plagiarism detectors, bioinformatics sequence search, and detecting duplicate substrings across gigabytes.
Common Interview Variations:
Longest duplicate substring Repeated DNA sequences Multi-pattern string search
#92

Basic Trie Construction & Search (Prefix Tree)

Deep Dive Guide

Advanced Strings, Tries & Segment Trees

Core Invariant: Tree where each node holds an array/map of child characters and an is_end boolean flag. Lookup and insert take O(L) time.
Why It Matters: Powers search bar autocomplete, IP router longest prefix match, and spell check dictionaries.
Common Interview Variations:
Implement Trie with insert & search Design Add and Search Words with wildcard dot (.) Replace words with shortest prefix
#93

Trie with DFS for Word Search (Boggle Solver)

Deep Dive Guide

Advanced Strings, Tries & Segment Trees

Core Invariant: Insert dictionary into a Trie. Run 2D grid DFS; prune branches immediately when current prefix is absent from the Trie.
Why It Matters: Eliminates checking millions of invalid English words in matrix word searches.
Common Interview Variations:
Word Search II Search suggestions system Longest word in dictionary
#94

Bitwise Trie (Binary Trie for Max XOR)

Deep Dive Guide

Advanced Strings, Tries & Segment Trees

Core Invariant: Store numbers in a binary Trie (children: 0 and 1). For a query X, greedily navigate to the opposite bit (1 - bit) to maximize XOR in O(32) time.
Why It Matters: High-performance bitwise routing and maximum XOR pair calculations.
Common Interview Variations:
Maximum XOR of two numbers in array Maximum XOR with an element from array Map sum pairs
#95

Segment Tree for Range Queries

Deep Dive Guide

Advanced Strings, Tries & Segment Trees

Core Invariant: Preprocess array into a balanced binary tree where each node stores summary for [L, R]. Range queries and point updates run in O(log n) time.
Why It Matters: Essential for mutable range sums, minimums, maximums, and live leaderboards in competitive programming.
Common Interview Variations:
Mutable range sum query Range minimum query (RMQ) My Calendar III (Event overlaps)
#96

Lazy Propagation in Segment Trees

Deep Dive Guide

Advanced Strings, Tries & Segment Trees

Core Invariant: Postpone interval updates to children by storing a pending lazy value on the parent node until a child node is explicitly queried.
Why It Matters: Enables batch range updates (e.g. add X to all elements from L to R) in O(log n) instead of O(n).
Common Interview Variations:
Batch range additions Interval toggles Range assignment
11

Matrix, Geometry & Simulation

Spiral, Rotate, Flood fill, Geometry formulas, and Turn systems

11 patterns
#97

Matrix DFS / BFS Traversal

Deep Dive Guide

Matrix, Geometry & Simulation

Core Invariant: Traverse 2D grids using coordinate direction arrays: dx = [-1, 0, 1, 0], dy = [0, 1, 0, -1]. Mark visited to avoid infinite loops.
Why It Matters: The foundation of all 2D grid and tile-based challenges in coding interviews.
Common Interview Variations:
Island count Connected region size Shortest escape path
#98

Spiral Matrix Traversal

Deep Dive Guide

Matrix, Geometry & Simulation

Core Invariant: Track top, bottom, left, right boundaries. Traverse right, down, left, up, shrinking boundaries after each row/column pass.
Why It Matters: Tests candidate's boundary management, off-by-one avoidance, and procedural simulation.
Common Interview Variations:
Spiral order print Spiral matrix generation II
#99

Diagonal Matrix Traversal

Deep Dive Guide

Matrix, Geometry & Simulation

Core Invariant: Group cells by (row + col) for anti-diagonals, or alternate up-right and down-left directional steps across diagonal lanes.
Why It Matters: Applied in JPEG image compression algorithms (zigzag scan) and matrix linear algebra.
Common Interview Variations:
Zigzag diagonal traverse Print diagonals of matrix
Google Microsoft Bloomberg
#100

Rotate Matrix In-Place

Deep Dive Guide

Matrix, Geometry & Simulation

Core Invariant: Rotate 90 degrees clockwise by transposing the matrix (swap matrix[i][j] with matrix[j][i]), then reverse each individual row.
Why It Matters: Demonstrates spatial coordinate mapping and in-place memory preservation without allocating O(n²) space.
Common Interview Variations:
90 degree rotation 180 / 270 degree rotation Transpose matrix
#101

Flood Fill / Region Filling

Deep Dive Guide

Matrix, Geometry & Simulation

Core Invariant: Traverse contiguous cells sharing the starting color; replace them with the new color using recursion or queue.
Why It Matters: The algorithmic engine of Photoshop paint buckets, map region grouping, and territory capture games.
Common Interview Variations:
Bucket flood fill Surrounded regions border-inward fill
#102

Geometry – Area, Distance & Collinearity

Deep Dive Guide

Matrix, Geometry & Simulation

Core Invariant: Use cross products or normalized fractional slopes to test collinearity without floating point precision issues.
Why It Matters: Essential for drone navigation, GPS mapping software, UI bounding box collision, and robotics.
Common Interview Variations:
Max points on a line Rectangle area overlap Valid square detection
#103

Math – Modular Arithmetic

Deep Dive Guide

Matrix, Geometry & Simulation

Core Invariant: (a + b) % M = ((a % M) + (b % M)) % M. Apply modulo at every intermediate step to prevent 64-bit integer overflow.
Why It Matters: Crucial for cryptographic algorithms, circular hashing, and problems asking for "answer modulo 10^9 + 7".
Common Interview Variations:
Modular addition and multiplication Modulo exponentiation Robot bounded in circle
Google Bloomberg Amazon
#104

Fast Power / Binary Exponentiation

Deep Dive Guide

Matrix, Geometry & Simulation

Core Invariant: Compute a^b in O(log b) time: if b is even, a^b = (a^(b/2))^2; if odd, a^b = a * (a^(b/2))^2.
Why It Matters: Fundamental for RSA public-key encryption, matrix exponentiation for DP, and fast math libraries.
Common Interview Variations:
Pow(x, n) Super Pow under modulo
#105

Combinatorics – nCr & Pascal’s Triangle

Deep Dive Guide

Matrix, Geometry & Simulation

Core Invariant: Construct combinations row-by-row using C(n, r) = C(n-1, r-1) + C(n-1, r), avoiding factorial integer overflow.
Why It Matters: Powers probability calculations, grid path counting, and binomial distribution analysis.
Common Interview Variations:
Pascal's Triangle I & II Unique Paths combination formula C(m+n-2, m-1)
#106

Clock & Circular Array Problems

Deep Dive Guide

Matrix, Geometry & Simulation

Core Invariant: Model circular wrap-around via (idx + step) % N. Reverse full array then reverse parts to rotate arrays in O(1) space.
Why It Matters: Used in ring buffers, round-robin CPU scheduling, and circular queues.
Common Interview Variations:
Rotate Array in O(1) space Robot bounded in circle Number of subarrays with bounded maximum
#107

Simulation – Turn-by-Turn State System

Deep Dive Guide

Matrix, Geometry & Simulation

Core Invariant: Model step-by-step evolution using queues or state arrays. Simulate turns until an elimination or termination condition is reached.
Why It Matters: Essential for gaming engines, queue scheduling, and election/voting simulations.
Common Interview Variations:
Dota2 Senate turn elimination Find the Winner of the Circular Game (Josephus) Product of the Last K Numbers
12

Wildcards & LLD / Machine Coding

Fenwick/Sparse Table, Meet-in-the-Middle, LRU, Rate Limiter, and LLD

20 patterns
#108

Median of Two Sorted Arrays (Partition Binary Search)

Deep Dive Guide

Wildcards & LLD / Machine Coding

Core Invariant: Binary search the partition cut of the shorter array in O(log(min(m, n))) time such that left elements are <= right elements.
Why It Matters: One of the most famous hard interview problems asked at Google and Meta to test deep binary search mechanics.
Common Interview Variations:
Median of two sorted arrays K-th element of two sorted arrays
Google Meta Microsoft
#109

Expression Evaluation (Shunting-Yard & Stack Parsing)

Deep Dive Guide

Wildcards & LLD / Machine Coding

Core Invariant: Use operator and operand stacks with precedence rules, or convert infix to postfix notation to evaluate arithmetic expressions.
Why It Matters: Critical for compilers, spreadsheet formula engines (Excel), and database SQL arithmetic parsers.
Common Interview Variations:
Basic Calculator I (+ - ( )) Basic Calculator II (+ - * /) Basic Calculator III (Full precedence)
#110

Number to Words (Recursive Chunking & Mapping)

Deep Dive Guide

Wildcards & LLD / Machine Coding

Core Invariant: Split integers into 3-digit groups (Billion, Million, Thousand). Map each 3-digit group recursively into English phonetic rules.
Why It Matters: Tests complex string edge-case handling, zero handling, and modular formatting logic.
Common Interview Variations:
Integer to English Words Roman to Integer Integer to Roman
#111

Max Frequency Character in a Sliding Window

Deep Dive Guide

Wildcards & LLD / Machine Coding

Core Invariant: Maintain max_freq in window. If (window_length - max_freq > k), shrink from left. Window size never decreases.
Why It Matters: Achieves clean O(n) without needing to re-scan the 26-character frequency table on each step.
Common Interview Variations:
Longest repeating character replacement Max consecutive ones III
#112

Random Pick with Weight (Prefix Sum + Binary Search)

Deep Dive Guide

Wildcards & LLD / Machine Coding

Core Invariant: Build cumulative prefix sum array. Generate random number in [1, total_weight], and binary search for target interval.
Why It Matters: Standard architecture for A/B testing bucketing, ad auction click probability, and machine learning sampling.
Common Interview Variations:
Weighted random selection Random pick with blacklist
Meta Google Twitter
#113

Interval Tree / Dynamic Interval Stream Tracking

Deep Dive Guide

Wildcards & LLD / Machine Coding

Core Invariant: Maintain non-overlapping intervals in a balanced BST (or TreeMap) to insert numbers and merge adjacent intervals dynamically.
Why It Matters: Used in dynamic memory allocators (malloc), database query windows, and streaming calendars.
Common Interview Variations:
Data stream as disjoint intervals Range module tracker
Google Bloomberg Amazon
#114

Binary Indexed Tree (Fenwick Tree)

Deep Dive Guide

Wildcards & LLD / Machine Coding

Core Invariant: Store partial sums using bitwise step i += (i & -i). Prefix sums and point updates run in O(log n) with minimal memory footprint.
Why It Matters: Much simpler to code and lower constant factor than Segment Trees for cumulative sum problems.
Common Interview Variations:
Point update & prefix sum query Count of smaller numbers after self
#115

Sparse Table (Immutable Range Queries)

Deep Dive Guide

Wildcards & LLD / Machine Coding

Core Invariant: Precompute answers for intervals of length 2^k in O(n log n). Answer idempotent queries (like min/max/gcd) in strictly O(1) time.
Why It Matters: Instant O(1) range queries for static lookup tables and Lowest Common Ancestor (LCA) queries.
Common Interview Variations:
Range Minimum Query in O(1) LCA via Euler Tour + Sparse Table
Google AtCoder Codeforces
#116

Meet in the Middle

Deep Dive Guide

Wildcards & LLD / Machine Coding

Core Invariant: Split input of size N into two halves of size N/2. Generate all 2^(N/2) subsets for both halves, then combine via two pointers/binary search.
Why It Matters: Reduces infeasible 2^40 exponential complexity to a manageable 2·2^20 operations.
Common Interview Variations:
Closest subset sum to target Smallest sufficient team Target sum combinations
#117

Monotonic Queue (Sliding Window Extremes)

Deep Dive Guide

Wildcards & LLD / Machine Coding

Core Invariant: Use a Deque maintaining decreasing values. Push new element from back while popping smaller elements; pop front if it exited window.
Why It Matters: Provides amortized O(1) time per window slide for sliding window minimum and maximum.
Common Interview Variations:
Sliding window maximum Shortest subarray with sum at least K
#118

Trie + Bitmask Hybrid

Deep Dive Guide

Wildcards & LLD / Machine Coding

Core Invariant: Combine a prefix tree with bitmask state tracking to prune constraint violations and optimize multi-word board traversals.
Why It Matters: Solves complex board searches and XOR optimizations with tight pruning bounds.
Common Interview Variations:
Word Search II with visited bitmask Max XOR of two numbers
#119

Offline Union-Find (Dynamic Connectivity in Reverse)

Deep Dive Guide

Wildcards & LLD / Machine Coding

Core Invariant: Process edge deletions in reverse as edge additions. Build connected components backwards to evaluate historical connectivity.
Why It Matters: Applied in database rollbacks, version control branching, and dynamic network reachability logs.
Common Interview Variations:
Smallest string with swaps Offline dynamic connectivity
Google Microsoft Codeforces
#120

LRU Cache (Least Recently Used Cache)

Deep Dive Guide

Wildcards & LLD / Machine Coding

Core Invariant: Combine a HashMap (for O(1) key lookup) with a Doubly Linked List (for O(1) node relocation to head upon access and eviction from tail).
Why It Matters: The single most frequently asked LLD and data structure question across Google, Amazon, and Meta.
Common Interview Variations:
LRU Cache LFU Cache (Least Frequently Used) Time-to-Live (TTL) cache
Google Amazon Meta Microsoft
#121

Rate Limiter / Token Bucket Design

Deep Dive Guide

Wildcards & LLD / Machine Coding

Core Invariant: Track API call timestamps in a queue or maintain a token bucket with continuous refill calculation: tokens = min(capacity, tokens + rate * elapsed).
Why It Matters: Essential for API gateways, DDoS defense, and third-party rate throttling.
Common Interview Variations:
Token Bucket rate limiter Sliding Window Counter Fixed window counter
Stripe Uber Amazon
#122

In-Memory File System

Deep Dive Guide

Wildcards & LLD / Machine Coding

Core Invariant: Model folders and files using an N-ary tree / Trie directory node structure supporting mkdir, ls, addContentToFile, and readContentFromFile.
Why It Matters: Core LLD / Machine Coding interview testing clean OOP class design, path tokenization, and tree encapsulation.
Common Interview Variations:
In-memory directory tree File snapshot versioning Permission modeling
Google Dropbox Amazon
#123

Logger Rate Limiter

Deep Dive Guide

Wildcards & LLD / Machine Coding

Core Invariant: Maintain a HashMap storing message string to last logged timestamp. Allow logging only if (timestamp - last_timestamp >= 10).
Why It Matters: Standard interview design question for alert throttling and log deduplication.
Common Interview Variations:
Message throttling per service Multi-tier rate levels (INFO, WARN, ERROR)
Google Netflix Amazon
#124

Parking Lot Design (OOP / LLD)

Deep Dive Guide

Wildcards & LLD / Machine Coding

Core Invariant: Design clean OOP classes for ParkingLot, Floor, ParkingSpot (Compact, Large, Handicapped), and Vehicle types with slot strategy.
Why It Matters: The canonical Object-Oriented Design interview question testing SOLID principles, enums, and encapsulation.
Common Interview Variations:
Multi-level parking floors Dynamic surge hourly pricing Electric charging spots
Amazon Uber Oyo
#125

Snake Game / Grid Simulation

Deep Dive Guide

Wildcards & LLD / Machine Coding

Core Invariant: Use a Deque to represent snake body coordinates and a HashSet for O(1) self-collision detection. Advance head and pop tail unless food is eaten.
Why It Matters: Evaluates 2D spatial coordinates, queue modeling, and self-collision mechanics in machine coding rounds.
Common Interview Variations:
Snake game mechanics Tic-Tac-Toe O(1) move evaluation Pacman maze movement
#126

Design Twitter / News Feed

Deep Dive Guide

Wildcards & LLD / Machine Coding

Core Invariant: Maintain user follow sets in a HashMap. On getNewsFeed, gather recent tweets from followees and merge using a Min/Max Heap of size 10.
Why It Matters: Bridges data structures with system design: fan-out on write versus fan-out on read.
Common Interview Variations:
Top 10 most recent posts All O(1) data structure for keys Follow/unfollow social graph
#127

Design Scheduler / Priority Job Queue

Deep Dive Guide

Wildcards & LLD / Machine Coding

Core Invariant: Execute jobs based on delay, interval, or priority. Maintain a Min-Heap sorted by scheduled_time; worker processes jobs as timestamp arrives.
Why It Matters: Essential for cron schedulers, delayed task execution, and OS process priority queues.
Common Interview Variations:
Task Scheduler with cooldown (LC 621) Rearrange string K distance apart Delayed job retry queue

Frequently Asked Questions

What are the 127 Core Coding Patterns?

The 127 Core Coding Patterns break down interview Data Structures and Algorithms into atomic, repeatable problem-solving invariants across 12 sections: Arrays, Linked Lists, Heaps/Stacks, Recursion, Dynamic Programming, Trees, Graphs, Greedy/Math, Advanced Strings/Segment Trees, Matrix Simulation, Wildcards, and Low-Level Design (LLD).

How do the 127 core patterns differ from the standard 21 macro-patterns?

Standard platforms teach 21 high-level categories (e.g. Dynamic Programming or Binary Search). The 127 core patterns drill deeper into the specific atomic variants interviewers test (e.g., 0/1 Knapsack vs. Unbounded vs. Digit DP vs. Bitmask DP, or Standard Binary Search vs. Search on Answer Space).

How should I practice these 127 patterns?

Focus on understanding the core logic and variation triggers rather than memorizing code. Start with Sections 1 to 4 (Foundations, Arrays, Linked Lists, Trees), progress to Sections 5 to 8 (DP, Graphs, Greedy), and finalize with Sections 9 to 12 (Advanced Range Queries and Low-Level Design). Check off each pattern as you solve its example problems.

Does this curriculum cover Low-Level Design (LLD) and Machine Coding?

Yes. Section 12 specifically covers the 9 essential Object-Oriented and Low-Level Design patterns required in Tier-1 technical rounds: LRU/LFU Cache, Rate Limiting Token Buckets, In-Memory File Systems, Parking Lots, Snake Game Simulation, Twitter News Feeds, and Job Schedulers.

Buy me a coffee
Daily Practice
0/0