0% revised

DSA Patterns

29 patterns · dense recall · code templates

0 / 29 revised
Data StructureAccessSearchInsertDelete
ArrayO(1)O(n)O(n)O(n)
LinkedListO(n)O(n)O(1)O(1)
Stack/QueueO(n)O(n)O(1)O(1)
HashMap—O(1)O(1)O(1)
BSTO(log n)O(log n)O(log n)O(log n)
Two Pointers
DSA
▾
Quick Recall
Sorted array → pair/window → two pointers
When to use / Signal: sorted, pair, sum, palindrome
Core idea: Use two indices moving inward/outward to solve paired/ordered problems.
python
# Two pointers - find pair sum
def two_sum_sorted(arr,target):
    i,j=0,len(arr)-1
    while i<j:
        s=arr[i]+arr[j]
        if s==target: return (i,j)
        if s<target: i+=1
        else: j-=1
    return None
Time & Space: O(n) time, O(1) space — pointers traverse once. O(n)
Classic problems: Two Sum II · Container With Most Water · Sort Colors
Gotchas: Only for sorted arrays or after sorting (cost).
Sliding Window
DSA
▾
Quick Recall
Contiguous subarray problems — maintain window sum/structure
When to use / Signal: subarray, contiguous, max sum, k-length
Core idea: Expand/contract window to maintain a condition; efficient for contiguous problems.
python
# Variable window - max sum < k
def max_subarray_at_most_k(arr,k):
    s=0;left=0;ans=0
    for right,val in enumerate(arr):
        s+=val
        while s>k and left<=right:
            s-=arr[left]; left+=1
        ans=max(ans,right-left+1)
    return ans
Time & Space: O(n) time, O(1) space — each element enters/leaves once. O(n)
Classic problems: Minimum Size Subarray Sum · Longest Substring with K Distinct
Gotchas: Careful with window boundaries; off-by-one.
Fast & Slow Pointers
DSA
▾
Quick Recall
Cycle detection / middle-of-list → fast/slow
When to use / Signal: cycle, middle, repeat
Core idea: Use two speeds; if they meet there is a cycle; for middle slow moves half speed.
python
# Floyd's cycle detection
def has_cycle(head):
    slow=fast=head
    while fast and fast.next:
        slow=slow.next; fast=fast.next.next
        if slow==fast: return True
    return False
Time & Space: O(n) time, O(1) space — pointers only. O(n)
Classic problems: Linked List Cycle · Middle of Linked List
Gotchas: Null checks for fast and fast.next.
Merge Intervals
DSA
▾
Quick Recall
Sort by start, merge overlapping intervals
When to use / Signal: intervals, overlap, calendar
Core idea: Sort intervals by start then merge by comparing end times.
python
def merge(intervals):
    intervals.sort()
    out=[]
    for s,e in intervals:
        if not out or s>out[-1][1]: out.append([s,e])
        else: out[-1][1]=max(out[-1][1],e)
    return out
Time & Space: O(n log n) time (sort), O(n) space. O(n log n)
Classic problems: Merge Intervals · Meeting Rooms II
Gotchas: Sort by start; handle equal starts.
Cyclic Sort
DSA
▾
Quick Recall
Numbers 1..n in array — place items at index
When to use / Signal: missing numbers, duplicates, 1..n
Core idea: Place each value at its correct index by swapping until correct.
python
def cyclic_sort(nums):
    i=0
    while i<len(nums):
        j=nums[i]-1
        if nums[i]!=nums[j]: nums[i],nums[j]=nums[j],nums[i]
        else: i+=1
    return nums
Time & Space: O(n) time, O(1) space. O(n)
Classic problems: Find Missing Number · First Missing Positive
Gotchas: Values must be in known bounded range.
In-place Linked List Reversal
DSA
▾
Quick Recall
Reverse pointers iteratively (prev/curr)
When to use / Signal: reverse list, reverse k
Core idea: Iteratively rewire next pointers using prev/curr/next.
python
def reverse(head):
    prev=None;cur=head
    while cur:
        nxt=cur.next
        cur.next=prev
        prev=cur; cur=nxt
    return prev
Time & Space: O(n) time, O(1) space. O(n)
Classic problems: Reverse Linked List · Reverse K Group
Gotchas: Keep next pointer before changing links.
Tree BFS
DSA
▾
Quick Recall
Level-order traversal → queue
When to use / Signal: level, shortest path on tree
Core idea: Use queue to traverse by levels; capture level info for breadth-based metrics.
python
from collections import deque
def bfs(root):
    q=deque([root])
    while q:
        node=q.popleft()
        # process node
        if node.left: q.append(node.left)
        if node.right: q.append(node.right)
Time & Space: O(n) time, O(width) space. O(n)
Classic problems: Level Order · Minimum Depth
Gotchas: Watch null root; large width space.
Tree DFS
DSA
▾
Quick Recall
Pre/in/post-order — recursion or stack
When to use / Signal: traversal, path, subtree
Core idea: Use recursion/backtracking or explicit stack for preorder/inorder/postorder.
python
def inorder(root):
    res=[]
    def dfs(n):
        if not n: return
        dfs(n.left)
        res.append(n.val)
        dfs(n.right)
    dfs(root); return res
Time & Space: O(n) time, O(h) space (recursion). O(n)
Classic problems: Inorder Traversal · Path Sum
Gotchas: Recursion depth for skewed trees.
Graph BFS
DSA
▾
Quick Recall
Shortest unweighted distance → BFS (multi-source allowed)
When to use / Signal: shortest unweighted, levels
Core idea: Queue + visited; push all sources for multi-source BFS.
python
from collections import deque
def multi_source_bfs(sources,adj):
    q=deque([(s,0) for s in sources])
    vis=set(sources)
    while q:
        u,d=q.popleft()
        # process
        for v in adj[u]:
            if v not in vis: vis.add(v); q.append((v,d+1))
Time & Space: O(V+E) time, O(V) space. O(V+E)
Classic problems: Nearest Exit · Rotten Oranges
Gotchas: Mark visited on enqueue.
Graph DFS
DSA
▾
Quick Recall
Components, cycle detection and topo via DFS
When to use / Signal: connected components, cycle, topo via back edges
Core idea: Recursively or stack explore; track recursion stack for directed-cycle detection.
python
def dfs(u):
    vis.add(u)
    for v in adj[u]:
        if v not in vis: dfs(v)
Time & Space: O(V+E) time, O(V) space. O(V+E)
Classic problems: Number of Islands · Course Schedule
Gotchas: Stack depth / iterative alternative.
Topological Sort
DSA
▾
Quick Recall
DAG ordering → Kahn or DFS post-order
When to use / Signal: dependency, build order
Core idea: Kahn: use indegree queue; DFS: push after children then reverse.
python
from collections import deque
def kahn(adj,indeg):
    q=deque([u for u in indeg if indeg[u]==0]); order=[]
    while q:
        u=q.popleft(); order.append(u)
        for v in adj[u]:
            indeg[v]-=1
            if indeg[v]==0: q.append(v)
    return order if len(order)==len(indeg) else []
Time & Space: O(V+E) O(V+E)
Classic problems: Course Schedule · Alien Dictionary
Gotchas: Detect cycle by size mismatch.
Union-Find / DSU
DSA
▾
Quick Recall
Maintain sets with parent/rank + path compression
When to use / Signal: connectivity, union queries
Core idea: Union by rank + compress paths on find.
python
def find(x):
    while x!=parent[x]: parent[x]=parent[parent[x]]; x=parent[x]
    return x
Time & Space: Inverse-Ackermann amortized. O(α(n))
Classic problems: Number of Islands II · Accounts Merge
Gotchas: Initialize parent for all nodes.
Backtracking
DSA
▾
Quick Recall
Try choices, backtrack on failure — pruning matters
When to use / Signal: combinatorial search, permutations, subsets
Core idea: DFS with state mutation & undo; prune early where possible.
python
def bt(path,choices):
    if done(path): ans.append(path[:]); return
    for c in choices:
        path.append(c); bt(path,choices); path.pop()
Time & Space: Exponential in worst-case. Exponential
Classic problems: N-Queens · Permutations
Gotchas: Prune and copy path on append.
DP — 0/1 Knapsack
DSA
▾
Quick Recall
Take/skip decisions → 2D or 1D dp
When to use / Signal: choose items bounded, capacity
Core idea: dp[i][w] = max(take, skip); compress to 1D reverse loop.
python
def knap(weights,vals,W):
    dp=[0]*(W+1)
    for i,(wt,val) in enumerate(zip(weights,vals)):
        for w in range(W,wt-1,-1): dp[w]=max(dp[w],dp[w-wt]+val)
    return dp[W]
Time & Space: O(nW) O(nW)
Classic problems: 0/1 Knapsack
Gotchas: Reverse iterate for 1D.
DP — Unbounded Knapsack
DSA
▾
Quick Recall
Items can repeat → forward loop for capacity
When to use / Signal: unbounded repeats, coin change
Core idea: Inner loop forward to allow repeating items.
python
def unbounded(weights,vals,W):
    dp=[0]*(W+1)
    for w in range(W+1):
        for i,(wt,val) in enumerate(zip(weights,vals)):
            if wt<=w: dp[w]=max(dp[w],dp[w-wt]+val)
    return dp[W]
Time & Space: O(nW) O(nW)
Classic problems: Coin Change
Gotchas: Order of loops matters.
DP — LCS / LIS
DSA
▾
Quick Recall
Subsequence alignment → DP or patience sort for LIS
When to use / Signal: subsequence, common subsequence
Core idea: LCS uses 2D dp; LIS can be O(n log n) patience algorithm.
python
# LIS n log n
import bisect
def lis(a):
    d=[]
    for x in a:
        i=bisect.bisect_left(d,x)
        if i==len(d): d.append(x)
        else: d[i]=x
    return len(d)
Time & Space: LCS O(nm), LIS O(n log n) O(n log n)
Classic problems: Longest Increasing Subsequence · Longest Common Subsequence
Gotchas: LCS space optimize with rolling array.
DP — Fibonacci-style
DSA
▾
Quick Recall
Simple recurrence → memo/tabulation
When to use / Signal: overlapping subproblems, optimal substructure
Core idea: Top-down memo or bottom-up loop; avoid recompute.
python
from functools import lru_cache
@lru_cache(None)
def fib(n):
    if n<2: return n
    return fib(n-1)+fib(n-2)
Time & Space: O(n) with memo O(n)
Classic problems: Climbing Stairs · Fibonacci
Gotchas: Stack depth with naive recursion.
DP — Grid / Matrix DP
DSA
▾
Quick Recall
Grid paths → dp[i][j] from top-left neighbors; obstacles = 0
When to use / Signal: grid, paths, min cost path
Core idea: Fill cell from left and top neighbors. dp[i][j] = f(dp[i-1][j], dp[i][j-1]).
python
def unique_paths(m, n):
    dp = [[1]*n for _ in range(m)]
    for i in range(1, m):
        for j in range(1, n):
            dp[i][j] = dp[i-1][j] + dp[i][j-1]
    return dp[m-1][n-1]
Time & Space: O(m×n) time, O(n) space with 1D optimization O(m×n)
Classic problems: Unique Paths · Minimum Path Sum · Dungeon Game
Gotchas: Handle obstacles by setting dp[i][j]=0. First row/col only have one direction.
DP — Subsequences & Partitions
DSA
▾
Quick Recall
Partition into subsets → bitmask DP or subset-sum reduction; palindrome partition → interval DP
When to use / Signal: partition, split, subsequence count
Core idea: Interval DP: dp[i][j] = best for subarray i..j. Subset DP: dp[mask] tracks which elements used.
python
# Palindrome partitioning - min cuts
def min_cut(s):
    n = len(s)
    dp = list(range(n))
    for i in range(1, n):
        if s[:i+1] == s[:i+1][::-1]:
            dp[i] = 0; continue
        for j in range(1, i+1):
            if s[j:i+1] == s[j:i+1][::-1]:
                dp[i] = min(dp[i], dp[j-1]+1)
    return dp[-1]
Time & Space: O(n²) for interval DP, O(2^n × n) for bitmask O(n²) / O(2ⁿ)
Classic problems: Palindrome Partitioning · Partition Equal Subset Sum · Word Break
Gotchas: Bitmask DP only feasible for n ≤ 20.
Greedy
DSA
▾
Quick Recall
Local optimum → globally valid for proofs
When to use / Signal: intervals, scheduling, choose min/earliest end
Core idea: Pick best local choice and prove exchange argument.
python
def interval_scheduling(intervals):
    intervals.sort(key=lambda x:x[1])
    ans=0;last=-1
    for s,e in intervals:
        if s>=last: ans+=1; last=e
    return ans
Time & Space: O(n log n) due to sort O(n log n)
Classic problems: Activity Selection · Huffman Coding
Gotchas: Requires proof; greedy can fail.
Heap / Top-K
DSA
▾
Quick Recall
Use heap for k-best or streaming medians
When to use / Signal: k largest, merge k lists, median stream
Core idea: Min-heap of size k or two-heaps for median.
python
import heapq
def k_largest(nums,k):
    h=[]
    for x in nums:
        heapq.heappush(h,x)
        if len(h)>k: heapq.heappop(h)
    return h
Time & Space: O(n log k) O(n log k)
Classic problems: Merge K Sorted Lists · Top K Frequent
Gotchas: Python heapq is min-heap.
Trie
DSA
▾
Quick Recall
Prefix store → O(len) ops
When to use / Signal: prefix search, autocomplete
Core idea: Nodes per char with children map; store end marker.
python
class TrieNode:
    def __init__(self): self.children = {}; self.end=False
class Trie:
    def __init__(self): self.root=TrieNode()
    def insert(self,s):
        cur=self.root
        for ch in s: cur=cur.children.setdefault(ch,TrieNode())
        cur.end=True
Time & Space: O(total chars) O(L)
Classic problems: Implement Trie · Auto-complete
Gotchas: Memory heavy; compress with TST or radix.
Monotonic Stack
DSA
▾
Quick Recall
Maintain monotonic stack for next greater/smaller
When to use / Signal: next greater, span, histogram
Core idea: Stack holds candidates in monotonic order, pop until condition.
python
def next_greater(a):
    res=[-1]*len(a); st=[]
    for i,x in enumerate(a):
        while st and a[st[-1]]<x: res[st.pop()]=x
        st.append(i)
    return res
Time & Space: O(n) O(n)
Classic problems: Next Greater Element · Largest Rectangle in Histogram
Gotchas: Strict vs non-strict comparisons.
Bit Manipulation
DSA
▾
Quick Recall
Use XOR/X & -X tricks for parity/lowest-bit
When to use / Signal: bits, xor, power of two
Core idea: XOR for differences; masks for sets/clears/count bits.
python
def count_bits(x):
    cnt=0
    while x:
        x &= x-1; cnt+=1
    return cnt
Time & Space: O(number of set bits) O(k)
Classic problems: Single Number · Count Bits
Gotchas: Signed shifts in some languages.
Prefix Sum / Difference Array
DSA
▾
Quick Recall
Prefix for range sums; diff array for range updates
When to use / Signal: range sum, range update
Core idea: Build prefix for O(1) range sum; diff array to batch updates.
python
def prefix(a):
    pre=[0]
    for x in a: pre.append(pre[-1]+x)
    return pre
Time & Space: O(n) preprocess, O(1) queries O(n)
Classic problems: Range Sum Query · Range Addition
Gotchas: Off-by-one indices.
Kadane's Algorithm
DSA
▾
Quick Recall
Max contiguous subarray → track local/global max
When to use / Signal: max subarray, contiguous
Core idea: Track current max ending here and global max so far.
python
def max_subarray(a):
    cur=mx=a[0]
    for x in a[1:]: cur=max(x,cur+x); mx=max(mx,cur)
    return mx
Time & Space: O(n) O(n)
Classic problems: Maximum Subarray
Gotchas: All negative arrays edge-case.
Matrix Traversal
DSA
▾
Quick Recall
Rows/cols traversal, careful with in-place transforms
When to use / Signal: matrix, grid, island
Core idea: Use directions array for grid DFS/BFS; in-place rotate uses layer swaps.
python
# DFS on grid
def dfs_grid(i,j):
    if out: return
    visited.add((i,j))
    for di,dj in ((1,0),(-1,0),(0,1),(0,-1)):
        ni,nj=i+di,j+dj
        # bounds check
Time & Space: O(n*m) O(n×m)
Classic problems: Number of Islands · Rotate Matrix
Gotchas: Mutate grid carefully; visited set.
Math / Number Theory
DSA
▾
Quick Recall
GCD/LCM & sieve for primes
When to use / Signal: primes, mod, gcd, lcm
Core idea: Use Euclid for gcd; sieve for primes; mod invariants for computations.
python
def gcd(a,b):
    while b: a,b=b,a%b
    return a
Time & Space: gcd O(log min(a,b)), sieve O(n log log n) O(log n)
Classic problems: GCD/LCM problems · Prime Sieve
Gotchas: Mod inverse exists only when coprime.