Coding interview solutions
Step-by-step solutions to 126 common coding interview problems, each with the optimal approach and its time & space complexity, explained in Python and JavaScript. Prefer to try first? Practice these problems online.
Two Sum solution
Find the indices of two distinct values whose sum matches a target.
Merge Intervals solution
Sort and merge every overlapping or touching interval into a disjoint list.
Reverse a String solution
Return a string with every character in reverse order without changing characters.
Longest Common Prefix solution
Find the longest leading substring shared by every string in a list.
Palindrome String solution
Determine whether a phrase reads the same after ignoring case and non-alphanumeric characters.
Palindromic Substrings solution
Count every contiguous substring that reads the same forward and backward.
Longest Palindromic Substring solution
Return the longest contiguous substring that is a palindrome.
Palindrome Linked List solution
Check whether the values represented by a singly linked list form a palindrome.
Roman to Integer solution
Convert a valid canonical Roman numeral into its integer value.
Letter Combinations of a Phone Number solution
Generate every letter combination represented by digits on a telephone keypad.
Valid Parentheses solution
Validate that every bracket closes in the correct order and with the matching type.
Find the Index of the First Occurrence in a String solution
Return the starting index of the first exact occurrence of one string inside another.
Length of Last Word solution
Measure the final whitespace-delimited word in a string.
Spiral Matrix solution
Generate an n-by-n matrix filled clockwise in spiral order.
FizzBuzz solution
Produce the classic FizzBuzz sequence using divisibility rules.
Contains Duplicate solution
Determine whether any integer appears more than once in an array.
Maximum Subarray solution
Return the largest sum obtainable from a non-empty contiguous subarray.
Fibonacci Number solution
Compute the zero-indexed Fibonacci number with an iterative recurrence.
Factorial solution
Compute the product of all positive integers up to a non-negative input.
Move Zeroes solution
Move every zero to the end while preserving non-zero element order.
Single Number solution
Find the only value that is not paired using constant extra space.
Best Time to Buy and Sell Stock solution
Find the best profit from one buy followed by one later sale.
Valid Anagram solution
Check whether two lowercase strings contain identical character frequencies.
Binary Search solution
Locate a target in a sorted unique array using logarithmic search.
Count Vowels solution
Count ASCII vowels in a string without changing other characters.
Climbing Stairs solution
Count ordered one-step and two-step paths to the top of a staircase.
Product of Array Except Self solution
Build prefix and suffix products without division.
Trapping Rain Water solution
Compute water trapped between elevation bars after rainfall.
Edit Distance solution
Measure the minimum insertions, deletions, and replacements between two strings.
Median of Two Sorted Arrays solution
Find the combined median without fully merging two sorted arrays.
Longest Valid Parentheses solution
Measure the longest contiguous substring of balanced parentheses.
Palindrome Number solution
Determine whether a base-10 integer reads identically in reverse.
Plus One solution
Add one to a number represented as an array of digits.
Majority Element solution
Find the element that appears more than half the time in an array.
Is Subsequence solution
Check whether one string is a subsequence of another.
First Unique Character in a String solution
Find the index of the first non-repeating character in a string.
Search Insert Position solution
Return the index where a target should be inserted into a sorted array.
House Robber solution
Maximize the loot from non-adjacent houses along a street.
Jump Game solution
Decide whether you can reach the last index of an array of jump lengths.
Coin Change solution
Find the fewest coins needed to make up a given amount.
Longest Substring Without Repeating Characters solution
Find the length of the longest substring without repeating characters.
Container With Most Water solution
Find two lines that together with the x-axis hold the most water.
Number of Islands solution
Count the number of islands in a grid of land and water cells.
Word Break solution
Determine whether a string can be segmented into words from a dictionary.
Longest Increasing Subsequence solution
Find the length of the longest strictly increasing subsequence.
Largest Rectangle in Histogram solution
Find the area of the largest rectangle that fits under a histogram.
Sliding Window Maximum solution
Return the maximum of every contiguous window of size k.
Jump Game II solution
Find the minimum number of jumps needed to reach the last index.
Reverse Linked List solution
Reverse a singly linked list in place using real ListNode structures.
Maximum Depth of Binary Tree solution
Find the maximum depth of a binary tree using real TreeNode structures.
Course Schedule solution
Determine whether all courses can be completed given prerequisite pairs.
Rotting Oranges solution
Find how many minutes are needed for rot to spread to every fresh orange.
Redundant Connection solution
Find the edge that creates a cycle in an otherwise tree-shaped graph.
Kth Largest Element in an Array solution
Return the kth largest value without requiring a fully sorted array.
Top K Frequent Elements solution
Return the k values that occur most often in an integer array.
Subsets solution
Generate every subset in the power set of a distinct integer array.
Invert Binary Tree solution
Swap every binary-tree node's left and right children.
Same Tree solution
Determine whether two binary trees have identical structure and values.
Validate Binary Search Tree solution
Check whether a binary tree satisfies strict BST ordering.
Binary Tree Level Order Traversal solution
Return binary-tree values grouped by breadth-first level.
Lowest Common Ancestor of a BST solution
Find the lowest shared ancestor of two values in a binary search tree.
Merge Two Sorted Lists solution
Merge two sorted linked lists by rewiring their nodes.
Linked List Cycle solution
Detect a cycle from a linked list represented by next-node indices.
Reorder List solution
Reorder a linked list by alternating nodes from its front and back.
Clone Graph solution
Deep-copy a connected graph from its adjacency-list representation.
Pacific Atlantic Water Flow solution
Find grid cells that can flow to both oceans under height constraints.
Network Delay Time solution
Compute how long a weighted directed network takes to receive a signal.
Merge K Sorted Lists solution
Merge k sorted sequences using a heap of current candidates.
Find Median from Data Stream solution
Return the median after incrementally inserting every stream value.
Permutations solution
Generate every ordering of a distinct integer array.
Combination Sum solution
Find target-sum combinations when candidate values may be reused.
Word Search solution
Find a word by backtracking through adjacent grid cells.
Implement Trie solution
Execute insert, exact-search, and prefix-search operations on a trie.
Design Add and Search Words solution
Build a trie that supports exact letters and wildcard searches.
LRU Cache solution
Simulate a bounded least-recently-used key-value cache.
Unique Paths solution
Count distinct top-left to bottom-right grid paths moving only right or down.
Pascal's Triangle solution
Build the first numRows rows of Pascal's triangle by summing adjacent values.
Count Primes solution
Count prime numbers strictly below n with the Sieve of Eratosthenes.
Sqrt(x) solution
Return the floored integer square root without a built-in sqrt function.
Happy Number solution
Decide whether summing squared digits eventually reaches one or cycles.
Excel Sheet Column Number solution
Convert a spreadsheet column title like AB into its 1-based number.
Insert Interval solution
Insert one interval into sorted disjoint intervals and merge any overlaps.
Non-overlapping Intervals solution
Remove the fewest intervals so the remaining schedule has no overlaps.
Sort Colors solution
Sort an array of 0s, 1s, and 2s in one in-place pass.
Number of Provinces solution
Count how many disconnected city groups exist in an undirected connectivity matrix.
Minimum Size Subarray Sum solution
Find the shortest contiguous subarray whose sum reaches a target.
3Sum solution
Find every unique triplet of numbers in an array that sums to zero.
Rotate Image solution
Rotate an n x n matrix 90 degrees clockwise and return the rotated matrix.
Search in Rotated Sorted Array solution
Find a target value's index in an ascending array that has been rotated at an unknown pivot.
Longest Consecutive Sequence solution
Find the length of the longest run of consecutive integers in an unsorted array.
Sum of Two Integers solution
Add two integers together without using the + or - operators.
Symmetric Tree solution
Check whether a binary tree is a mirror image of itself around its center.
Diameter of Binary Tree solution
Find the length in edges of the longest path between any two nodes in a binary tree.
Kth Smallest Element in a BST solution
Return the k-th smallest value stored in a binary search tree.
Add Two Numbers solution
Add two non-negative integers represented as reversed-digit linked lists.
Remove Nth Node From End of List solution
Delete the n-th node from the end of a singly linked list in one pass.
Path Sum solution
Determine whether a binary tree has a root-to-leaf path whose values sum to a target.
Convert Sorted Array to Binary Search Tree solution
Build a height-balanced binary search tree from an ascending array of unique integers.
Reverse Linked List II solution
Reverse only the nodes between two 1-indexed positions of a singly linked list, in one pass.
Swap Nodes in Pairs solution
Swap every adjacent pair of nodes in a singly linked list without changing the node values.
Binary Tree Right Side View solution
Return the values visible when looking at a binary tree from the right side, ordered top to bottom.
Merge Two Binary Trees solution
Overlay two binary trees, summing values where both trees have a node.
Path Sum II solution
Find every root-to-leaf path in a binary tree whose values sum to a target.
Construct Binary Tree from Preorder & Inorder solution
Rebuild a unique binary tree from its preorder and inorder traversal arrays.
Linked List Cycle II solution
Find the index where a cycle begins in a linked list represented by next-node indices, or -1 if there is none.
Odd Even Linked List solution
Regroup a singly linked list so all odd-positioned nodes come before all even-positioned nodes, preserving relative order within each group.
Task Scheduler solution
Find the minimum timeline length needed to schedule tasks with a cooldown between identical letters.
Connected Components in an Undirected Graph solution
Count how many disconnected components remain in an undirected graph with labeled vertices.
Palindrome Partitioning solution
Return every way to cut a string into palindromic substrings, ordered by DFS prefix exploration.
Word Search II solution
Find all dictionary words that can be traced through adjacent board cells without reusing a cell.
Word Ladder solution
Find the length of the shortest one-letter transformation sequence from a start word to an end word.
Daily Temperatures solution
Return how many days each temperature must wait until a warmer reading appears.
Decode Ways solution
Count how many valid A1Z26 decodings a digit string can represent.
Gas Station solution
Find the unique starting station that lets you complete a circular route, or report failure.
Alien Dictionary solution
Recover a valid alien letter order from a sorted word list, returning the lexicographically smallest valid order.
Binary Tree Maximum Path Sum solution
Find the largest sum obtainable from any non-empty path inside a binary tree.
Meeting Rooms II solution
Return the minimum number of meeting rooms needed so every interval can be scheduled without overlap.
Minimum Window Substring solution
Find the shortest substring of s that still contains every character required by t, including duplicates.
Longest Increasing Path in a Matrix solution
Find the maximum path length you can build by moving to orthogonally adjacent cells with strictly larger values.
Range Sum Query - Mutable solution
Process point updates and inclusive range-sum queries efficiently over the same integer array.
Cheapest Flights Within K Stops solution
Find the least expensive route from src to dst when you may use at most k intermediate stops.
Group Anagrams solution
Group strings that are anagrams of one another into deterministic buckets.
Min Stack solution
Process push, pop, top, and getMin operations on a stack in constant time.
Accounts Merge solution
Merge account rows that share an email address into deterministic combined profiles.
K Closest Points to Origin solution
Return the k points with the smallest distance from the origin in deterministic order.
Counting Bits solution
Return the number of set bits for every integer from 0 through n.