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.

easy
arrays
hashmap

Merge Intervals solution

Sort and merge every overlapping or touching interval into a disjoint list.

medium
arrays
sorting

Reverse a String solution

Return a string with every character in reverse order without changing characters.

easy
strings

Longest Common Prefix solution

Find the longest leading substring shared by every string in a list.

easy
strings

Palindrome String solution

Determine whether a phrase reads the same after ignoring case and non-alphanumeric characters.

easy
strings
two-pointers

Palindromic Substrings solution

Count every contiguous substring that reads the same forward and backward.

medium
strings
dynamic-programming

Longest Palindromic Substring solution

Return the longest contiguous substring that is a palindrome.

medium
strings
dynamic-programming

Palindrome Linked List solution

Check whether the values represented by a singly linked list form a palindrome.

easy
linked-list
two-pointers

Roman to Integer solution

Convert a valid canonical Roman numeral into its integer value.

easy
strings
math

Letter Combinations of a Phone Number solution

Generate every letter combination represented by digits on a telephone keypad.

medium
strings
backtracking

Valid Parentheses solution

Validate that every bracket closes in the correct order and with the matching type.

easy
strings
stack

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.

easy
strings
two-pointers

Length of Last Word solution

Measure the final whitespace-delimited word in a string.

easy
strings

Spiral Matrix solution

Generate an n-by-n matrix filled clockwise in spiral order.

medium
arrays
matrix

FizzBuzz solution

Produce the classic FizzBuzz sequence using divisibility rules.

easy
strings
math

Contains Duplicate solution

Determine whether any integer appears more than once in an array.

easy
arrays
hashmap

Maximum Subarray solution

Return the largest sum obtainable from a non-empty contiguous subarray.

medium
arrays
dynamic-programming

Fibonacci Number solution

Compute the zero-indexed Fibonacci number with an iterative recurrence.

easy
math
dynamic-programming

Factorial solution

Compute the product of all positive integers up to a non-negative input.

easy
math
recursion

Move Zeroes solution

Move every zero to the end while preserving non-zero element order.

easy
arrays
two-pointers

Single Number solution

Find the only value that is not paired using constant extra space.

easy
arrays
bit-manipulation

Best Time to Buy and Sell Stock solution

Find the best profit from one buy followed by one later sale.

easy
arrays
dynamic-programming

Valid Anagram solution

Check whether two lowercase strings contain identical character frequencies.

easy
strings
hashmap

Binary Search solution

Locate a target in a sorted unique array using logarithmic search.

easy
arrays
binary-search

Count Vowels solution

Count ASCII vowels in a string without changing other characters.

easy
strings

Climbing Stairs solution

Count ordered one-step and two-step paths to the top of a staircase.

easy
math
dynamic-programming

Product of Array Except Self solution

Build prefix and suffix products without division.

medium
arrays
prefix-sum

Trapping Rain Water solution

Compute water trapped between elevation bars after rainfall.

hard
arrays
two-pointers

Edit Distance solution

Measure the minimum insertions, deletions, and replacements between two strings.

hard
strings
dynamic-programming

Median of Two Sorted Arrays solution

Find the combined median without fully merging two sorted arrays.

hard
arrays
binary-search

Longest Valid Parentheses solution

Measure the longest contiguous substring of balanced parentheses.

hard
strings
stack

Palindrome Number solution

Determine whether a base-10 integer reads identically in reverse.

easy
math

Plus One solution

Add one to a number represented as an array of digits.

easy
arrays
math

Majority Element solution

Find the element that appears more than half the time in an array.

easy
arrays
hashmap

Is Subsequence solution

Check whether one string is a subsequence of another.

easy
strings
two-pointers

First Unique Character in a String solution

Find the index of the first non-repeating character in a string.

easy
strings
hashmap

Search Insert Position solution

Return the index where a target should be inserted into a sorted array.

easy
arrays
binary-search

House Robber solution

Maximize the loot from non-adjacent houses along a street.

medium
arrays
dynamic-programming

Jump Game solution

Decide whether you can reach the last index of an array of jump lengths.

medium
arrays
greedy

Coin Change solution

Find the fewest coins needed to make up a given amount.

medium
arrays
dynamic-programming

Longest Substring Without Repeating Characters solution

Find the length of the longest substring without repeating characters.

medium
strings
sliding-window

Container With Most Water solution

Find two lines that together with the x-axis hold the most water.

medium
arrays
two-pointers

Number of Islands solution

Count the number of islands in a grid of land and water cells.

medium
matrix
graph

Word Break solution

Determine whether a string can be segmented into words from a dictionary.

hard
strings
dynamic-programming

Longest Increasing Subsequence solution

Find the length of the longest strictly increasing subsequence.

hard
arrays
dynamic-programming

Largest Rectangle in Histogram solution

Find the area of the largest rectangle that fits under a histogram.

hard
arrays
stack

Sliding Window Maximum solution

Return the maximum of every contiguous window of size k.

hard
arrays
sliding-window

Jump Game II solution

Find the minimum number of jumps needed to reach the last index.

hard
arrays
greedy

Reverse Linked List solution

Reverse a singly linked list in place using real ListNode structures.

easy
linked-list
pointers

Maximum Depth of Binary Tree solution

Find the maximum depth of a binary tree using real TreeNode structures.

easy
binary-tree
recursion

Course Schedule solution

Determine whether all courses can be completed given prerequisite pairs.

medium
graph
topological-sort

Rotting Oranges solution

Find how many minutes are needed for rot to spread to every fresh orange.

medium
matrix
graph

Redundant Connection solution

Find the edge that creates a cycle in an otherwise tree-shaped graph.

medium
graph
union-find

Kth Largest Element in an Array solution

Return the kth largest value without requiring a fully sorted array.

medium
arrays
heap

Top K Frequent Elements solution

Return the k values that occur most often in an integer array.

medium
arrays
hashmap

Subsets solution

Generate every subset in the power set of a distinct integer array.

medium
arrays
backtracking

Invert Binary Tree solution

Swap every binary-tree node's left and right children.

easy
binary-tree
depth-first-search

Same Tree solution

Determine whether two binary trees have identical structure and values.

easy
binary-tree
depth-first-search

Validate Binary Search Tree solution

Check whether a binary tree satisfies strict BST ordering.

medium
binary-tree
binary-search-tree

Binary Tree Level Order Traversal solution

Return binary-tree values grouped by breadth-first level.

medium
binary-tree
breadth-first-search

Lowest Common Ancestor of a BST solution

Find the lowest shared ancestor of two values in a binary search tree.

medium
binary-tree
binary-search-tree

Merge Two Sorted Lists solution

Merge two sorted linked lists by rewiring their nodes.

easy
linked-list
two-pointers

Linked List Cycle solution

Detect a cycle from a linked list represented by next-node indices.

easy
linked-list
two-pointers

Reorder List solution

Reorder a linked list by alternating nodes from its front and back.

medium
linked-list
two-pointers

Clone Graph solution

Deep-copy a connected graph from its adjacency-list representation.

medium
graph
depth-first-search

Pacific Atlantic Water Flow solution

Find grid cells that can flow to both oceans under height constraints.

medium
graph
matrix

Network Delay Time solution

Compute how long a weighted directed network takes to receive a signal.

medium
graph
shortest-path

Merge K Sorted Lists solution

Merge k sorted sequences using a heap of current candidates.

hard
linked-list
heap

Find Median from Data Stream solution

Return the median after incrementally inserting every stream value.

hard
heap
priority-queue

Permutations solution

Generate every ordering of a distinct integer array.

medium
arrays
backtracking

Combination Sum solution

Find target-sum combinations when candidate values may be reused.

medium
arrays
backtracking

Word Search solution

Find a word by backtracking through adjacent grid cells.

medium
matrix
backtracking

Implement Trie solution

Execute insert, exact-search, and prefix-search operations on a trie.

medium
trie
string

Design Add and Search Words solution

Build a trie that supports exact letters and wildcard searches.

medium
trie
backtracking

LRU Cache solution

Simulate a bounded least-recently-used key-value cache.

medium
hashmap
linked-list

Unique Paths solution

Count distinct top-left to bottom-right grid paths moving only right or down.

medium
math
dynamic-programming

Pascal's Triangle solution

Build the first numRows rows of Pascal's triangle by summing adjacent values.

easy
math
combinatorics

Count Primes solution

Count prime numbers strictly below n with the Sieve of Eratosthenes.

medium
math

Sqrt(x) solution

Return the floored integer square root without a built-in sqrt function.

easy
math
binary-search

Happy Number solution

Decide whether summing squared digits eventually reaches one or cycles.

easy
math
hashmap

Excel Sheet Column Number solution

Convert a spreadsheet column title like AB into its 1-based number.

easy
math
strings

Insert Interval solution

Insert one interval into sorted disjoint intervals and merge any overlaps.

medium
arrays
intervals

Non-overlapping Intervals solution

Remove the fewest intervals so the remaining schedule has no overlaps.

medium
arrays
intervals

Sort Colors solution

Sort an array of 0s, 1s, and 2s in one in-place pass.

medium
arrays
sorting

Number of Provinces solution

Count how many disconnected city groups exist in an undirected connectivity matrix.

medium
graph
union-find

Minimum Size Subarray Sum solution

Find the shortest contiguous subarray whose sum reaches a target.

medium
arrays
sliding-window

3Sum solution

Find every unique triplet of numbers in an array that sums to zero.

medium
arrays
two-pointers

Rotate Image solution

Rotate an n x n matrix 90 degrees clockwise and return the rotated matrix.

medium
matrix
arrays

Search in Rotated Sorted Array solution

Find a target value's index in an ascending array that has been rotated at an unknown pivot.

medium
arrays
binary-search

Longest Consecutive Sequence solution

Find the length of the longest run of consecutive integers in an unsorted array.

medium
arrays
hashmap

Sum of Two Integers solution

Add two integers together without using the + or - operators.

easy
bit-manipulation
math

FAQ