Blind Plus 100, visualized.
Step through every algorithm, compare four approaches from brute force to production grade, and rehearse the follow-up questions an interviewer will ask. 100 of 100 problems are live: the 75 Blind problems plus 25 advanced hard ones.
#1 · Arrays & Hashing
Two Sum
Given an array of integers and a target, return the indices of the two numbers that add up to the target. Exactly one solution exists and you may not use the same element twice.
#2 · Sliding Window
Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring that contains no repeated character.
#3 · Trees
Invert Binary Tree
Given the root of a binary tree, invert it (swap every node's left and right children) and return its root.
#4 · Graphs
Course Schedule
There are n courses, and prerequisites[i] = [a, b] means you must take b before a. Return true if you can finish all courses, which is the same as asking whether the prerequisite graph has no cycle.
#5 · 1D DP
Coin Change
Given coin denominations and a target amount, return the fewest coins needed to make that amount, or −1 if it is impossible. Each coin can be used any number of times.
#6 · Arrays & Hashing
Contains Duplicate
Given an integer array, return true if any value appears at least twice, and false if every element is distinct.
#7 · Arrays & Hashing
Valid Anagram
Given two strings s and t, return true if t is an anagram of s: the same letters, each used exactly the same number of times, in any order.
#8 · Sliding Window
Best Time to Buy and Sell Stock
Given daily prices, choose one day to buy and a later day to sell to maximize profit. Return the maximum profit, or 0 if no profitable trade exists.
#9 · Arrays & Hashing
Product of Array Except Self
Return an array where out[i] is the product of every element of nums except nums[i], in O(n) time and without using division.
#10 · Arrays & Hashing
Group Anagrams
Given an array of strings, group the anagrams together. You may return the groups in any order.
#11 · Arrays & Hashing
Encode and Decode Strings
Design an algorithm to encode a list of strings into a single string, and decode it back to the original list. The strings can contain any characters, so no character is safe to use as a plain separator.
#12 · Arrays & Hashing
Longest Consecutive Sequence
Given an unsorted array of integers, return the length of the longest run of consecutive values (like 1, 2, 3, 4), regardless of their order in the array. The solution must run in O(n) time.
#13 · Two Pointers
Valid Palindrome
After lowercasing and removing every non-alphanumeric character, a phrase is a palindrome if it reads the same forwards and backwards. Given a string, return true if it is a palindrome.
#14 · Two Pointers
3Sum
Given an integer array, return all unique triplets [a, b, c] with a + b + c = 0. The solution set must not contain duplicate triplets.
#15 · Two Pointers
Container With Most Water
Given n vertical lines of given heights, pick two of them that together with the x-axis form a container holding the most water, and return that amount. (Area = distance between the lines × the shorter height.)
#16 · Sliding Window
Minimum Window Substring
Given strings s and t, return the shortest substring of s that contains every character of t (including duplicates). Return an empty string if no such window exists.
#17 · Sliding Window
Longest Repeating Character Replacement
Given a string of uppercase letters and an integer k, you may replace at most k characters with any letter. Return the length of the longest substring that can be turned into a single repeated letter.
#18 · Linked List
Reverse Linked List
Given the head of a singly linked list, reverse the list and return the new head.
#19 · Linked List
Merge Two Sorted Lists
Merge two sorted linked lists into one sorted list by splicing together the nodes of the two lists, and return its head.
#20 · Linked List
Reorder List
Rearrange L0 → L1 → … → Ln−1 → Ln into L0 → Ln → L1 → Ln−1 → L2 → … in place, without changing any node values.
#21 · Linked List
Remove Nth Node From End of List
Given the head of a linked list, remove the n-th node from the end of the list and return its head.
#22 · Linked List
Linked List Cycle
Given the head of a linked list, return true if the list contains a cycle: some node can be reached again by continuously following next.
#23 · Linked List
Merge k Sorted Lists
Given an array of k sorted linked lists, merge them into one sorted linked list and return its head.
#24 · Stack
Valid Parentheses
Given a string containing only '(', ')', '{', '}', '[' and ']', determine whether it is valid: every bracket is closed by the same type, in the correct order.
#25 · Binary Search
Find Minimum in Rotated Sorted Array
A sorted array of unique values was rotated an unknown number of times (for example [0,1,2,4,5,6,7] became [4,5,6,7,0,1,2]). Return its minimum element in O(log n) time.
#26 · Binary Search
Search in Rotated Sorted Array
A sorted array of distinct values was rotated at an unknown pivot. Given a target, return its index, or −1 if it is absent, in O(log n) time.
#27 · Heap / Priority Queue
Top K Frequent Elements
Given an integer array and an integer k, return the k most frequent elements, in any order. The algorithm should be better than O(n log n).
#28 · Heap / Priority Queue
Find Median from Data Stream
Design a data structure that supports addNum(num), which inserts an integer from a data stream, and findMedian(), which returns the median of everything inserted so far.
#29 · Trees
Maximum Depth of Binary Tree
Given the root of a binary tree, return its maximum depth: the number of nodes on the longest path from the root down to the farthest leaf.
#30 · Trees
Same Tree
Given the roots of two binary trees p and q, return true if they are structurally identical and every pair of corresponding nodes has the same value.
#31 · Trees
Subtree of Another Tree
Given the roots of two binary trees root and subRoot, return true if some node of root together with ALL of its descendants is identical to subRoot.
#32 · Trees
Lowest Common Ancestor of a BST
Given a binary SEARCH tree and two of its nodes p and q, find their lowest common ancestor: the deepest node that has both p and q as descendants (a node counts as a descendant of itself).
#33 · Trees
Binary Tree Level Order Traversal
Given the root of a binary tree, return the values of its nodes level by level, from left to right, as a list of lists.
#34 · Trees
Validate Binary Search Tree
Given the root of a binary tree, decide whether it is a valid binary search tree: for EVERY node, all values in its left subtree are smaller and all values in its right subtree are larger.
#35 · Trees
Kth Smallest Element in a BST
Given the root of a binary search tree and an integer k, return the k-th smallest value (1-indexed) among all node values.
#36 · Trees
Construct Binary Tree from Preorder and Inorder Traversal
Given the pre-order and in-order traversals of a binary tree with distinct values, rebuild and return the tree.
#37 · Trees
Binary Tree Maximum Path Sum
A path is a sequence of nodes where each adjacent pair is connected by an edge; it need not pass through the root. Return the maximum sum of node values over all non-empty paths in the tree.
#38 · Trees
Serialize and Deserialize Binary Tree
Design an algorithm to turn a binary tree into a string (serialize) and to rebuild exactly the same tree from that string (deserialize). The encoding format is up to you.
#39 · Tries
Implement Trie (Prefix Tree)
Design a Trie with insert(word), search(word) for an exact stored word, and startsWith(prefix) for any stored word that begins with the prefix.
#40 · Tries
Design Add and Search Words Data Structure
Design a WordDictionary with addWord(word) and search(pattern), where a "." in the pattern matches any single letter.
#41 · Tries
Word Search II
Given an m × n board of letters and a list of words, return every word that can be built from letters of sequentially adjacent cells (up, down, left, right), using each cell at most once per word.
#42 · Backtracking
Combination Sum
Given distinct positive integers and a target, return every unique combination of the numbers that adds up to the target. The same number may be used any number of times, and order inside a combination does not matter.
#43 · Backtracking
Word Search
Given an m × n grid of letters and a word, return true if the word can be constructed from letters of sequentially adjacent cells (horizontal or vertical), using each cell at most once.
#44 · Graphs
Clone Graph
Given a reference to a node in a connected undirected graph, return a deep copy: new nodes with the same values and the same neighbour structure, sharing nothing with the original.
#45 · Graphs
Number of Islands
Given an m × n grid of "1" (land) and "0" (water), count the islands. An island is land connected horizontally or vertically; diagonal contact does not count.
#46 · Graphs
Pacific Atlantic Water Flow
Given a grid of heights, rain water flows to a neighbouring cell with equal or lower height. The Pacific touches the top and left edges and the Atlantic touches the bottom and right edges. Return every cell from which water can flow to both oceans.
#47 · Graphs
Graph Valid Tree
Given n nodes labelled 0 to n − 1 and a list of undirected edges, check whether the edges form a valid tree: connected, with no cycles.
#48 · Graphs
Number of Connected Components in an Undirected Graph
Given n nodes labelled 0 to n − 1 and a list of undirected edges, return the number of connected components.
#49 · Advanced Graphs
Alien Dictionary
You receive a list of words from an alien language, sorted lexicographically by that language's own alphabet. Return a string of its letters in a valid order, or an empty string if the ordering is inconsistent.
#50 · 1D DP
Climbing Stairs
You climb a staircase of n steps, taking 1 or 2 steps at a time. In how many distinct ways can you reach the top?
#51 · 1D DP
House Robber
Given the amount of money in each house along a street, return the maximum you can rob without robbing two adjacent houses.
#52 · 1D DP
House Robber II
The houses are arranged in a circle, so the first and last houses are neighbours. Return the maximum you can rob without robbing two adjacent houses.
#53 · 1D DP
Longest Palindromic Substring
Given a string s, return its longest palindromic substring (a contiguous part that reads the same forwards and backwards).
#54 · 1D DP
Palindromic Substrings
Given a string s, return the number of palindromic substrings in it. Substrings with different positions count separately even if they have the same letters.
#55 · 1D DP
Decode Ways
A message of digits encodes letters with A=1 … Z=26. Given a string of digits, return the number of ways to decode it. A zero cannot stand alone.
#56 · 1D DP
Maximum Product Subarray
Given an integer array, find a contiguous non-empty subarray with the largest product and return that product.
#57 · 1D DP
Word Break
Given a string s and a dictionary of words, return true if s can be split into a sequence of one or more dictionary words (words may be reused).
#58 · 1D DP
Longest Increasing Subsequence
Given an integer array, return the length of the longest strictly increasing subsequence (elements in order, not necessarily adjacent).
#59 · 2D DP
Unique Paths
A robot starts at the top-left of an m × n grid and may move only right or down. How many distinct paths lead to the bottom-right corner?
#60 · 2D DP
Longest Common Subsequence
Given two strings, return the length of their longest common subsequence: the longest sequence of characters that appears, in order but not necessarily contiguously, in both.
#61 · Greedy
Maximum Subarray
Given an integer array, find the contiguous non-empty subarray with the largest sum and return that sum.
#62 · Greedy
Jump Game
Each element of the array is the maximum jump length from that position. Starting at the first index, can you reach the last index?
#63 · Intervals
Merge Intervals
Given a list of intervals [start, end], merge all overlapping ones and return the non-overlapping intervals that cover the same ranges.
#64 · Intervals
Insert Interval
Given sorted, non-overlapping intervals and a new interval, insert the new interval and merge any overlaps, returning a sorted list of non-overlapping intervals.
#65 · Intervals
Non-overlapping Intervals
Given a list of intervals, return the minimum number of intervals to remove so that the remaining ones do not overlap. Intervals that only touch (one ends where the next starts) do not overlap.
#66 · Intervals
Meeting Rooms
Given meeting time intervals [start, end), determine whether one person could attend all of them (no two overlap).
#67 · Intervals
Meeting Rooms II
Given meeting time intervals [start, end), return the minimum number of conference rooms required so that every meeting has a room.
#68 · Math & Geometry
Rotate Image
Rotate an n × n matrix 90 degrees clockwise, in place (this version also returns the matrix so the result can be checked).
#69 · Math & Geometry
Spiral Matrix
Given an m × n matrix, return all its elements in spiral order, starting at the top-left and going clockwise.
#70 · Math & Geometry
Set Matrix Zeroes
If an element of an m × n matrix is 0, set its entire row and column to 0, in place (this version also returns the matrix so the result can be checked).
#71 · Bit Manipulation
Number of 1 Bits
Given an unsigned integer, return the number of 1 bits in its binary representation (its Hamming weight).
#72 · Bit Manipulation
Counting Bits
Given n, return an array ans of length n + 1 where ans[i] is the number of 1 bits in the binary representation of i.
#73 · Bit Manipulation
Reverse Bits
Reverse the bits of a 32-bit unsigned integer: the lowest bit becomes the highest, and so on.
#74 · Bit Manipulation
Missing Number
Given an array of n distinct numbers taken from the range 0 … n, return the one number in that range that is missing from the array.
#75 · Bit Manipulation
Sum of Two Integers
Return the sum of two integers a and b without using the operators + and -.
#76 · Two Pointers
Trapping Rain Water
Given n non-negative integers representing an elevation map where each bar has width 1, compute how much water it can trap after raining.
#77 · Arrays & Hashing
First Missing Positive
Given an unsorted integer array nums, return the smallest missing positive integer. The intended solution runs in O(n) time and uses O(1) auxiliary space.
#78 · Arrays & Hashing
Subarray Sum Equals K
Given an integer array nums and an integer k, return the total number of contiguous subarrays whose sum equals k. Values may be negative.
#79 · Sliding Window
Sliding Window Maximum
Given an integer array nums and a window size k that slides from the far left to the far right one position at a time, return the maximum of each window.
#80 · Stack
Largest Rectangle in Histogram
Given an array of bar heights where each bar has width 1, return the area of the largest rectangle in the histogram.
#81 · Stack
Maximal Rectangle
Given a rows × cols binary matrix filled with 0s and 1s, find the largest rectangle containing only 1s and return its area.
#82 · Stack
Remove Duplicate Letters
Given a string s, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.
#83 · Stack
Longest Valid Parentheses
Given a string containing just the characters ( and ), return the length of the longest valid (well-formed) parentheses substring.
#84 · Binary Search
Median of Two Sorted Arrays
Given two sorted arrays nums1 and nums2 of sizes m and n, return the median of the two sorted arrays. The overall run time complexity should be O(log (m + n)).
#85 · Trees
Lowest Common Ancestor of a Binary Tree
Given a binary tree (no ordering guarantees) and two nodes p and q, find their lowest common ancestor: the deepest node that has both p and q as descendants (a node can be a descendant of itself).
#86 · Heap / Priority Queue
The Skyline Problem
Given buildings as [left, right, height] triples sorted by left edge, return the skyline: the list of key points [x, height] where the outline of the merged silhouette changes height, ending with a point on the ground.
#87 · Heap / Priority Queue
Smallest Range Covering Elements from K Lists
Given k lists of integers sorted in non-decreasing order, find the smallest range [a, b] that includes at least one number from each of the k lists. Among equally small ranges, prefer the one with the smaller start.
#88 · Backtracking
N-Queens
Place n queens on an n × n chessboard so that no two queens attack each other, and return all distinct board configurations ("Q" for a queen, "." for an empty square).
#89 · Graphs
Word Ladder
Given beginWord, endWord and a dictionary wordList, return the number of words in the shortest transformation sequence from beginWord to endWord, where each step changes exactly one letter and every intermediate word is in wordList; return 0 if none exists.
#90 · Graphs
Bus Routes
routes[i] is a bus that travels its stops in a loop forever. Starting at stop source (not yet on any bus), return the fewest buses you must take to reach stop target, or −1 if it is impossible.
#91 · Advanced Graphs
Reconstruct Itinerary
Given airline tickets as [from, to] pairs, reconstruct the itinerary that starts at "JFK" and uses every ticket exactly once. If several valid itineraries exist, return the one with the smallest lexical order.
#92 · Advanced Graphs
Critical Connections in a Network
There are n servers numbered 0 … n − 1 connected by undirected connections forming a connected network. A critical connection (bridge) is one whose removal makes some servers unable to reach others. Return all critical connections in any order.
#93 · 2D DP
Edit Distance
Given two strings word1 and word2, return the minimum number of operations (insert a character, delete a character, replace a character) required to convert word1 into word2.
#94 · 2D DP
Burst Balloons
You are given n balloons with numbers nums[i]. Bursting balloon i earns nums[i - 1] * nums[i] * nums[i + 1] coins (out-of-range neighbours count as 1). Return the maximum coins you can collect by bursting all balloons wisely.
#95 · 2D DP
Regular Expression Matching
Implement regular expression matching with support for "." (any single character) and "*" (zero or more of the preceding element). The match must cover the entire input string.
#96 · 2D DP
Minimum Cost to Cut a Stick
A wooden stick of length n has marks at the positions in cuts. Cutting a stick costs the length of the stick being cut. Choose the order of cuts to minimise the total cost, and return that minimum.
#97 · 2D DP
Interleaving String
Given strings s1, s2 and s3, decide whether s3 is formed by interleaving s1 and s2: merging them into one string while keeping the relative order of the characters inside each of s1 and s2.
#98 · Design
LRU Cache
Design a data structure for a Least Recently Used cache with get(key) and put(key, value) running in O(1) average time. When the capacity is exceeded, evict the least recently used key.
#99 · Design
LFU Cache
Design a Least Frequently Used cache with get(key) and put(key, value) in O(1) average time. When full, evict the key used the fewest times; if several tie, evict the least recently used among them.
#100 · Design
All O(1) Data Structure
Design a data structure that stores strings with counts and supports inc(key), dec(key) (removing the key when its count reaches 0), getMaxKey() and getMinKey(), each in O(1) average time.