Coding interview solutions
Step-by-step solutions to 91 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.