Coding Interview Problems
132 problems grouped by the pattern that solves them — plus practical backend tasks and “what does this print?” gotchas. Write your solution in Node.js, TypeScript, Python, PHP or Java and run it against test cases right in your browser.
Study lists
Arrays & Hashing
Hash maps and sets turn O(n²) lookups into O(n).
- Two Sum Find the indices of the two numbers that add up to a target.
- Contains Duplicate Return true if any value appears at least twice.
- Valid Anagram Check whether two strings are anagrams of each other.
- Group Anagrams Group words that are anagrams of each other.
- Top K Frequent Elements Return the k most frequent values.
- Product of Array Except Self Product of all other elements for each index, without division.
- Longest Consecutive Sequence Length of the longest run of consecutive integers, in O(n).
Two Pointers
Walk a sorted array from both ends or at two speeds.
Sliding Window
Grow and shrink a window over a sequence.
Stack
Matching brackets, monotonic stacks, undo histories.
Binary Search
Halve the search space on sorted or monotonic data.
Linked List
Pointer manipulation: reverse, merge, detect cycles.
Trees
DFS and BFS on binary trees and BSTs.
- Maximum Depth of Binary Tree Number of nodes on the longest root-to-leaf path.
- Invert Binary Tree Mirror a binary tree.
- Binary Tree Level Order Traversal Values of a binary tree, level by level (BFS).
- Validate Binary Search Tree Check the BST property across the whole tree.
- Lowest Common Ancestor of a BST Deepest node that is an ancestor of both values in a BST.
Graphs
Grids, BFS/DFS, topological sort.
Heap / Priority Queue
Top-K and merging sorted streams.
Intervals
Sort by start, then merge or sweep.
Dynamic Programming
Overlapping subproblems, memoization and tabulation.
Backtracking
Generate subsets, permutations and combinations.
Design & Data Structures
Build a class with the right internal structures.
- LRU Cache A fixed-capacity cache that evicts the least recently used key, with O(1) get and put.
- Token Bucket Rate Limiter Allow bursts up to a capacity while refilling at a steady rate.
- Key-Value Store with TTL An in-memory cache whose entries expire after a time-to-live.
- URL Shortener Codes (Base62) Encode numeric IDs into short Base62 codes and decode them back.
- Build an EventEmitter Implement on, off, once and emit like Node's EventEmitter.
- Row Lock Manager with Deadlock Detection Build the core of a database lock manager: grant, queue, release in FIFO order, and abort on deadlock.
- Versioned Store with Optimistic Locking Stop silent overwrites between editors: every update must name the version it was based on.
- Flash-Sale Reservations Without Overselling Hold stock for 10 minutes, enforce a per-customer limit, survive client retries and never oversell.
- Consistent Hash Ring for Shard Routing Route keys to shards on a hash ring with virtual nodes, so adding a shard only moves a slice of keys.
- Read-Your-Writes Replica Router Send reads to a replica only when it already has the user's latest write — otherwise use the primary.
- Sharded Counter for a Hot Row Spread increments of a viral post's like counter over several slots and measure the lock waits.
- Single-Flight Cache Loader When a hot key expires, let one request load it while everyone else waits — instead of a thundering herd.
- Cache with Version-Checked Sets Prevent the cache-aside stale-set race: a slow reader must not re-cache an old value after an invalidation.
- Write-Behind View Counter with Safe Flushes Buffer view counts and flush them in batches that survive crashes and are never applied twice.
Data Processing
Parse, transform, aggregate and paginate records.
- Top Endpoints from Access Logs Parse web-server log lines and return the most requested paths.
- Group Events into Sessions Split a user's event timestamps into sessions separated by inactivity gaps.
- Flatten Nested JSON Turn nested objects and arrays into a flat map with dotted keys.
- Revenue Report from CSV Parse a CSV export, skip bad rows and total paid revenue per region.
Async & Concurrency
Promises, timers, retries, concurrency limits.
- Retry with Exponential Backoff Retry a failing operation with exponential delays, but never retry non-retryable errors.
- Implement debounce() Delay a function until calls stop for `wait` ms; support cancel() and keep `this`.
- Run Async Tasks with a Concurrency Limit Map over items with at most `limit` promises in flight, keeping result order.
- Thread-Safe Counting with ExecutorService Fix a race condition with atomics and split work across a thread pool.
Language Idioms
Collections, generators, decorators, types and OOP.
- Type-safe groupBy<T, K>() Write a generic groupBy that infers key and item types.
- Result Type Instead of Exceptions Model success/failure with a discriminated union and narrow on it.
- Typed pick() and omit() Implement runtime pick/omit whose return types match Pick<T,K> and Omit<T,K>.
- Leaderboard Sorting with usort and <=> Sort associative arrays by several keys using the spaceship operator.
- Slugify a Title (Strings & Regex) Turn a title into a URL slug with a maximum length that doesn't cut words.
- Order Status Enum with Transitions Use a PHP 8.1 backed enum with methods to enforce valid state changes.
- Lazy chunked() Generator Yield fixed-size lists from any iterable — lazily, so it works on infinite streams.
- Decorator with Arguments: @retry Write a parameterised decorator that retries selected exceptions and preserves metadata.
- Immutable Money Value Object (dataclasses) Use a frozen, ordered dataclass with __add__ and __str__ for money.
- Reporting with Streams and Collectors Group, count, average and sort records using the Stream API.
- equals() and hashCode() Done Right Implement value equality so HashSet and HashMap behave correctly.
Gotchas
Scoping, equality, mutability and evaluation order.
- var in a Loop with setTimeout Why every callback sees the same `i`.
- Microtasks vs Macrotasks Order of sync code, promise callbacks, await continuations and timers.
- Type Coercion Surprises `+` vs `-` with strings, loose equality and typeof quirks.
- Numeric Enums at Runtime Auto-incremented values and reverse mappings of TypeScript enums.
- Type Assertions Don't Convert `as number` changes the type, not the value.
- readonly and as const at Runtime Compile-time immutability doesn't freeze objects.
- Mutable Default Arguments Default values are evaluated once, at definition time.
- Late-Binding Closures Lambdas look up variables when called, not when created.
- List Multiplication Shares Rows `[[0] * 3] * 3` creates three references to one row.
- PHP 8 String-to-Number Comparison How `==` changed in PHP 8 and why numeric strings still compare as numbers.
- foreach by Reference Leftover A dangling reference after `foreach (... as &$item)` corrupts the next loop.
- Array Key Casting Which keys PHP silently converts to integers.
- Integer Cache and == Why 127 == 127 but 128 != 128 for boxed Integers.
- String Immutability and Interning Methods return new strings; compile-time constants are interned.
- Integer Division and String Concatenation Left-to-right evaluation of + with numbers, chars and strings.
- Two Checkouts, One Item Left Predict what a read-modify-write checkout does when two requests interleave.
- The Stale Cache Set A slow cache-aside reader and a writer race. What ends up in the cache?
- Read Committed vs Repeatable Read A report reads a balance twice while a deposit commits in between. What does each isolation level see?
Code Clinic: Find the Bug
Off-by-ones, mutable defaults, loose equality, async races: the bugs interviewers hand you to fix.
- Fix the Binary Search A binary search that misses some targets: find the off-by-one and fix it.
- Fix the Two Sum Hash Map A one-pass Two Sum that sometimes pairs a number with itself.
- Fix the Longest Substring Without Repeats A sliding window whose left edge sometimes moves backwards.
- Fix Merge Intervals An interval merge that shrinks intervals when one contains another.
- Fix the Mutable Default Argument A Python helper whose results leak from one call into the next.
- Fix the Substring Check A contains-check that says no when the match is at the very start of the string.
- Fix the Median (JavaScript Sort) A median function that is right for single digits and wrong for 10.
- Fix the Number Parser (map + parseInt) A one-line parser that turns most of its input into NaN.
- Fix the Async Total (forEach) An async loop that returns before any of its work has finished.
- Fix the Bill Splitter Splitting money with rounding loses or invents cents.
- Fix the Pagination Helper Page 1 shows the second page of results.
- Fix the TTL Cache Expiry A TTL cache that serves entries one tick after they expired.
- Fix Removing Items While Iterating Deleting from a list inside the loop that walks it skips elements (or throws, in Java).
- Fix the Word Counter A word counter that counts the spaces between words, and counts one word in an empty string.
- Fix the Bracket Validator A bracket validator that accepts brackets that were opened and never closed.
Code Clinic: Make It Fast
Correct but slow code. Spot the hidden O(n^2) and fix it without changing the answers.
- Speed Up Contains Duplicate A correct but quadratic duplicate check that times out on large input: make it linear.
- Speed Up Two Sum The brute-force Two Sum checks every pair. Make it one pass.
- Speed Up Recursive Fibonacci Textbook recursive Fibonacci recomputes the same values billions of times. Remove the repeated work.
- Speed Up the Most Frequent Word Counting each word by rescanning the whole list is quadratic. Count once.
- Speed Up the Active-Customer Join A membership check against an array inside a loop is a hidden nested loop. Turn the lookup into O(1).
- Speed Up Range Sum Queries Re-adding every range for every query is O(n x q). Precompute prefix sums once.
- Speed Up Longest Consecutive Sequence Searching the array for x + 1 again and again is slow. Use a set and only start counting at the start of a run.
- Speed Up Subarray Sum Equals K Trying every subarray is O(n^2). Count matching prefix sums in one pass.
- Speed Up Maximum Subarray Summing every subarray is quadratic. Kadane's algorithm does it in one pass.
- Speed Up the Sliding Window Sum Re-summing every window costs O(n x k). Slide the window: add one value, remove one.
- Speed Up Pairs With Difference K Comparing every pair to find differences of k is quadratic. Look up x + k in a set.
Code Clinic: Code Review
Review real-looking pull requests: N+1 queries, injection, missing authorization, race conditions.
- Review a Laravel Orders Controller A short Laravel controller with an N+1 query, mass assignment, a missing authorization check and an unbounded query.
- Review an Express User Search Endpoint An Express route that builds SQL from the query string, returns password hashes and leaks errors.
- Review a Payment Webhook Handler A FastAPI webhook that trusts unsigned requests and credits accounts twice when the provider retries.
- Review a Sign-Up Function A registration function with a check-then-insert race, weak password hashing and an account-enumeration leak.
- Review a CSV Export Endpoint An export that loads a whole table into memory, runs a query per row and builds the CSV by hand.
- Review a React Search Component A search-as-you-type component with a request race, a leaking interval and an unstable list key.
- Review a Vue Comment List A Vue component that renders user HTML with v-html, mutates its props and combines v-if with v-for.
- Review a jQuery Shopping Cart Script Legacy jQuery that stacks event handlers on every refresh, builds HTML from server data and uses synchronous AJAX.
- Review a Python Service Client An HTTP client that logs secrets, has no timeouts, swallows every exception and retries in a tight loop.
- Review a PHP Money Transfer A balance transfer with no transaction, a lost-update race, float money and no ownership check.
- Review a Java Order Service A Spring-style singleton service with shared mutable state, a broken lazy init, leaked JDBC resources and swallowed exceptions.
- Review a Node.js Batch Processor A batch job that fires 200,000 requests at once, loads everything into memory and loses track of failures.
- Review a Laravel Queue Job A queued job that emails every user in one run, holds the whole table in memory and double-sends on retry.
- Review a TypeScript API Client A typed fetch wrapper that retries payments, trusts unvalidated JSON and stores tokens in localStorage.
- Review a Python Cache-Aside Helper A Redis cache helper with no expiry, a stampede on popular keys, pickle deserialisation and stale data after writes.