Algorithms
Data structures and algorithms problems, each with a step-by-step explanation, a worked example and tested Java code. 497 problems in 21 topics.
Fundamentals
Arrays & Hashing 68 problems
- 4 Sum
- 4Sum II
- Array With Elements Not Equal to Average of Neighbors
- Best Time to Buy and Sell Stock II
- Brick Wall
- Can Place Flowers
- Candy Distribution
- Concatenation of Array
- Contains Duplicates
- Continuous Subarray Sum
- Count Distinct Integers After Reverse Operations
- Count Number of Texts
- Design HashSet
- Design Parking System
- Design Underground System
- Dota2 Senate
- Find All Numbers Disappeared in An Array
- Find Pivot Index
- Find the Difference of Two Arrays
- First Missing Positive
- Grid Game
- Kth Largest Element in an Array
- Kth Missing Positive Number
- Largest Number
- Longest Consecutive Sequence
- Majority Element
- Make Array Strictly Increasing
- Max Chunks To Make Sorted
- Maximum Number of Coins You Can Get
- Maximum Number of Tasks You Can Assign
- Maximum Profit in Job Scheduling
- Maximum Subarray
- Maximum Sum Circular Subarray
- Maximum Sum of 3 Non-Overlapping Subarrays
- Maximum Width Ramp
- Median of two sorted arrays of same size
- Merge Sorted Array
- Minimum Difference Between Highest and Lowest of K Scores
- Minimum Jumps to Reach Home
- Minimum Operations to Make Array Continuous
- Minimum Penalty for a Shop
- Naming a Company
- Next Greater Element
- Non Decreasing Array
- Number of Pairs of Interchangeable Rectangles
- Number of Subsequences That Satisfy the Given Sum Condition
- Number of Ways to Split Array
- Number of Zero-Filled Subarrays
- Pascal's Triangle
- Product of Array Except Self
- Push Dominoes
- Range Sum Query - Immutable
- Range Sum Query 2D Immutable
- Remove Duplicates From Sorted Array II
- Remove Element
- Replace Elements with Greatest Element on Right Side
- Rotate Array
- Shortest Subarray with Sum at Least K
- Sign of An Array
- Subarray Sum Equals K
- Subarrays with K Different Integers
- Text Justification
- Top K Frequent Elements
- Transpose Matrix
- Two Sum
- Unique Email Addresses
- Valid Sudoku
- Wiggle Sort
Strings & Hashing 40 problems
- Basic Calculator II
- Break a String Into Maximum Number of Unique Substrings
- Check if a String Contains all Binary Codes of Size K
- Count and Say
- Count Binary Substrings
- Count Substrings That Differ by One Character
- Decode String
- Encode and Decode Strings
- Encode and Decode Tiny URL
- Find All Anagrams in a String
- Find And Replace in String
- Find The Index of The First Occurrence in a String
- Group Anagrams
- Integer to Roman
- Is String Has Unique Characters
- Is Subsequence
- Isomorphic Strings
- KMP String Matching
- Length Of Last Word
- Longest Common Prefix
- Longest Palindromic Substring
- Manacher's Algorithm
- Maximum Number of Balloons
- Maximum Product of The Length of Two Palindromic Subsequences
- Merge Strings Alternately
- Minimum Number of Swaps to Make The String Balanced
- Optimal Partition of String
- Repeated DNA Sequences
- Repeated String Match
- Reverse String
- Roman to Integer
- Rotate String
- Shortest Palindrome
- Sort Vowels in a String
- Unique Length-3 Palindromic Subsequences
- Valid Anagram
- Valid Palindrome
- Valid Palindrome II
- Word Pattern
- Z-Function (Z-Algorithm)
Two Pointers 18 problems
Start here: Two Pointers Basics- 3 Sum
- Backspace String Compare
- Boats to Save People
- Container With Most Water
- Count Pairs Whose Sum is Less Than Target
- Find the Duplicate Number
- Long Pressed Name
- Max Consecutive Ones II
- Minimum Length of String After Deleting Similar Ends
- Move Zeroes
- Remove Duplicates From Sorted Array
- Reverse Vowels of a String
- Reverse Words in a String
- Reverse Words in a String III
- Sort Array By Parity
- Squares of a Sorted Array
- Trapping Rain Water
- Two Sum II, Input Array Is Sorted
Sliding Window 26 problems
Start here: Sliding Window Basics- Best Time to Buy and Sell Stock
- Contains Duplicate II
- Count Subarrays Where Max Element Appears at Least K Times
- Find K Closest Elements
- Frequency of the Most Frequent Element
- Fruits Into Basket
- Longest Repeating Character Replacement
- Longest Subarray of 1s After Deleting One Element
- Longest Substring with At Least K Repeating Characters
- Longest Substring with at most K Distinct Characters
- Longest Substring with K Unique Characters
- Longest Substring Without Repeating Characters
- Max Consecutive Ones III
- Maximum Average Subarray I
- Maximum Erasure Value
- Maximum Number of Vowels in a Substring of Given Length
- Minimum Consecutive Cards to Pick Up
- Minimum Number of Flips to Make the Binary String Alternating
- Minimum Operations to Reduce X to Zero
- Minimum Size Subarray Sum
- Minimum Window Substring
- Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold
- Number of Substrings Containing All Three Characters
- Permutation in String
- Sliding Window Maximum
- Substrings of Size Three with Distinct Characters
Binary Search 26 problems
Start here: Binary Search Basics- Allocate Books (Book Allocation Problem)
- Arranging Coins
- Binary Search
- Capacity To Ship Packages Within D Days
- Find First and Last Position in Sorted Array
- Find K-th Smallest Pair Distance
- Find Minimum in Rotated Sorted Array
- Find Minimum in Rotated Sorted Array II (Duplicates)
- Find Peak Element
- Find Right Interval
- Guess Number Higher or Lower
- H-Index II
- Koko Eating Bananas
- Kth Smallest Element in a Sorted Matrix
- Median of Two Sorted Arrays
- Minimum Number of Days to Make m Bouquets
- Minimum Speed to Arrive on Time
- Search a 2D Matrix
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array II (Duplicates)
- Search Insert Position
- Single Element in a Sorted Array
- Smallest Divisor Given a Threshold
- Sqrt(x)
- Time Based Key-Value Store
- Valid Perfect Square
Sorting 9 problems
Math 20 problems
- Add Strings
- Bulb Switcher
- Count Primes
- Excel Sheet Column Number
- Excel Sheet Column Title
- FizzBuzz
- Happy Number
- Minimum Moves to Equal Array Elements
- Multiply Strings
- Nth Ugly Number
- Palindrome Number
- Plus One
- Pow(x, n)
- Power of Four
- Power of Three
- Prime Arrangements
- Random Pick with Weight
- Reverse Integer
- Strobogrammatic Number
- Ugly Number
Bit Manipulation 20 problems
Start here: Bit Manipulation Basics- Bitwise AND of Numbers Range
- Counting Bits
- Divide Two Integers
- Find the Difference
- Flip and Invert Image
- Gray Code
- Hamming Distance
- Maximum Product of Word Lengths
- Maximum XOR of Two Numbers in an Array
- Minimum Flips to Make a OR b Equal to c
- Missing Number
- Number of 1 Bits
- Power of Two
- Reverse Bits
- Single Number
- Single Number II
- Single Number III
- Sum of Two Integers
- Total Hamming Distance
- XOR Queries of a Subarray
Data Structures
Stack 23 problems
Start here: Monotonic Stack: Introduction- 132 Pattern
- Asteroid Collision
- Baseball Game
- Car Fleet
- Daily Temperatures
- Evaluate Reverse Polish Notation
- Exclusive Time of Functions
- Implement Stack using Queues
- Largest Rectangle in Histogram
- Max Stack
- Maximum Frequency Stack
- Min Stack
- Minimum Add to Make Parentheses Valid
- Minimum Remove to Make Valid Parentheses
- Next Greater Element II
- Online Stock Span
- Remove All Adjacent Duplicates in String II
- Remove K Digits
- Removing Stars From a String
- Simplify Path
- Sum of Subarray Minimums
- Valid Parentheses
- Validate Stack Sequences
Linked List 25 problems
- Add Two Numbers
- Add Two Numbers II
- Copy List with Random Pointer
- Delete Node in a Linked List
- Flatten a Multilevel Doubly Linked List
- Intersection of Two Linked Lists
- LFU Cache
- Linked List Cycle
- Linked List Cycle II
- LRU Cache
- Merge Two Sorted Linked Lists
- Merge Two Sorted Linked Lists And Remove Duplicates
- Middle of the Linked List
- Odd Even Linked List
- Palindrome Linked List
- Partition List
- Remove Duplicates from Sorted List
- Remove Nth Node From End of List
- Reorder List
- Reverse a Linked List
- Reverse Linked List II
- Reverse Nodes in k-Group
- Rotate List
- Sort List
- Swap Nodes in Pairs
Heap / Priority Queue 16 problems
Start here: Heap / Priority Queue - Introduction- Course Schedule III
- Farthest Building You Can Reach
- Find Kth Largest Integer in the Array
- Find Median from Data Stream
- IPO
- K Closest Points to Origin
- Kth Largest Element in a Stream
- Last Stone Weight
- Maximum Subsequence Score
- Merge K Sorted Lists
- Minimum Cost to Hire K Workers
- Reorganize String
- Sliding Window Median
- Smallest Number in Infinite Set
- Smallest Range Covering Elements from K Lists
- Sort Characters By Frequency
Trees 34 problems
Start here: Trees - Introduction- All Nodes Distance K in Binary Tree
- Average of Levels in Binary Tree
- Balanced Binary Tree
- Binary Tree Level Order Traversal
- Binary Tree Maximum Path Sum
- Binary Tree Paths
- Binary Tree Right Side View
- Binary Tree Zigzag Level Order Traversal
- Construct Binary Tree from Inorder and Postorder Traversal
- Construct Binary Tree from Preorder and Inorder Traversal
- Count Good Nodes in Binary Tree
- Delete Node in a BST
- Diameter of Binary Tree
- Flatten Binary Tree to Linked List
- Insert into a BST
- Invert Binary Tree
- Kth Smallest Element in a BST
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a BST
- Maximum Depth of Binary Tree
- Maximum Difference Between Node and Ancestor
- Maximum Width of Binary Tree
- Path Sum
- Path Sum II
- Path Sum III
- Populating Next Right Pointers in Each Node
- Recover Binary Search Tree
- Same Tree
- Serialize and Deserialize Binary Tree
- Subtree of Another Tree
- Sum of Left Leaves
- Symmetric Tree
- Validate Binary Search Tree
- Vertical Order Traversal of a Binary Tree
Trie 12 problems
Matrix 10 problems
Design 12 problems
Graphs
Graph 38 problems
Start here: Graph - Introduction- Alien Dictionary
- All Ancestors of a Node in a Directed Acyclic Graph
- Cheapest Flights Within K Stops
- Clone Graph
- Course Schedule
- Critical Connections in a Network
- Find Eventual Safe States
- Graph - Breadth First Search (BFS)
- Graph - Depth First Search (DFS)
- Graph - Dijkstra's Shortest Path Algorithm
- Graph - Kruskal's Minimum Spanning Tree (MST)
- Graph - Prim's Minimum Spanning Tree (MST)
- Graph Valid Tree
- Keys and Rooms
- Longest Path With Different Adjacent Characters
- Making a Large Island
- Max Area of Island
- Minesweeper
- Minimum Cost to Connect All Points
- Minimum Height Trees
- Network Delay Time
- Number of Closed Islands
- Number of Enclaves
- Number of Islands
- Number of Operations to Make Network Connected
- Pacific Atlantic Water Flow
- Parallel Courses
- Reconstruct Itinerary
- Rotting Oranges
- Satisfiability of Equality Equations
- Shortest Path in Binary Matrix
- Shortest Path in Unweighted Graph (BFS)
- Surrounded Regions
- Swim in Rising Water
- Topological Sort
- Walls and Gates
- Word Ladder
- Word Ladder II
Union Find 7 problems
Techniques
Backtracking 19 problems
Start here: Backtracking Basics- All Paths From Source to Target
- Beautiful Arrangement
- Combination Sum
- Combination Sum II
- Combination Sum III
- Fair Distribution of Cookies
- Generate Parentheses
- Letter Case Permutation
- Letter Combinations of a Phone Number
- N-Queens
- N-Queens II
- Palindrome Partitioning II
- Permutations
- Permutations II
- Restore IP Addresses
- Subsets
- Subsets II
- Sudoku Solver
- Word Search
Greedy 22 problems
- Assign Cookies
- Car Pooling
- Delete Columns to Make Sorted
- Gas Station
- Hand of Straights
- Jump Game
- Jump Game II
- Lemonade Change
- Maximum Swap
- Maximum Units on a Truck
- Merge Triplets to Form Target Triplet
- Minimum Cost to Connect Sticks
- Minimum Domino Rotations For Equal Row
- Minimum Number of Refueling Stops
- Minimum Number of Taps to Open to Water a Garden
- Partition Labels
- Queue Reconstruction by Height
- Remove Duplicate Letters
- Task Scheduler
- Two City Scheduling
- Valid Parenthesis String
- Wiggle Subsequence
Intervals 13 problems
- Data Stream as Disjoint Intervals
- Employee Free Time
- Insert Interval
- Interval List Intersections
- Meeting Rooms
- Meeting Rooms II (Min Rooms)
- Merge Intervals
- Minimum Interval to Include Each Query
- Minimum Number of Arrows to Burst Balloons
- My Calendar I
- Non-overlapping Intervals
- Remove Covered Intervals
- Split Array into Consecutive Subsequences
Dynamic Programming 39 problems
Start here: Dynamic Programming Introduction- Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock IV
- Best Time to Buy and Sell Stock with Cooldown
- Best Time to Buy and Sell Stock with Transaction Fee
- Climbing Stairs
- Coin Change
- Coin Change II
- Decode Ways
- Delete and Earn
- Distinct Subsequences
- Dungeon Game
- Edit Distance
- House Robber
- House Robber II
- Interleaving String
- Largest Divisible Subset
- Longest Common Subsequence
- Longest Increasing Subsequence
- Longest Palindromic Subsequence
- Maximal Square
- Maximum Product Subarray
- Min Cost Climbing Stairs
- Minimum Falling Path Sum
- Minimum Path Sum
- N-th Tribonacci Number
- Number of Longest Increasing Subsequences
- Number of Ways to Form a Target String Given a Dictionary
- Palindromic Substrings
- Partition Equal Subset Sum
- Perfect Squares
- Regular Expression Matching
- Scramble String
- Target Sum
- Triangle Minimum Path Sum
- Unique Paths
- Unique Paths II
- Video Stitching
- Wildcard Matching
- Word Break