Backtracking Patterns: Subsets, Permutations, N-Queens
A practical guide to backtracking: the recursion template, pruning, classic problems with code, and complexity analysis for subsets and permutations.
90 posts.
A practical guide to backtracking: the recursion template, pruning, classic problems with code, and complexity analysis for subsets and permutations.
Learn the divide-and-conquer pattern through merge sort and quick sort, recurrence relations, the Master theorem, and how to recognize the pattern.
Learn how heaps power priority queues, why heapq runs push and pop in O(log n), and how to solve classic Top-K and merge problems in Python.
A careful walkthrough of LeetCode 15 3Sum using sort plus two pointers. We handle duplicate triplets cleanly and avoid the classic off-by-one traps.
Walk through LeetCode 121 Best Time to Buy and Sell Stock. We go from the quadratic brute force to a clean one-pass solution tracking the running minimum.
Walk through LeetCode 70 Climbing Stairs from brute force recursion to bottom-up DP, with edge cases, complexity analysis, and an interview script.
Walk through LeetCode 322 Coin Change with brute force recursion, memoization, and bottom-up DP. Includes complexity analysis and interview script.
Solve LeetCode 11 Container With Most Water with the two-pointer technique. We prove correctness and contrast it with the quadratic brute force.
Detect cycles and produce a valid course order in LeetCode 207 Course Schedule using DFS-based topological sort. Includes BFS Kahn alternative and interview script.
Solve LeetCode Daily Temperatures with a monotonic decreasing stack of indices. Includes brute force comparison, walkthrough, complexity, and interview tips.
Solve LeetCode Group Anagrams cleanly with a hash map keyed by sorted strings or character counts. Includes complexity analysis and interview talking points.
Solve LeetCode 198 House Robber with the pick-or-skip DP recurrence, then optimize to O(1) space. Includes interview script and related variants.
Solve LeetCode 226 Invert Binary Tree with a four-line recursive swap and an iterative BFS alternative, including complexity and interview talking points.
Walk through LeetCode Longest Palindromic Substring using the expand-around-center technique. Compare brute force, DP, and the optimal approach with examples.
Solve LeetCode 3 Longest Substring Without Repeating Characters using a sliding window with a hash map. We go from brute force to a clean O(n) sweep.
Design LeetCode 146 LRU Cache with a hash map and a doubly linked list to get O(1) get and put, with a clean Python implementation and interview tips.
Solve LeetCode 104 Maximum Depth of Binary Tree with a three-line recursive DFS and an iterative BFS alternative, with complexity analysis and interview tips.
A clear walkthrough of LeetCode 53 Maximum Subarray. We build Kadane's algorithm from first principles and contrast it with the divide and conquer approach.
Solve LeetCode 21 Merge Two Sorted Lists with the dummy-head pointer pattern, plus a recursive variant, edge cases, and interview explanation tips.
Design a stack that supports push, pop, top, and getMin in constant time. Walkthrough of the two-stack and pair-stack solutions with edge cases and interview tips.
Solve LeetCode 200 Number of Islands with grid DFS and BFS, including a union-find variant, edge-case handling, and clear interview talking points.
Walk through LeetCode 206 Reverse Linked List with iterative pointer flipping and a clean recursive solution, plus complexity and interview talking points.
Generate all subsets of an array in LeetCode 78 using backtracking and iterative bit-mask approaches. Includes complexity analysis and interview script.
A complete walkthrough of LeetCode 1 Two Sum. We move from the obvious nested loop to a single-pass hash map and dissect why it works.
A clean walkthrough of LeetCode Valid Parentheses with the optimal stack solution. Covers edge cases, complexity, and how to explain the approach in interviews.
A complete walkthrough of LeetCode Valid Anagram. Compare the sorting approach with the optimal hash map counting solution and learn how to explain it in interviews.
Solve LeetCode 139 Word Break with bottom-up dynamic programming. Includes brute force, edge cases, complexity analysis, and an interview script.
The essential math toolkit for interviews: Euclidean GCD, sieve of Eratosthenes, modular exponentiation, modular inverses, and common pitfalls.
A practical introduction to tries: node structure, insert, search, prefix queries, memory tradeoffs, and classic interview problems like word search.
Learn the union-find data structure with union by rank and path compression, why it runs in near-O(1) amortized, and how it powers Kruskal and islands.
Understand Bellman-Ford's relaxation loop, how it handles negative edges, detects negative cycles, and why it costs more than Dijkstra.
Learn Dijkstra's shortest path algorithm with a clean Python implementation, complexity analysis, and the priority queue intuition behind it.
Implement and understand the Fenwick tree, also called the binary indexed tree, for O(log n) prefix sums and point updates in just a few lines.
Build minimum spanning trees with Kruskal's union-find approach and Prim's priority queue approach, with side-by-side Python implementations.
LeetCode 102 in detail — the queue-with-size BFS pattern, why DFS still works, and how this template extends to zigzag and right-side view.
LeetCode 133 walked through — why a hash map from original to copy is the entire idea, plus the BFS variant for stack-limited environments.
Solve LeetCode 39 Combination Sum with a clean backtracking template. Pruning, duplicate avoidance, complexity discussion, and interview script.
LeetCode 72 fully unpacked — the three-operation recurrence, the 2D table, and the rolling-array space optimization that makes interviewers nod.
Solve LeetCode 22 Generate Parentheses with counting-based backtracking. Clean invariant, walkthrough, complexity discussion, and interview tips.
LeetCode 230 in detail — the inorder traversal trick, the iterative early-exit version, and the follow-up that haunts FAANG interviews.
Solve LeetCode 17 Letter Combinations of a Phone Number with backtracking. Mapping setup, recursive enumeration, complexity, and interview walkthrough.
Solve LeetCode 128 Longest Consecutive Sequence in O(n) using a hash set and a start-of-run check. Walkthrough, edge cases, and interview script.
LeetCode 300 in detail — the O(n^2) DP, the O(n log n) patience-sorting trick with binary search, and when each one matters.
LeetCode 235 walked through end to end — why BST ordering collapses LCA into a one-line traversal, and the iterative version that needs zero extra space.
LeetCode 417 explained — why you should flood from the oceans inward, not from each cell outward, and how the intersection gives the answer.
LeetCode 112 in detail — the DFS-with-decrement trick, why the leaf condition is the whole problem, and the variants that build on it.
Solve LeetCode 46 Permutations with backtracking and a used array. Compare swap-in-place vs used-array, walkthrough, complexity, and interview tips.
Solve LeetCode 238 Product of Array Except Self in O(n) without division using prefix and suffix passes. Clean walkthrough plus interview script.
Solve LeetCode 48 Rotate Image in place by transposing and reversing each row. Walkthrough, edge cases, complexity, and interview script.
Solve LeetCode 33 Search in Rotated Sorted Array in O(log n) with modified binary search. Pivot detection, half-decision logic, and interview talking points.
LeetCode 297 fully unpacked — the preorder-with-nulls encoding, the iterator-driven decoder, and why level-order is a worse choice than it looks.
Solve LeetCode 239 Sliding Window Maximum in O(n) using a monotonic deque. Step-by-step walkthrough, interview script, and complexity analysis.
Solve LeetCode 54 Spiral Matrix with the four-boundary walk pattern. Clean implementation, edge cases for rectangles, complexity, and interview tips.
Solve LeetCode 347 Top K Frequent Elements with both a min-heap and a bucket sort approach. Trade-offs, complexity, and interview-ready walkthrough.
Solve LeetCode 42 Trapping Rain Water in linear time and constant space using the two-pointer technique. Brute force, optimal walkthrough, and interview talk track.
LeetCode 62 in two ways — the O(m * n) grid DP that interviewers expect and the binomial-coefficient closed form that surprises them.
LeetCode 98 in full — the seductive wrong answer, the correct min/max bounds approach, and how to defend it in an interview.
LeetCode 127 walked through — the wildcard-pattern adjacency trick, why BFS is mandatory, and the bidirectional speedup.
Learn segment trees for fast range sum, min, and max queries with point updates, including a clean iterative Python implementation.
Compare Kahn's BFS-based topological sort with DFS-based postorder, with Python implementations, complexity, and cycle detection.
The everyday array patterns every DSA learner should know — traversal, linear search, insertion, deletion, reversal, rotation, prefix sums, Kadane's preview, and the one-pass habit.
Ten classic array interview problems with examples, approach, complexity, and clean Python solutions — Two Sum, Best Time to Buy/Sell Stock, Kadane's, Rotate Array, Product Except Self, and more.
A beginner's introduction to arrays — contiguous memory, indexing, the Python list vs C array caveat, time complexity of read/write/insert/delete, and 1D vs 2D arrays.
A practical introduction to binary trees — the TreeNode class, terminology (full, complete, perfect, balanced), height vs depth, BSTs, and the small calculations you need to reason about tree problems.
A practical guide to Big-O notation — O(1), O(log n), O(n), O(n log n), O(n^2), and beyond, with code examples, best/average/worst case, and a brief look at amortized and space complexity.
Eight classic binary tree interview problems with examples, approach notes, and clean Python solutions — max depth, same tree, invert, symmetric, path sum, LCA, validate BST, and serialize/deserialize.
A practical introduction to bit manipulation in Python — binary representation, the bitwise operators, two's complement, and the common operations to set, clear, toggle, and check individual bits.
Six classic bit manipulation problems — Single Number, Number of 1 Bits, Power of Two, Counting Bits, Missing Number, Reverse Bits — plus the tricks that make them tick: n & (n-1), n & -n, and XOR cancellation.
A practical guide to the four canonical binary tree traversals — recursive and iterative versions, when to use each, and the patterns that make them click.
Eight classic dynamic programming problems — Climbing Stairs, House Robber, Coin Change, LIS, Word Break, 0/1 Knapsack, Edit Distance, and LCS — each with Python solutions and DP tables.
An introduction to dynamic programming — overlapping subproblems, optimal substructure, top-down memoization, and bottom-up tabulation, with worked examples in Python.
A practical guide to BFS and DFS on graphs — recursive and iterative DFS, BFS with a deque, shortest paths on unweighted graphs, connected components, cycle detection, and five classic practice problems.
A practical introduction to graphs — directed vs undirected, weighted vs unweighted, cyclic vs acyclic, and the three main representations (adjacency list, adjacency matrix, edge list) with Python code.
How hash functions, hash maps, and hash sets work — the intuition behind buckets and collisions, chaining vs open addressing, average and worst-case complexity, and the Python containers built on them.
An introduction to greedy algorithms — when the locally best choice gives a globally optimal answer, when it doesn't, the exchange argument, and six classic problems.
Eight classic hash map problems with worked Python solutions — Two Sum, Group Anagrams, Subarray Sum Equals K, Longest Consecutive Sequence, Top K Frequent Elements, and more.
The core operations every linked list problem builds on — inserting at head/tail/middle, deleting by value, reversing iteratively and recursively, finding the middle, and detecting a cycle.
A practical introduction to linked lists — what a node is, singly vs doubly linked, head and tail, how arrays and linked lists differ, and a clean Python implementation you can build on.
Eight classic linked-list interview problems — reverse, detect cycle, merge sorted lists, remove Nth from end, cycle start, palindrome, add two numbers, and intersection — each with a worked Python solution.
A practical introduction to recursion — the base case, the recursive case, the call stack, and how to think about problems that solve themselves through smaller versions of themselves.
A practical guide to binary search — the classic template, off-by-one traps, Python's bisect module, and the binary-search-on-answer pattern, with six worked problems.
A practical guide to sliding window — fixed-size vs variable-size windows, expand/shrink invariants, and six classic problems with worked Python solutions.
A tour of the five sorting algorithms every programmer should know — their ideas, Big-O time and space, stability, and Python implementations, plus when to just use sort().
A practical introduction to stacks and queues — LIFO vs FIFO, using a Python list as a stack, collections.deque as a queue, and the real-world problems each one solves cleanly.
Eight classic stack and queue interview problems with worked Python solutions — Valid Parentheses, Min Stack, Daily Temperatures, Sliding Window Maximum, and more.
An introduction to strings for data structures and algorithms — immutability, indexing, slicing, common operations, ASCII versus Unicode, and the two-pointer and frequency-counter patterns you will use everywhere.
A practical tour of substring search — the naive O(n·m) scan, the KMP algorithm with its LPS array, and the Rabin-Karp rolling hash. Worked examples, code, and intuition for when to use each.
Eight classic string problems with worked Python solutions — Valid Anagram, Group Anagrams, Longest Substring Without Repeating Characters, Longest Palindromic Substring, and more.
A practical guide to the two pointers technique — opposite-end and same-direction patterns, when to use each, and six classic interview problems with worked solutions.
A beginner-friendly introduction to data structures and algorithms — what they are, why they matter for interviews and real performance, and how to actually start learning DSA.