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

Top 25 most asked The problems that come up again and again in screens and onsites, across all five languages. 25 problems 1-week interview sprint Four problems a day, one pattern family at a time — arrays to dynamic programming in seven days. 28 problems Practical backend tasks Take-home and pairing-round style tasks: caches, rate limiters, retries, log and CSV processing. 10 problems Data consistency at scale Concurrency, locking, reservations, caching and sharding tasks from real high-traffic systems. 13 problems Node.js interview warm-up Event loop, closures, async concurrency and the Node.js practicals interviewers love. 9 problems TypeScript interview warm-up Generics, discriminated unions, utility types and what types do (not) do at runtime. 9 problems Python interview warm-up Mutable defaults, closures, generators, decorators and dataclasses — plus classic problems. 9 problems PHP interview warm-up PHP 8 comparisons, references, array keys, enums and the array/string functions you'll be asked to use. 9 problems Java interview warm-up Integer caching, strings, equals/hashCode, streams and concurrency — the Java fundamentals screens probe. 9 problems Find the bug Code that looks right and is not. Run it, find the bug, fix it with the smallest change. 15 problems Make it fast Correct but too slow. Find the hidden quadratic loop and bring every case under the time limit. 11 problems Code review classics Pull-request snippets with the problems interviewers expect you to catch: security, performance, reliability. 15 problems

Arrays & Hashing

Hash maps and sets turn O(n²) lookups into O(n).

  1. Two Sum Find the indices of the two numbers that add up to a target. Easy Most asked All 5 languages
  2. Contains Duplicate Return true if any value appears at least twice. Easy All 5 languages
  3. Valid Anagram Check whether two strings are anagrams of each other. Easy All 5 languages
  4. Group Anagrams Group words that are anagrams of each other. Medium Most asked All 5 languages
  5. Top K Frequent Elements Return the k most frequent values. Medium Most asked All 5 languages
  6. Product of Array Except Self Product of all other elements for each index, without division. Medium All 5 languages
  7. Longest Consecutive Sequence Length of the longest run of consecutive integers, in O(n). Medium All 5 languages

Two Pointers

Walk a sorted array from both ends or at two speeds.

  1. Valid Palindrome Is the string a palindrome, ignoring case and non-alphanumerics? Easy All 5 languages
  2. 3Sum All unique triplets that sum to zero. Medium Most asked All 5 languages
  3. Container With Most Water Pick two lines that hold the most water. Medium All 5 languages

Sliding Window

Grow and shrink a window over a sequence.

  1. Best Time to Buy and Sell Stock Max profit from one buy and one later sell. Easy Most asked All 5 languages
  2. Longest Substring Without Repeating Characters Length of the longest substring with all-distinct characters. Medium Most asked All 5 languages
  3. Minimum Window Substring Smallest substring of s containing every character of t. Hard All 5 languages

Stack

Matching brackets, monotonic stacks, undo histories.

  1. Valid Parentheses Check that brackets are balanced and properly nested. Easy Most asked All 5 languages
  2. Daily Temperatures Days until a warmer temperature, using a monotonic stack. Medium All 5 languages
  3. Min Stack A stack that returns its minimum in O(1). Medium All 5 languages

Linked List

Pointer manipulation: reverse, merge, detect cycles.

  1. Reverse Linked List Reverse a singly linked list. Easy Most asked All 5 languages
  2. Merge Two Sorted Lists Merge two sorted linked lists into one sorted list. Easy Most asked All 5 languages
  3. Linked List Cycle Detect whether a linked list has a cycle (Floyd's algorithm). Easy All 5 languages
  4. Remove Nth Node From End of List Delete the n-th node from the end in one pass. Medium All 5 languages

Trees

DFS and BFS on binary trees and BSTs.

  1. Maximum Depth of Binary Tree Number of nodes on the longest root-to-leaf path. Easy All 5 languages
  2. Invert Binary Tree Mirror a binary tree. Easy All 5 languages
  3. Binary Tree Level Order Traversal Values of a binary tree, level by level (BFS). Medium Most asked All 5 languages
  4. Validate Binary Search Tree Check the BST property across the whole tree. Medium Most asked All 5 languages
  5. Lowest Common Ancestor of a BST Deepest node that is an ancestor of both values in a BST. Medium All 5 languages

Graphs

Grids, BFS/DFS, topological sort.

  1. Number of Islands Count connected groups of land cells in a grid. Medium Most asked All 5 languages
  2. Course Schedule Can all courses be finished given prerequisites? (cycle detection) Medium All 5 languages
  3. Find Deadlocked Transactions Given who-waits-for-whom edges from a lock monitor, report the transactions stuck in a deadlock cycle. Medium All 5 languages

Heap / Priority Queue

Top-K and merging sorted streams.

  1. Kth Largest Element in an Array The k-th largest value without fully sorting. Medium Most asked All 5 languages

Intervals

Sort by start, then merge or sweep.

  1. Merge Intervals Merge all overlapping intervals. Medium Most asked All 5 languages
  2. Insert Interval Insert an interval into a sorted, non-overlapping list and merge. Medium All 5 languages
  3. Find Free Meeting Slots Given busy blocks, list free slots in the working day long enough for a meeting. Medium All 5 languages

Dynamic Programming

Overlapping subproblems, memoization and tabulation.

  1. Climbing Stairs Ways to climb n stairs taking 1 or 2 steps at a time. Easy Most asked All 5 languages
  2. House Robber Max sum of non-adjacent elements. Medium All 5 languages
  3. Coin Change Fewest coins that make up an amount. Medium Most asked All 5 languages
  4. Longest Increasing Subsequence Length of the longest strictly increasing subsequence. Medium All 5 languages

Backtracking

Generate subsets, permutations and combinations.

  1. Subsets All subsets (the power set) of distinct integers. Medium All 5 languages
  2. Permutations All orderings of distinct integers. Medium All 5 languages

Design & Data Structures

Build a class with the right internal structures.

  1. LRU Cache A fixed-capacity cache that evicts the least recently used key, with O(1) get and put. Medium Most asked All 5 languages
  2. Token Bucket Rate Limiter Allow bursts up to a capacity while refilling at a steady rate. Medium All 5 languages
  3. Key-Value Store with TTL An in-memory cache whose entries expire after a time-to-live. Medium All 5 languages
  4. URL Shortener Codes (Base62) Encode numeric IDs into short Base62 codes and decode them back. Easy All 5 languages
  5. Build an EventEmitter Implement on, off, once and emit like Node's EventEmitter. Medium Node.js
  6. Row Lock Manager with Deadlock Detection Build the core of a database lock manager: grant, queue, release in FIFO order, and abort on deadlock. Hard All 5 languages
  7. Versioned Store with Optimistic Locking Stop silent overwrites between editors: every update must name the version it was based on. Easy All 5 languages
  8. Flash-Sale Reservations Without Overselling Hold stock for 10 minutes, enforce a per-customer limit, survive client retries and never oversell. Medium All 5 languages
  9. 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. Medium All 5 languages
  10. Read-Your-Writes Replica Router Send reads to a replica only when it already has the user's latest write — otherwise use the primary. Easy All 5 languages
  11. Sharded Counter for a Hot Row Spread increments of a viral post's like counter over several slots and measure the lock waits. Medium All 5 languages
  12. Single-Flight Cache Loader When a hot key expires, let one request load it while everyone else waits — instead of a thundering herd. Medium All 5 languages
  13. 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. Medium All 5 languages
  14. Write-Behind View Counter with Safe Flushes Buffer view counts and flush them in batches that survive crashes and are never applied twice. Medium All 5 languages

Data Processing

Parse, transform, aggregate and paginate records.

  1. Top Endpoints from Access Logs Parse web-server log lines and return the most requested paths. Medium All 5 languages
  2. Group Events into Sessions Split a user's event timestamps into sessions separated by inactivity gaps. Easy All 5 languages
  3. Flatten Nested JSON Turn nested objects and arrays into a flat map with dotted keys. Medium All 5 languages
  4. Revenue Report from CSV Parse a CSV export, skip bad rows and total paid revenue per region. Easy All 5 languages

Async & Concurrency

Promises, timers, retries, concurrency limits.

  1. Retry with Exponential Backoff Retry a failing operation with exponential delays, but never retry non-retryable errors. Medium Most asked All 5 languages
  2. Implement debounce() Delay a function until calls stop for `wait` ms; support cancel() and keep `this`. Medium Most asked Node.js
  3. Run Async Tasks with a Concurrency Limit Map over items with at most `limit` promises in flight, keeping result order. Medium Most asked Node.js
  4. Thread-Safe Counting with ExecutorService Fix a race condition with atomics and split work across a thread pool. Medium Java

Language Idioms

Collections, generators, decorators, types and OOP.

  1. Type-safe groupBy<T, K>() Write a generic groupBy that infers key and item types. Easy TypeScript
  2. Result Type Instead of Exceptions Model success/failure with a discriminated union and narrow on it. Medium TypeScript
  3. Typed pick() and omit() Implement runtime pick/omit whose return types match Pick<T,K> and Omit<T,K>. Easy TypeScript
  4. Leaderboard Sorting with usort and <=> Sort associative arrays by several keys using the spaceship operator. Easy PHP
  5. Slugify a Title (Strings & Regex) Turn a title into a URL slug with a maximum length that doesn't cut words. Easy PHP
  6. Order Status Enum with Transitions Use a PHP 8.1 backed enum with methods to enforce valid state changes. Medium PHP
  7. Lazy chunked() Generator Yield fixed-size lists from any iterable — lazily, so it works on infinite streams. Easy Python
  8. Decorator with Arguments: @retry Write a parameterised decorator that retries selected exceptions and preserves metadata. Medium Python
  9. Immutable Money Value Object (dataclasses) Use a frozen, ordered dataclass with __add__ and __str__ for money. Medium Python
  10. Reporting with Streams and Collectors Group, count, average and sort records using the Stream API. Medium Most asked Java
  11. equals() and hashCode() Done Right Implement value equality so HashSet and HashMap behave correctly. Easy Most asked Java

Gotchas

Scoping, equality, mutability and evaluation order.

  1. var in a Loop with setTimeout Why every callback sees the same `i`. Easy Most asked Node.js
  2. Microtasks vs Macrotasks Order of sync code, promise callbacks, await continuations and timers. Medium Most asked Node.js
  3. Type Coercion Surprises `+` vs `-` with strings, loose equality and typeof quirks. Medium Node.js
  4. Numeric Enums at Runtime Auto-incremented values and reverse mappings of TypeScript enums. Medium TypeScript
  5. Type Assertions Don't Convert `as number` changes the type, not the value. Easy TypeScript
  6. readonly and as const at Runtime Compile-time immutability doesn't freeze objects. Medium TypeScript
  7. Mutable Default Arguments Default values are evaluated once, at definition time. Easy Most asked Python
  8. Late-Binding Closures Lambdas look up variables when called, not when created. Medium Python
  9. List Multiplication Shares Rows `[[0] * 3] * 3` creates three references to one row. Easy Python
  10. PHP 8 String-to-Number Comparison How `==` changed in PHP 8 and why numeric strings still compare as numbers. Medium PHP
  11. foreach by Reference Leftover A dangling reference after `foreach (... as &$item)` corrupts the next loop. Medium PHP
  12. Array Key Casting Which keys PHP silently converts to integers. Hard PHP
  13. Integer Cache and == Why 127 == 127 but 128 != 128 for boxed Integers. Easy Most asked Java
  14. String Immutability and Interning Methods return new strings; compile-time constants are interned. Medium Java
  15. Integer Division and String Concatenation Left-to-right evaluation of + with numbers, chars and strings. Easy Java
  16. Two Checkouts, One Item Left Predict what a read-modify-write checkout does when two requests interleave. Easy Python
  17. The Stale Cache Set A slow cache-aside reader and a writer race. What ends up in the cache? Medium Node.js
  18. Read Committed vs Repeatable Read A report reads a balance twice while a deposit commits in between. What does each isolation level see? Medium Python

Code Clinic: Find the Bug

Off-by-ones, mutable defaults, loose equality, async races: the bugs interviewers hand you to fix.

  1. Fix the Binary Search A binary search that misses some targets: find the off-by-one and fix it. Easy Most asked All 5 languages
  2. Fix the Two Sum Hash Map A one-pass Two Sum that sometimes pairs a number with itself. Easy Most asked All 5 languages
  3. Fix the Longest Substring Without Repeats A sliding window whose left edge sometimes moves backwards. Medium Most asked All 5 languages
  4. Fix Merge Intervals An interval merge that shrinks intervals when one contains another. Medium Most asked All 5 languages
  5. Fix the Mutable Default Argument A Python helper whose results leak from one call into the next. Easy Most asked Python
  6. Fix the Substring Check A contains-check that says no when the match is at the very start of the string. Easy Most asked All 5 languages
  7. Fix the Median (JavaScript Sort) A median function that is right for single digits and wrong for 10. Easy Most asked Node.js, TypeScript
  8. Fix the Number Parser (map + parseInt) A one-line parser that turns most of its input into NaN. Easy Node.js, TypeScript
  9. Fix the Async Total (forEach) An async loop that returns before any of its work has finished. Medium Most asked Node.js, TypeScript
  10. Fix the Bill Splitter Splitting money with rounding loses or invents cents. Easy All 5 languages
  11. Fix the Pagination Helper Page 1 shows the second page of results. Easy Most asked All 5 languages
  12. Fix the TTL Cache Expiry A TTL cache that serves entries one tick after they expired. Medium All 5 languages
  13. Fix Removing Items While Iterating Deleting from a list inside the loop that walks it skips elements (or throws, in Java). Easy Most asked Node.js, TypeScript, Python, Java
  14. Fix the Word Counter A word counter that counts the spaces between words, and counts one word in an empty string. Easy All 5 languages
  15. Fix the Bracket Validator A bracket validator that accepts brackets that were opened and never closed. Easy Most asked All 5 languages

Code Clinic: Make It Fast

Correct but slow code. Spot the hidden O(n^2) and fix it without changing the answers.

  1. Speed Up Contains Duplicate A correct but quadratic duplicate check that times out on large input: make it linear. Easy Most asked All 5 languages
  2. Speed Up Two Sum The brute-force Two Sum checks every pair. Make it one pass. Easy Most asked All 5 languages
  3. Speed Up Recursive Fibonacci Textbook recursive Fibonacci recomputes the same values billions of times. Remove the repeated work. Easy All 5 languages
  4. Speed Up the Most Frequent Word Counting each word by rescanning the whole list is quadratic. Count once. Easy All 5 languages
  5. 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). Easy Most asked All 5 languages
  6. Speed Up Range Sum Queries Re-adding every range for every query is O(n x q). Precompute prefix sums once. Medium All 5 languages
  7. 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. Medium Most asked All 5 languages
  8. Speed Up Subarray Sum Equals K Trying every subarray is O(n^2). Count matching prefix sums in one pass. Medium Most asked All 5 languages
  9. Speed Up Maximum Subarray Summing every subarray is quadratic. Kadane's algorithm does it in one pass. Medium Most asked All 5 languages
  10. Speed Up the Sliding Window Sum Re-summing every window costs O(n x k). Slide the window: add one value, remove one. Easy All 5 languages
  11. Speed Up Pairs With Difference K Comparing every pair to find differences of k is quadratic. Look up x + k in a set. Medium All 5 languages

Code Clinic: Code Review

Review real-looking pull requests: N+1 queries, injection, missing authorization, race conditions.

  1. Review a Laravel Orders Controller A short Laravel controller with an N+1 query, mass assignment, a missing authorization check and an unbounded query. Medium Most asked PHP
  2. Review an Express User Search Endpoint An Express route that builds SQL from the query string, returns password hashes and leaks errors. Easy Most asked Node.js
  3. Review a Payment Webhook Handler A FastAPI webhook that trusts unsigned requests and credits accounts twice when the provider retries. Medium Most asked Python
  4. Review a Sign-Up Function A registration function with a check-then-insert race, weak password hashing and an account-enumeration leak. Medium Python
  5. 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. Medium Python
  6. Review a React Search Component A search-as-you-type component with a request race, a leaking interval and an unstable list key. Medium Most asked TypeScript
  7. 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. Medium Node.js
  8. Review a jQuery Shopping Cart Script Legacy jQuery that stacks event handlers on every refresh, builds HTML from server data and uses synchronous AJAX. Easy Node.js
  9. Review a Python Service Client An HTTP client that logs secrets, has no timeouts, swallows every exception and retries in a tight loop. Medium Python
  10. Review a PHP Money Transfer A balance transfer with no transaction, a lost-update race, float money and no ownership check. Medium Most asked PHP
  11. Review a Java Order Service A Spring-style singleton service with shared mutable state, a broken lazy init, leaked JDBC resources and swallowed exceptions. Hard Java
  12. 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. Medium Node.js
  13. 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. Medium PHP
  14. Review a TypeScript API Client A typed fetch wrapper that retries payments, trusts unvalidated JSON and stores tokens in localStorage. Medium TypeScript
  15. 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. Hard Python