Worked problems and reference notes on algorithms and data structures, organized by topic rather than one page per problem.
- 01/138
Pattern Recognition Cheatsheet
Common hints in problem statements that point toward specific algorithms or data structures.
- 02/138
Algorithm Design Paradigms
The three broad approaches to algorithm design — divide and conquer, greedy algorithms, and dynamic programming.
- 03/138
Backtracking
A divide-and-conquer method for exhaustive search that prunes branches that can't lead to a result, illustrated with permutation generation.
- 04/138
The Karatsuba Algorithm
A divide-and-conquer fast multiplication algorithm that reduces the number of multiplications needed to multiply two large numbers.
- 05/138
Recursion Basics
Base cases vs. recursive cases, how a recursive call stack actually unwinds (walked through with a factorial and a print-N example), and a checklist for approaching new recursion problems.
- 06/138
Recursion Practice Problems
Small warm-up recursion problems — printing N times, printing in ascending/descending order, and summing the first N numbers both the parameterized way and the functional way.
- 07/138
Reversing an Array Recursively
Reversing an array by swapping the first and last elements, then recursing on the inner subarray.
- 08/138
Checking for a Palindrome Recursively
Comparing the first and last characters of a string and recursing inward until the middle is reached.
- 09/138
Fibonacci Number Recursively
The classic recursive Fibonacci definition, and why it's inefficient for large n without memoization.
- 10/138
The Two-Pointer Technique
The two variations of the two-pointer approach — opposite-directional and equi-directional (fast/slow) — illustrated with two sum on a sorted array and linked-list cycle detection.
- 11/138
Find the Duplicate Number
Using Floyd's Tortoise and Hare cycle detection to find a duplicate in an array without modifying it or using extra space.
- 12/138
Middle of the Linked List
Finding the middle node of a singly linked list with a brute-force counting pass vs. the fast/slow pointer trick.
- 13/138
Linked List Cycle II
Finding where a cycle begins in a linked list — a HashMap approach vs. Floyd's Tortoise and Hare in constant space.
- 14/138
Linked List Cycle
Detecting whether a linked list contains a cycle — a HashSet approach vs. Floyd's Tortoise and Hare in constant space.
- 15/138
Length of Loop in a Linked List
Determining a cycle's length with a HashMap of visit timestamps vs. Floyd's Tortoise and Hare plus a loop-length counting step.
- 16/138
Bubble Sort
Pushing the maximum value to the end through adjacent swaps, with an early-exit optimization for already-sorted input.
- 17/138
Selection Sort
Building a sorted section one minimum at a time by repeatedly scanning the unsorted remainder.
- 18/138
Insertion Sort
Building a sorted section one element at a time by inserting each new element into its correct position, like sorting playing cards in your hand.
- 19/138
Merge Sort
The divide-and-merge algorithm — split down to single elements, then merge back together in sorted order — worked through with pseudocode and two C++ implementations.
- 20/138
Quick Sort
Pivot selection, partitioning smaller/larger elements around it, and recursing on each side — with pseudocode and a full C++ implementation.
- 21/138
Heap Sort
An upgraded selection sort that uses a heap to efficiently find the next largest element instead of scanning linearly.
- 22/138
Binary ↔ Decimal Conversion
Converting decimal to binary by repeated division, and binary to decimal by summing powers of 2, with Java implementations of both.
- 23/138
Bitwise Operators
The five bitwise operators — AND, OR, XOR, SHIFT, and NOT — worked through by hand with binary examples, including 2's complement for negative results.
- 24/138
Hashing
Trading a linear scan for a pre-storing/fetching approach — the intuition behind hash arrays, worked through with a frequency-counting example.
- 25/138
Prefix Sum: Product of Array Except Self
Computing result[i] as the product of every element except nums[i], in O(n) time and O(1) extra space, without division.
- 26/138
Classes and Objects in Python
What a class is, how instance methods work, and a from-scratch Employee example plus a simpler Car example.
- 27/138
Inheritance in Python
Creating a subclass that inherits properties and methods from a parent class, illustrated with an ElectricCar extending Car.
- 28/138
Polymorphism in Python
Treating different classes as objects of a common superclass, illustrated with a shared display_info function.
- 29/138
Encapsulation in Python
Restricting direct access to an object's components using protected and private attribute naming conventions.
- 30/138
Abstraction in Python
Hiding implementation details behind an abstract base class and abstractmethod, illustrated with Animal, Dog, and Cat.
- 31/138
Operator Overloading: A Fraction Class
Implementing __str__, __add__, __eq__, __mul__, __sub__, and __truediv__ on a Fraction class, plus the GCD helper it depends on.
- 32/138
Reverse a Singly Linked List
Reversing the data via a stack vs. reversing the links in place with three pointers.
- 33/138
Palindrome Linked List
Checking whether a linked list's values read the same forward and backward — a stack approach vs. an O(1)-space fast/slow pointer + in-place reversal.
- 34/138
Odd-Even Linked List
Grouping odd-indexed nodes before even-indexed nodes while preserving relative order — an extra-space approach vs. in-place pointer rewiring.
- 35/138
Deleting Linked List Nodes
Deleting the head, the tail, and the kth node of a singly linked list.
- 36/138
Remove Nth Node From End of List
A two-pass counting approach vs. a one-pass two-pointer approach with a dummy node to handle removing the head cleanly.
- 37/138
Intersection of Two Linked Lists
Finding the node where two linked lists intersect — nested loops, hashing, and the elegant two-pointer swap-to-other-list trick.
- 38/138
Reverse Nodes in k-Group
Reversing a linked list k nodes at a time in place, leaving any final incomplete group untouched.
- 39/138
Counting Digits
Counting the number of individual digits in a number by repeatedly dividing by 10.
- 40/138
Extracting Digits
Printing the individual digits of a number using the modulo and divide-by-10 trick.
- 41/138
Reversing a Number
Reversing the digits of a number by extracting the last digit and appending it to a running reversed number.
- 42/138
Armstrong Numbers
Checking whether a number equals the sum of the cubes of its individual digits.
- 43/138
Printing All Divisors
Finding all numbers that evenly divide a given number by looping from 1 to n.
- 44/138
Checking for Primality
The brute-force factor-counting check for a prime number, optimized to only check up to the square root.
- 45/138
GCD / HCF
Finding the greatest common divisor — naive loop, loop bounded by the smaller number, and the much faster Euclidean algorithm.
- 46/138
Adding Digits (Digital Root)
Repeatedly summing a number's digits until one remains — and the O(1) modulo-9 shortcut that avoids simulating the process.
- 47/138
Counting Odd Numbers in a Range
Counting odd numbers in an inclusive [low, high] range in O(1) using the range size and boundary parity.
- 48/138
Merge Strings Alternately
Merging two strings by alternating characters from each, appending the remainder of the longer string at the end.
- 49/138
Reverse Words in a String
Trimming and splitting on whitespace, reversing the word array with two pointers, then rejoining with a single space.
- 50/138
Ransom Note
Checking whether a string can be built from the letters of another, using a 26-slot frequency count.
- 51/138
Remove Outermost Parentheses
Stripping the outermost parentheses from each primitive substring of a valid parentheses string using a depth counter.
- 52/138
Maximum Nesting Depth of Parentheses
Tracking the deepest point in a valid parentheses string using a stack's size at each open paren.
- 53/138
Roman to Integer
Converting a Roman numeral string to an integer using a symbol-value map and the subtract-if-smaller-comes-before-larger rule.
- 54/138
String to Integer (atoi)
Implementing atoi from scratch — skipping whitespace, handling the sign, converting digits, and guarding against overflow before it happens.
- 55/138
Palindrome and Anagram Checks
Checking whether a string reads the same reversed, and whether two strings are anagrams of each other.
- 56/138
Check if a Word Occurs as a Prefix in a Sentence
Finding the first word in a sentence that has a given search word as its prefix.
- 57/138
Lower Bound
Finding the smallest index where arr[i] >= x in a sorted array — linear search vs. binary search.
- 58/138
Upper Bound
Finding the smallest index where arr[i] > x, the strictly-greater counterpart to lower bound.
- 59/138
Search Insert Position
Returning a target's index if present, or its insertion index otherwise — exactly the lower bound problem.
- 60/138
First and Last Position of an Element
Finding both the first and last index of a target in a sorted array by running a modified binary search twice.
- 61/138
Search in a Rotated Sorted Array
Finding a target in a rotated sorted array by identifying which half is sorted at each step.
- 62/138
Search in a Rotated Sorted Array II
Handling duplicates in the rotated-array search by shrinking the search space when the sorted half is ambiguous.
- 63/138
Minimum in a Rotated Sorted Array
Finding the minimum of a rotated sorted array by always keeping the leftmost element of whichever half is sorted.
- 64/138
Minimum in a Rotated Sorted Array II
Finding the minimum of a rotated sorted array that may contain duplicates, shrinking the range when the sorted half is ambiguous.
- 65/138
How Many Times Has an Array Been Rotated
The rotation count of a sorted-then-rotated array equals the index of its minimum element.
- 66/138
Peak Index in a Mountain Array
Finding the peak of a strictly-increases-then-decreases array by comparing each midpoint to its right neighbor.
- 67/138
Find Peak Element
Finding any element greater than both neighbors in a 1D array, treating array edges as negative infinity.
- 68/138
Single Element in a Sorted Array
Finding the one non-duplicated element in a sorted array of pairs, using index-parity patterns to binary search.
- 69/138
Square Root (Floor Value)
Finding floor(sqrt(n)) with linear search vs. binary search, exploiting that squaring increases monotonically.
- 70/138
Nth Root of a Number
Finding the integer nth root of a number (or -1 if none exists) with linear search vs. binary search.
- 71/138
Koko Eating Bananas
Binary searching over possible eating speeds to find the minimum that finishes all banana piles within h hours.
- 72/138
Kth Missing Positive Number
Finding the kth missing positive integer from a strictly increasing array, using how far each value has drifted from its expected position.
- 73/138
Minimum Days to Make M Bouquets
Binary searching over possible days to find the earliest point where m bouquets of k adjacent bloomed roses become possible.
- 74/138
Smallest Divisor Given a Threshold
Binary searching for the smallest divisor whose element-wise ceiling-division sum stays within a threshold.
- 75/138
Capacity to Ship Packages Within D Days
Binary searching over ship capacities to find the minimum that ships all packages within a day limit.
- 76/138
Aggressive Cows
Binary searching to maximize the minimum distance between cows placed in stalls.
- 77/138
Allocate Books
Binary searching to minimize the maximum pages any one student reads, given contiguous book allocation.
- 78/138
Split Array Largest Sum
Binary searching to minimize the largest subarray sum when splitting an array into k contiguous parts.
- 79/138
Search a 2D Matrix
Treating a fully row-major-sorted matrix as one flattened array and binary searching it directly without actually flattening.
- 80/138
Search a 2D Matrix II
Searching a matrix with sorted rows and columns (but no full-matrix ordering guarantee) by starting at the top-right corner and eliminating a row or column each step.
- 81/138
Row with the Maximum Number of Ones
Using lower bound per-row on a 0/1 sorted matrix to count ones without scanning every cell.
- 82/138
Find a Peak Element in a 2D Matrix
Binary searching over columns, using each column's row-max as a proxy, to find any element greater than its 4 neighbors.
- 83/138
Median of a Row-Wise Sorted Matrix
Binary searching over the value range of a matrix, counting elements <= mid per row via upper bound, to find the median without fully sorting.
- 84/138
Kth Element of Two Sorted Arrays
Finding the kth smallest element across two sorted arrays — full merge, two-pointer simulation, and a divide-and-conquer partition approach.
- 85/138
Median of Two Sorted Arrays
Finding the median across two sorted arrays by tracking only the two middle positions while merging, without storing the full merged result.
- 86/138
Second Largest Element
Finding the second largest element in an array in a single pass, without sorting, handling duplicates correctly.
- 87/138
Check if an Array Is Sorted
A single linear pass comparing each element to the previous one.
- 88/138
Remove Duplicates In-Place from a Sorted Array
Deduplicating a sorted array in place using a HashSet vs. the two-pointer technique that exploits the existing order.
- 89/138
Rotate an Array by K Places
Left-rotating an array using a temp array vs. the three-reversal trick that needs no extra space.
- 90/138
Move Zeros to the End
Preserving non-zero order while pushing all zeros to the end, using a temp array vs. two pointers in place.
- 91/138
Union of Two Sorted Arrays
Combining two sorted arrays into a deduplicated, sorted union using a set vs. a two-pointer merge.
- 92/138
Intersection of Two Sorted Arrays
Finding elements common to both sorted arrays (duplicates allowed) with a visited-marker brute force vs. two pointers.
- 93/138
Missing Number
Finding the one missing number from 1..n using a sum formula or XOR, both in a single pass.
- 94/138
Maximum Consecutive Ones
Tracking the longest run of consecutive 1s in a binary array in a single pass, including the trailing-run edge case.
- 95/138
Single Number (Appears Once)
Finding the one element that appears once while everything else appears twice, via nested loops, a hashmap, or XOR.
- 96/138
Longest Subarray with Sum K
Finding the longest contiguous subarray summing to K — brute force, prefix sum + hashmap (handles negatives), and a sliding window for positive-only arrays.
- 97/138
Two Sum
Finding whether (or where) two array elements sum to a target — nested loops vs. a single hashmap pass.
- 98/138
Sort an Array of 0s, 1s, and 2s
The Dutch National Flag problem — sorting a three-valued array in a single pass with three pointers.
- 99/138
Majority Element
Finding the element appearing more than n/2 times using nested loops, a hashmap, or Moore's Voting Algorithm.
- 100/138
Maximum Subarray Sum (Kadane's Algorithm)
Finding the contiguous subarray with the largest sum, from O(n³) brute force down to Kadane's O(n) single pass, plus a variant that returns the subarray itself.
- 101/138
Best Time to Buy and Sell Stock
Maximizing profit from a single buy/sell pair by tracking the minimum price seen so far.
- 102/138
Rearrange Array Elements by Sign
Alternating positive and negative values while preserving relative order, for both equal and unequal counts of each sign.
- 103/138
Next Permutation
Finding the next lexicographically larger arrangement of an array's elements using the breakpoint + swap + reverse technique.
- 104/138
Longest Consecutive Sequence
Finding the longest run of consecutive integers regardless of array order — brute force, sort-first, and an O(n) HashSet approach.
- 105/138
Set Matrix Zeroes
Zeroing out every row and column containing a zero, without the cascading false-zero bug, using O(n+m) marker arrays.
- 106/138
Rotate a Matrix by 90 Degrees (In Place)
Rotating an n×n matrix clockwise with a new matrix vs. transposing and reversing rows in place.
- 107/138
Find the Peaks (1D Array)
Finding every index whose value is strictly greater than both its neighbors.
- 108/138
Spiral Traversal of a Matrix
Printing a matrix in spiral order using four shrinking boundaries.
- 109/138
Jump Game
Determining if the last index is reachable by tracking the farthest reachable index in a single pass.
- 110/138
Number of Subarrays with Sum K
Counting (not just finding) subarrays summing to K using a prefix-sum hashmap of counts.
- 111/138
Pascal's Triangle
Three related problems — the element at a given row/column, printing a single row, and printing the whole triangle — all without recomputing from scratch.
- 112/138
Three Sum
Finding all unique triplets summing to zero — three-pointer plus set dedup, hashing to cut a loop, then sort + two pointers with no set needed at all.
- 113/138
Three Sum Closest
Finding the triplet whose sum is closest to a target, using sort + two pointers and stopping early on an exact match.
- 114/138
Four Sum
Finding all unique quadruplets summing to a target — nested loops, hashing to drop a loop, then sort + two pointers extending the Three Sum pattern.
- 115/138
Largest Subarray with Sum 0
Finding the longest zero-sum subarray using a prefix-sum hashmap that tracks each sum's first occurrence.
- 116/138
Merge Overlapping Intervals
Merging all overlapping intervals into the minimum number of non-overlapping ones by sorting and extending in place.
- 117/138
Merge Two Sorted Arrays Without Extra Space
Merging two sorted arrays in place — swapping from the ends, and the Shell Sort–style Gap Method.
- 118/138
Find the Repeating and Missing Numbers
Finding the one duplicated and one missing number from a 1..n array using hashing vs. a sum-and-sum-of-squares equation system.
- 119/138
Count Reverse Pairs
Counting pairs where arr[i] > 2*arr[j] using a merge-sort-based counting step instead of nested loops.
- 120/138
Maximum Product Subarray
Finding the contiguous subarray with the largest product using prefix/suffix products that handle negatives and zeros.
- 121/138
Kids With the Greatest Number of Candies
Checking whether giving each kid all the extra candies would tie or beat the current maximum.
- 122/138
Can Place Flowers
Checking whether n new flowers can be planted in a flowerbed without any two being adjacent.
- 123/138
Determine if Two Events Have Conflict
Checking whether two HH:MM time ranges overlap by converting both to minutes since midnight.
- 124/138
Container With Most Water
Finding the two bars that hold the most water using brute force vs. two pointers that always move the shorter bar.
- 125/138
Nodes: The Building Block of Linked Structures
What a node is and how to implement one with value/next pointers in Python and Java.
- 126/138
Array Methods (Python & Java)
Reference for Python's array module methods and a Java array sort-and-search example.
- 127/138
List Methods & Operations (Python)
Reference for Python's built-in list methods and sequence operations.
- 128/138
Dictionary Operators & Methods (Python)
How Python dictionaries are created, plus their core operators and methods.
- 129/138
Set Operations & Methods (Python)
Python set membership operators and the core set methods for union, intersection, and difference.
- 130/138
Stack: LIFO Operations
How a stack's push, pop, and peek operations work, tracked with a TOP pointer.
- 131/138
String Methods (Python & Java)
Reference for Python's and Java's built-in string methods.
- 132/138
Singly Linked List
A list with one pointer per node, traversable in a single direction only.
- 133/138
Doubly Linked List Operations
Insert-before-head, insert-before-tail, delete-tail, and reverse operations on a doubly linked list.
- 134/138
Linked List Operations: Pseudocode & Boundary Conditions
Add/remove at head and tail, traversal, and node deletion, with the boundary conditions each operation needs to handle.
- 135/138
Queue: FIFO Operations
How a queue's enqueue, dequeue, and peek operations work, tracked with FRONT and REAR pointers.
- 136/138
Circular Queue
How wrapping REAR and FRONT around the end of the array solves a simple queue's wasted-space problem.
- 137/138
Priority Queue
How elements are served by priority rather than arrival order, typically backed by a heap.
- 138/138
Deque (Double-Ended Queue)
Insert/delete from both front and rear, plus the full/empty checks for an array-backed deque.