Coding interview problems

Practice 146 classic interview problems with runnable test cases, then read the step-by-step solutions with time & space complexity.

Terminal view

Your progress

0 / 146 solved

0%

Not sure where to start?

Choose a learning path and practice one pattern at a time.

Browse paths

Find your next problem

146 of 146 problems

Browse by pattern

001

Two Sum

Find the indices of two distinct values whose sum matches a target.

arrayshashmap
easy
002

Merge Intervals

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

arrayssorting
medium
003

Reverse a String

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

strings
easy
004

Longest Common Prefix

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

strings
easy
005

Palindrome String

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

stringstwo pointers
easy
006

Palindromic Substrings

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

stringsdynamic programming
medium
007

Longest Palindromic Substring

Return the longest contiguous substring that is a palindrome.

stringsdynamic programming
medium
008

Palindrome Linked List

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

linked listtwo pointers
easy
009

Roman to Integer

Convert a valid canonical Roman numeral into its integer value.

stringsmath
easy
010

Letter Combinations of a Phone Number

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

stringsbacktracking
medium
011

Valid Parentheses

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

stringsstack
easy
012

Find the Index of the First Occurrence in a String

Return the starting index of the first exact occurrence of one string inside another.

stringstwo pointers
easy
013

Length of Last Word

Measure the final whitespace-delimited word in a string.

strings
easy
014

Spiral Matrix

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

arraysmatrix
medium
015

FizzBuzz

Produce the classic FizzBuzz sequence using divisibility rules.

stringsmath
easy
016

Contains Duplicate

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

arrayshashmap
easy
017

Maximum Subarray

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

arraysdynamic programming
medium
018

Fibonacci Number

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

mathdynamic programming
easy
019

Factorial

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

mathrecursion
easy
020

Move Zeroes

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

arraystwo pointers
easy
021

Single Number

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

arraysbit manipulation
easy
022

Best Time to Buy and Sell Stock

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

arraysdynamic programming
easy
023

Valid Anagram

Check whether two lowercase strings contain identical character frequencies.

stringshashmap
easy
024

Binary Search

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

arraysbinary search
easy
025

Count Vowels

Count ASCII vowels in a string without changing other characters.

strings
easy
026

Climbing Stairs

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

mathdynamic programming
easy
027

Product of Array Except Self

Build prefix and suffix products without division.

arraysprefix sum
medium
028

Trapping Rain Water

Compute water trapped between elevation bars after rainfall.

arraystwo pointers
hard
029

Edit Distance

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

stringsdynamic programming
hard
030

Median of Two Sorted Arrays

Find the combined median without fully merging two sorted arrays.

arraysbinary search
hard
031

Longest Valid Parentheses

Measure the longest contiguous substring of balanced parentheses.

stringsstack
hard
032

Palindrome Number

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

math
easy
033

Plus One

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

arraysmath
easy
034

Majority Element

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

arrayshashmap
easy
035

Is Subsequence

Check whether one string is a subsequence of another.

stringstwo pointers
easy
036

First Unique Character in a String

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

stringshashmap
easy
037

Search Insert Position

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

arraysbinary search
easy
038

House Robber

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

arraysdynamic programming
medium
039

Jump Game

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

arraysgreedy
medium
040

Coin Change

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

arraysdynamic programming
medium
041

Longest Substring Without Repeating Characters

Find the length of the longest substring without repeating characters.

stringssliding window
medium
042

Container With Most Water

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

arraystwo pointers
medium
043

Number of Islands

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

matrixgraph
medium
044

Word Break

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

stringsdynamic programming
hard
045

Longest Increasing Subsequence

Find the length of the longest strictly increasing subsequence.

arraysdynamic programming
hard
046

Largest Rectangle in Histogram

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

arraysstack
hard
047

Sliding Window Maximum

Return the maximum of every contiguous window of size k.

arrayssliding window
hard
048

Jump Game II

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

arraysgreedy
hard
049

Reverse Linked List

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

linked listpointers
easy
050

Maximum Depth of Binary Tree

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

binary treerecursion
easy
051

Course Schedule

Determine whether all courses can be completed given prerequisite pairs.

graphtopological sort
medium
052

Rotting Oranges

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

matrixgraph
medium
053

Redundant Connection

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

graphunion find
medium
054

Kth Largest Element in an Array

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

arraysheap
medium
055

Top K Frequent Elements

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

arrayshashmap
medium
056

Subsets

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

arraysbacktracking
medium
057

Invert Binary Tree

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

binary treedepth first search
easy
058

Same Tree

Determine whether two binary trees have identical structure and values.

binary treedepth first search
easy
059

Validate Binary Search Tree

Check whether a binary tree satisfies strict BST ordering.

binary treebinary search tree
medium
060

Binary Tree Level Order Traversal

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

binary treebreadth first search
medium
061

Lowest Common Ancestor of a BST

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

binary treebinary search tree
medium
062

Merge Two Sorted Lists

Merge two sorted linked lists by rewiring their nodes.

linked listtwo pointers
easy
063

Linked List Cycle

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

linked listtwo pointers
easy
064

Reorder List

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

linked listtwo pointers
medium
065

Clone Graph

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

graphdepth first search
medium
066

Pacific Atlantic Water Flow

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

graphmatrix
medium
067

Network Delay Time

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

graphshortest path
medium
068

Merge K Sorted Lists

Merge several sorted linked lists into one sorted list.

linked listheap
hard
069

Find Median from Data Stream

Return the median after incrementally inserting every stream value.

heappriority queue
hard
070

Permutations

Generate every ordering of a distinct integer array.

arraysbacktracking
medium
071

Combination Sum

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

arraysbacktracking
medium
072

Word Search

Find a word by backtracking through adjacent grid cells.

matrixbacktracking
medium
073

Implement Trie

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

triestring
medium
074

Design Add and Search Words

Add words to a dictionary and search with exact letters or single-letter wildcards.

triebacktracking
medium
075

LRU Cache

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

hashmaplinked list
medium
076

Unique Paths

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

mathdynamic programming
medium
077

Pascal's Triangle

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

mathcombinatorics
easy
078

Count Primes

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

math
medium
079

Sqrt(x)

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

mathbinary search
easy
080

Happy Number

Decide whether summing squared digits eventually reaches one or cycles.

mathhashmap
easy
081

Excel Sheet Column Number

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

mathstrings
easy
082

Insert Interval

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

arraysintervals
medium
083

Non-overlapping Intervals

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

arraysintervals
medium
084

Sort Colors

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

arrayssorting
medium
085

Number of Provinces

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

graphunion find
medium
086

Minimum Size Subarray Sum

Find the shortest contiguous subarray whose sum reaches a target.

arrayssliding window
medium
087

3Sum

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

arraystwo pointers
medium
088

Rotate Image

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

matrixarrays
medium
089

Search in Rotated Sorted Array

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

arraysbinary search
medium
090

Longest Consecutive Sequence

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

arrayshashmap
medium
091

Sum of Two Integers

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

bit manipulationmath
easy
092

Symmetric Tree

Check whether a binary tree is a mirror image of itself around its center.

binary treedepth first search
easy
093

Diameter of Binary Tree

Find the length in edges of the longest path between any two nodes in a binary tree.

binary treedepth first search
easy
094

Kth Smallest Element in a BST

Return the k-th smallest value stored in a binary search tree.

binary treebinary search tree
medium
095

Add Two Numbers

Add two non-negative integers represented as reversed-digit linked lists.

linked listmath
medium
096

Remove Nth Node From End of List

Delete the n-th node from the end of a singly linked list in one pass.

linked listtwo pointers
medium
097

Path Sum

Determine whether a binary tree has a root-to-leaf path whose values sum to a target.

binary treedepth first search
medium
098

Convert Sorted Array to Binary Search Tree

Build a height-balanced binary search tree from an ascending array of unique integers.

binary treebinary search tree
easy
099

Reverse Linked List II

Reverse only the nodes between two 1-indexed positions of a singly linked list, in one pass.

linked listpointers
medium
100

Swap Nodes in Pairs

Swap every adjacent pair of nodes in a singly linked list without changing the node values.

linked listpointers
medium
101

Binary Tree Right Side View

Return the values visible when looking at a binary tree from the right side, ordered top to bottom.

binary treebreadth first search
medium
102

Merge Two Binary Trees

Overlay two binary trees, summing values where both trees have a node.

binary treedepth first search
easy
103

Path Sum II

Find every root-to-leaf path in a binary tree whose values sum to a target.

binary treedepth first search
medium
104

Construct Binary Tree from Preorder & Inorder

Rebuild a unique binary tree from its preorder and inorder traversal arrays.

binary treedivide and conquer
medium
105

Linked List Cycle II

Find the index where a cycle begins in a linked list represented by next-node indices, or -1 if there is none.

linked listtwo pointers
medium
106

Odd Even Linked List

Reorder a linked list so odd-positioned nodes come first, keeping each group's relative order.

linked listtwo pointers
medium
107

Task Scheduler

Find the minimum timeline length needed to schedule tasks with a cooldown between identical letters.

heappriority queue
medium
108

Connected Components in an Undirected Graph

Count how many disconnected components remain in an undirected graph with labeled vertices.

graphunion find
medium
109

Palindrome Partitioning

Return every way to cut a string into palindromic substrings, ordered by DFS prefix exploration.

stringsbacktracking
medium
110

Word Search II

Find all dictionary words that can be traced through adjacent board cells without reusing a cell.

triebacktracking
hard
111

Word Ladder

Find the length of the shortest one-letter transformation sequence from a start word to an end word.

graphbreadth first search
hard
112

Daily Temperatures

Return how many days each temperature must wait until a warmer reading appears.

arraysstack
medium
113

Decode Ways

Count how many valid A1Z26 decodings a digit string can represent.

stringsdynamic programming
medium
114

Gas Station

Find the unique starting station that lets you complete a circular route, or report failure.

arraysgreedy
medium
115

Alien Dictionary

Recover a valid alien letter order from a sorted word list, returning the lexicographically smallest valid order.

graphtopological sort
hard
116

Binary Tree Maximum Path Sum

Find the largest sum obtainable from any non-empty path inside a binary tree.

binary treedepth first search
hard
117

Meeting Rooms II

Return the minimum number of meeting rooms needed so every interval can be scheduled without overlap.

intervalssorting
medium
118

Minimum Window Substring

Find the shortest substring of s that still contains every character required by t, including duplicates.

stringssliding window
hard
119

Longest Increasing Path in a Matrix

Find the maximum path length you can build by moving to orthogonally adjacent cells with strictly larger values.

matrixgraph
hard
120

Range Sum Query - Mutable

Process point updates and inclusive range-sum queries efficiently over the same integer array.

designprefix sum
medium
121

Cheapest Flights Within K Stops

Find the least expensive route from src to dst when you may use at most k intermediate stops.

graphshortest path
medium
122

Group Anagrams

Group anagrams while preserving the original order of words and their groups.

arrayshashmap
medium
123

Min Stack

Process push, pop, top, and getMin operations on a stack in constant time.

stackdesign
medium
124

Accounts Merge

Merge account rows that share an email address into deterministic combined profiles.

graphunion find
medium
125

K Closest Points to Origin

Return the k points with the smallest distance from the origin in deterministic order.

arraysheap
medium
126

Counting Bits

Return the number of set bits for every integer from 0 through n.

bit manipulationdynamic programming
easy
127

Maximum Product Subarray

Find the largest product obtainable from any non-empty contiguous subarray.

arraysdynamic programming
medium
128

Course Schedule II

Return a valid topological ordering of courses, or an empty array if a cycle blocks completion.

graphtopological sort
medium
129

Kth Smallest Element in a Sorted Matrix

Return the kth value in an n-by-n matrix whose rows and columns are both sorted ascending.

matrixbinary search
medium
130

Missing Number

Find the only value missing from the distinct numbers drawn from the range 0 through n.

arraysmath
easy
131

Find All Anagrams in a String

Return every starting index where p appears as an anagram inside s.

stringssliding window
medium
132

Find Minimum in Rotated Sorted Array

Find the smallest value in an ascending array that has been rotated an unknown number of times.

arraysbinary search
medium
133

Search a 2D Matrix

Decide whether a target value exists in a matrix whose rows and row-boundaries are both sorted ascending.

arraysbinary search
medium
134

Single Number II

Find the one value that appears a single time when every other value appears exactly three times.

arraysbit manipulation
medium
135

Subarray Sum Equals K

Count how many contiguous subarrays add up to exactly the target value k.

arrayshashmap
medium
136

Isomorphic Strings

Determine whether two strings share a consistent one-to-one character mapping in both directions.

stringshashmap
easy
137

Next Permutation

Return the lexicographically next greater permutation, or wrap to ascending order.

arraystwo pointers
medium
138

First Missing Positive

Find the smallest positive integer that does not appear in an unsorted array.

arraysin place
hard
139

Set Matrix Zeroes

Zero out the entire row and column of every cell that contains a zero.

matrixarrays
medium
140

Spiral Matrix II

Generate an n-by-n matrix filled with 1 through n² in clockwise spiral order.

arraysmatrix
medium
141

Balanced Binary Tree

Check whether every binary-tree node stays within one level of balance.

binary treedepth first search
easy
142

Lowest Common Ancestor of a Binary Tree

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

binary treedepth first search
medium
143

Binary Tree Zigzag Level Order Traversal

Return binary-tree values level by level, alternating left-to-right and right-to-left order.

binary treebreadth first search
medium
144

Pseudo-Palindromic Paths in a Binary Tree

Count root-to-leaf paths whose digits can be rearranged to form a palindrome.

binary treedepth first search
medium
145

N-Queens

Return all valid N-Queens boards in deterministic DFS placement order.

backtrackingmatrix
hard
146

Rotate String

Check whether one string can be rotated to become another.

strings
easy

FAQ