Data Structures & Algorithms

Roadmap
0 Completed

out of 300 problems

0%

Completed
In Progress

Interactive visualizations to help you understand complex algorithms. Browse problems by category and difficulty.

​
Arrays & Hashing
29
Two Sum
Easy

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

Contains Duplicate
Easy

Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.

Valid Anagram
Easy

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

Group Anagrams
Medium

Given an array of strings strs, group the anagrams together. You can return the answer in any order.

Top K Frequent
Medium

Given an integer array nums and an integer k, return the k most frequent elements.

Product Except Self
Medium

Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].

Valid Sudoku
Medium

Determine if a 9x9 Sudoku board is valid.

Longest Consecutive Sequence
Medium

Find the length of the longest consecutive elements sequence in O(n) time.

Encode and Decode Strings
Medium

Design an algorithm to encode a list of strings to a string. The encoded string is then sent over the network and is decoded back to the original list of strings.

Subarray Sum Equals K
Medium

Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k.

Find the Duplicate Number
Medium

Given an array of n + 1 integers where each integer is in the range [1, n], find the one repeated number without modifying the array and using only O(1) space.

Rotate Array
Medium

Given an integer array nums, rotate the array to the right by k steps, where k is non-negative. Do it in-place with O(1) extra space.

Pascal's Triangle
Easy

Given an integer numRows, return the first numRows of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it.

Majority Element
Easy

Given an array nums of size n, return the majority element. The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.

Move Zeroes
Easy

Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. Note that you must do this in-place without making a copy of the array.

Missing Number
Easy

Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.

Merge Sorted Array
Easy

Merge nums2 into nums1 as one sorted array. nums1 has enough space (size m + n) to hold additional elements from nums2.

Plus One
Easy

Given a large integer represented as an integer array digits, increment the large integer by one and return the resulting array of digits.

Intersection of Two Arrays
Easy

Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.

Remove Element
Easy

Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. Return the number of elements in nums which are not equal to val.

Contains Duplicate II
Easy

Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k.

Find All Duplicates in an Array
Medium

Given an integer array nums of length n where all the integers are in the range [1, n] and each integer appears once or twice, return an array of all the integers that appear twice. You must write an algorithm that runs in O(n) time and uses only constant extra space.

4Sum
Medium

Find all unique quadruplets in the array which gives the sum of target.

First Missing Positive
Hard

Given an unsorted integer array nums, return the smallest missing positive integer. Must run in O(n) time and O(1) auxiliary space.

Find All Numbers Disappeared in an Array
Easy

Given an array nums of n integers where nums[i] is in the range [1, n], return an array of all the integers in the range [1, n] that do not appear in nums. You must write an algorithm that runs in O(n) time and uses only constant extra space.

Largest Number
Medium

Given a list of non-negative integers nums, arrange them such that they form the largest number and return it.

Next Permutation
Medium

A permutation of an array of integers is an arrangement of its members into a sequence or linear order. The next permutation of an array is the next lexicographically greater permutation. If such arrangement is not possible, it must rearrange it as the lowest possible order (i.e., sorted in ascending order).

Count of Smaller Numbers After Self
Hard

Given an integer array nums, return an integer array counts where counts[i] is the number of smaller elements to the right of nums[i].

Detect Squares
Medium

You are given a stream of points on the X-Y plane. Design an algorithm that adds new points from the stream into a data structure. Duplicate points are allowed and should be treated as different points. Given a query point, counts the number of ways to choose three points from the data structure such that the three points and the query point form an axis-aligned square with positive area.

Backtracking
17
Word Search II
Hard

Given an m x n board of characters and a list of strings words, return all words on the board.

Word Search
Medium

Given an m x n grid of characters board and a string word, return true if word exists in the grid. The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.

Combination Sum
Medium

Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target.

Permutations
Medium

Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.

Subsets
Medium

Given an integer array nums of unique elements, return all possible subsets (the power set). The solution set must not contain duplicate subsets. Return the solution in any order.

Subsets II
Medium

Given an integer array nums that may contain duplicates, return all possible subsets (the power set). The solution set must not contain duplicate subsets. Return the solution in any order.

Combination Sum II
Medium

Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target. Each number in candidates may only be used once in the combination.

Palindrome Partitioning
Medium

Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s.

Letter Combinations of a Phone Number
Medium

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.

Generate Parentheses
Medium

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

Combination Sum III
Medium

Find all valid combinations of k numbers that sum up to n such that: Only numbers 1 through 9 are used, each number is used at most once. Return a list of all possible valid combinations.

Restore IP Addresses
Medium

A valid IP address consists of exactly four integers separated by single dots. Each integer is between 0 and 255 (inclusive) and cannot have leading zeros. Given a string s containing only digits, return all possible valid IP addresses that can be formed by inserting dots into s.

N-Queens
Hard

Place n queens on an n x n chessboard such that no two queens attack each other. Return all distinct solutions.

Combinations
Medium

Given two integers n and k, return all possible combinations of k numbers chosen from the range [1, n]. You may return the answer in any order.

Sudoku Solver
Hard

Write a program to solve a Sudoku puzzle by filling the empty cells. A sudoku solution must satisfy all of the following rules: Each of the digits 1-9 must occur exactly once in each row, column, and 3x3 sub-box.

Remove Invalid Parentheses
Hard

Given a string s that contains parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid. Return all possible results.

Expression Add Operators
Hard

Given a string num that contains only digits and an integer target, return all possible expressions by adding the binary operators +, -, or * between the digits so that the expression evaluates to the target value.

Binary Search
19
Binary Search
Easy

Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.

Search a 2D Matrix
Medium

Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix.

Search in Rotated Sorted Array
Medium

Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums.

Find Minimum in Rotated Sorted Array
Medium

Suppose an array of length n sorted in ascending order is rotated between 1 and n times. Find the minimum element of this array.

Koko Eating Bananas
Medium

Koko loves to eat bananas. There are n piles of bananas, the ith pile has piles[i] bananas. The guards have gone and will come back in h hours. Koko can decide her bananas-per-hour eating speed of k. Each hour, she chooses some pile of bananas and eats k bananas from that pile. If the pile has less than k bananas, she eats all of them instead and will not eat any more bananas during this hour. Return the minimum integer k such that she can eat all the bananas within h hours.

Time Based Key-Value Store
Medium

Design a time-based key-value data structure that can store multiple values for the same key at different time stamps and retrieve the key's value at a certain timestamp.

Search a 2D Matrix II
Medium

Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties: Integers in each row are sorted in ascending from left to right. Integers in each column are sorted in ascending from top to bottom.

Kth Smallest Element in a Sorted Matrix
Medium

Given an n x n matrix where each of the rows and columns is sorted in ascending order, return the kth smallest element in the matrix. Note that it is the kth smallest element in the sorted order, not the kth distinct element.

Find Peak Element
Medium

A peak element is an element that is strictly greater than its neighbors. Given a 0-indexed integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks.

Single Element in a Sorted Array
Medium

You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Return the single element that appears only once.

Median of Two Sorted Arrays
Hard

Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

Capacity To Ship Packages Within D Days
Medium

A conveyor belt has packages that must be shipped from one port to another within days days. The ith package has a weight of weights[i]. Each day, we load the ship with packages on the conveyor belt (in the order given by weights). We may not load more weight than the maximum weight capacity of the ship. Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within days days.

Split Array Largest Sum
Hard

Given an integer array nums and an integer m, split the array into m non-empty continuous subarrays. Write an algorithm to minimize the largest sum among these m subarrays.

Find K Closest Elements
Medium

Given a sorted array, find the k closest integers to x. The result should also be sorted in ascending order.

Find First and Last Position of Element in Sorted Array
Medium

Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value. If target is not found, return [-1, -1].

Sqrt(x)
Easy

Given a non-negative integer x, return the square root of x rounded down to the nearest integer.

Search Insert Position
Easy

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be inserted.

First Bad Version
Easy

You are a product manager and currently leading a team to develop a new product. Since each version is developed based on the previous version, all the versions after a bad version are also bad. Find the first bad version.

Kth Missing Positive Number
Easy

Given an array arr of positive integers sorted in a strictly increasing order, and an integer k, return the kth positive integer that is missing from this array.

Bit Manipulation
8
Single Number
Easy

Given a non-empty array of integers nums, every element appears twice except for one. Find that single one. You must implement a solution with linear runtime complexity and use only constant extra space.

Reverse Bits
Easy

Reverse bits of a given 32 bits unsigned integer.

Number of 1 Bits
Easy

Write a function that takes the binary representation of an unsigned integer and returns the number of 1 bits it has (also known as the Hamming weight).

Power of Two
Easy

Given an integer n, return true if it is a power of two. Otherwise, return false.

Counting Bits
Easy

Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1's in the binary representation of i.

Sum of Two Integers
Medium

Given two integers a and b, return the sum of the two integers without using the operators + and -. Use bitwise operations instead.

Bitwise AND of Numbers Range
Medium

Given two integers left and right that represent the range [left, right], return the bitwise AND of all numbers in this range, inclusive.

Maximum XOR of Two Numbers in an Array
Medium

Given an integer array nums, return the maximum result of nums[i] XOR nums[j], where 0 <= i <= j < n.

Design
4
LRU Cache
Medium

Design a data structure that follows the constraints of a Least Recently Used (LRU) cache. Implement the LRUCache class with get(key) returning the value or -1 if not found, and put(key, value) to insert or update. When capacity is exceeded, evict the least recently used key.

LFU Cache
Hard

Design and implement a data structure for a Least Frequently Used (LFU) cache. Implement get and put operations with O(1) time complexity.

Data Stream as Disjoint Intervals
Hard

Given a data stream input of non-negative integers, summarize the numbers seen so far as a list of disjoint intervals.

Design In-Memory File System
Hard

Design an in-memory file system to simulate ls, mkdir, addContentToFile, and readContentFromFile operations.

Dynamic Programming
49
Climbing Stairs
Easy

You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

House Robber
Medium

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Maximum Product Subarray
Medium

Given an integer array nums, find a subarray that has the largest product, and return the product.

Word Break
Medium

Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words.

Coin Change
Medium

You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.

Longest Increasing Subsequence
Medium

Given an integer array nums, return the length of the longest strictly increasing subsequence.

Decode Ways
Medium

A message containing letters from A-Z can be encoded into numbers using the mapping: 'A' -> "1", 'B' -> "2", ... 'Z' -> "26". To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above. Given a string s containing only digits, return the number of ways to decode it.

Unique Paths
Medium

There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time. Given the two integers m and n, return the number of possible unique paths that the robot can take to reach the bottom-right corner.

Longest Common Subsequence
Medium

Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0.

Palindromic Substrings
Medium

Given a string s, return the number of palindromic substrings in it. A string is a palindrome when it reads the same backward as forward.

House Robber II
Medium

You are a robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Adjacent houses have security systems connected and will automatically contact police if two adjacent houses were broken into on the same night. Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.

Min Cost Climbing Stairs
Easy

You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps. You can either start from the step with index 0, or the step with index 1. Return the minimum cost to reach the top of the floor.

Minimum Path Sum
Medium

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path. You can only move either down or right at any point in time.

Edit Distance
Hard

Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2. Operations: insert, delete, or replace a character.

Longest Palindromic Substring
Medium

Given a string s, return the longest palindromic substring in s.

Interleaving String
Medium

Given strings s1, s2, and s3, determine if s3 is formed by interleaving s1 and s2 while preserving their relative order.

Partition Equal Subset Sum
Medium

Given an integer array nums, return true if you can partition the array into two subsets such that the sum of the elements in both subsets is equal.

Maximum Sum Circular Subarray
Medium

Given a circular integer array nums, return the maximum possible sum of a non-empty subarray. A circular array means the end connects to the beginning.

Target Sum
Medium

You are given an integer array nums and an integer target. You want to build an expression out of nums by adding one of the symbols '+' and '-' before each integer in nums. Return the number of different expressions that you can build, which evaluates to target.

Best Time to Buy and Sell Stock with Cooldown
Medium

Find the maximum profit with a cooldown period of 1 day after selling (cannot buy the next day after selling).

Best Time to Buy and Sell Stock III
Hard

Find the maximum profit with at most two transactions. You may not engage in multiple transactions simultaneously (you must sell the stock before you buy again).

Best Time to Buy and Sell Stock IV
Hard

You are given an integer array prices where prices[i] is the price of a given stock on the ith day, and an integer k. Find the maximum profit you can achieve. You may complete at most k transactions. Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

Longest Valid Parentheses
Hard

Given a string containing just the characters '(' and ')', return the length of the longest valid (well-formed) parentheses substring.

Coin Change II
Medium

You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. Return the number of combinations that make up that amount. If that amount of money cannot be made up by any combination of the coins, return 0.

Maximal Square
Medium

Given an m x n binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.

Wildcard Matching
Hard

Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*' where: '?' Matches any single character. '*' Matches any sequence of characters (including the empty sequence).

Triangle
Medium

Given a triangle array, return the minimum path sum from top to bottom. For each step, you may move to an adjacent number of the row below. More formally, if you are on index i on the current row, you may move to either index i or index i + 1 on the next row.

Longest Increasing Path in a Matrix
Hard

Given an m x n integers matrix, return the length of the longest increasing path in matrix. From each cell, you can either move in four directions: left, right, up, or down. You may not move diagonally or move outside the boundary.

Minimum Falling Path Sum
Medium

Given an n x n matrix, return the minimum sum of any falling path through the matrix. A falling path starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right.

Longest Palindromic Subsequence
Medium

Given a string s, find the longest palindromic subsequence's length in s. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.

Dungeon Game
Hard

The demons had captured the princess and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of m x n rooms. Our valiant knight was initially positioned in the top-left room and must fight through the dungeon to rescue the princess. The knight has an initial health point. Some rooms have demons that decrease health, others have magic orbs that increase health. Determine the minimum initial health needed so the knight can rescue the princess.

Distinct Subsequences
Hard

Given two strings s and t, return the number of distinct subsequences of s which equals t. A subsequence of a string is a new string formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters.

Burst Balloons
Hard

You are given n balloons, indexed from 0 to n - 1. Each balloon is painted with a number on it represented by an array nums. You are asked to burst all the balloons. If you burst the ith balloon, you will get nums[i - 1] * nums[i] * nums[i + 1] coins. If i - 1 or i + 1 goes out of bounds, treat it as if there is a balloon with a 1 painted on it. Return the maximum coins you can collect by bursting the balloons wisely.

Ones and Zeroes
Medium

You are given an array of binary strings strs and two integers m and n. Return the size of the largest subset of strs such that there are at most m 0's and n 1's in the subset.

Regular Expression Matching
Hard

Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: '.' Matches any single character. '*' Matches zero or more of the preceding element. The matching should cover the entire input string (not partial).

Maximal Rectangle
Hard

Given a rows x cols binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.

Word Break II
Hard

Given a string s and a dictionary of strings wordDict, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in any order.

Palindrome Partitioning II
Hard

Given a string s, partition s such that every substring of the partition is a palindrome. Return the minimum cuts needed for a palindrome partitioning of s.

Russian Doll Envelopes
Hard

You are given a 2D array of integers envelopes where envelopes[i] = [wi, hi] represents the width and height of an envelope. Return the maximum number of envelopes you can Russian doll (i.e., put one inside other).

Maximum Profit in Job Scheduling
Hard

We have n jobs, where every job is scheduled to be done from startTime[i] to endTime[i], obtaining a profit of profit[i]. Return the maximum profit you can take such that there are no two jobs with overlapping time ranges.

Super Egg Drop
Hard

You are given k identical eggs and you have access to a building with n floors. Your goal is to determine the minimum number of moves needed to find the critical floor f where eggs start breaking.

Odd Even Jump
Hard

You are given an integer array arr. From some starting index, you can make a series of jumps. The first jump is odd, the second is even, and so on. From index i, during odd jumps you can jump to j where arr[j] is the smallest value >= arr[i] with j > i. During even jumps, jump to j where arr[j] is the largest value <= arr[i] with j > i. Return the number of good starting indices.

Cherry Pickup II
Hard

You are given a rows x cols matrix grid representing a field of cherries where grid[i][j] represents the number of cherries you can collect from cell (i, j). Two robots are located at (0, 0) and (0, cols-1). Return the maximum number of cherries collected using both robots by moving towards the bottom.

Minimum Difficulty of a Job Schedule
Hard

You want to schedule a list of jobs in d days. Jobs are dependent so you have to finish all jobs from index 0 to i before working on job i+1. Each day you must work on at least one job. The difficulty of a day is the maximum difficulty of a job done that day. Return the minimum sum of difficulties of each day.

Frog Jump
Hard

A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water. Given a list of stones positions in sorted ascending order, determine if the frog can cross the river by landing on the last stone. Initially, the frog is on the first stone and assumes the first jump must be 1 unit.

Number of Ways to Cut a Pizza
Hard

Given a rectangular pizza represented as a rows x cols matrix containing 'A' (apple) and '.', cut the pizza into k pieces using k-1 cuts. For each cut, you choose the direction: horizontal or vertical, then cut the pizza. The piece given away is either the upper part if horizontal or the left part if vertical. Return the number of ways to cut such that each piece contains at least one apple.

Strange Printer
Hard

A strange printer can only print a sequence of the same character each turn. At each turn, the printer can print new characters starting from and ending at any place and will cover the original existing characters. Given a string s, return the minimum number of turns the printer needs to print it.

Maximum Number of Events That Can Be Attended II
Hard

Given an array of events where events[i] = [startDay, endDay, value], and an integer k. You can attend at most k events. You cannot attend two events that overlap. Return the maximum sum of values that you can receive by attending events.

Make Array Strictly Increasing
Hard

Given two integer arrays arr1 and arr2, return the minimum number of operations to make arr1 strictly increasing. In one operation, you can replace any element in arr1 with any element from arr2. If impossible, return -1.

Graph
33
Number of Islands
Medium

Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.

Clone Graph
Medium

Given a reference of a node in a connected undirected graph. Return a deep copy (clone) of the graph.

Course Schedule
Medium

There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai. Return true if you can finish all courses. Otherwise, return false.

Pacific Atlantic Water Flow
Medium

Return a list of grid coordinates where water can flow to both the Pacific and Atlantic oceans.

Cheapest Flights Within K Stops
Medium

There are n cities connected by some number of flights. You are given an array flights where flights[i] = [fromi, toi, pricei] indicates that there is a flight from city fromi to city toi with cost pricei. You are also given three integers src, dst, and k, return the cheapest price from src to dst with at most k stops. If there is no such route, return -1.

Count Connected Components
Medium

You have a graph of n nodes. You are given an integer n and an array edges where edges[i] = [ai, bi] indicates that there is an edge between ai and bi in the graph. Return the number of connected components in the graph.

Graph Valid Tree
Medium

Given n nodes labeled from 0 to n - 1 and a list of undirected edges, write a function to check whether these edges make up a valid tree.

Redundant Connection
Medium

In this problem, a tree is an undirected graph that is connected and has no cycles. You are given a graph that started as a tree with n nodes labeled from 1 to n, with one additional edge added. The added edge has two different vertices chosen from 1 to n, and was not an edge that already existed. The graph is represented as an array edges of length n where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the graph. Return an edge that can be removed so that the resulting graph is a tree of n nodes. If there are multiple answers, return the answer that occurs last in the input.

Max Area of Island
Medium

You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical). Return the maximum area of an island in grid. If there is no island, return 0.

Rotting Oranges
Medium

You are given an m x n grid where each cell can have one of three values: 0 (empty), 1 (fresh orange), or 2 (rotten orange). Every minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten. Return the minimum number of minutes until no cell has a fresh orange. If impossible, return -1.

Course Schedule II
Medium

There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai. Return the ordering of courses you should take to finish all courses. If there are many valid answers, return any of them. If it is impossible to finish all courses, return an empty array.

Surrounded Regions
Medium

Given an m x n matrix board containing 'X' and 'O', capture all regions that are 4-directionally surrounded by 'X'. A region is captured by flipping all 'O's into 'X's in that surrounded region.

Word Ladder
Hard

Given two words beginWord and endWord, and a dictionary wordList, return the number of words in the shortest transformation sequence from beginWord to endWord (changing one letter at a time).

Accounts Merge
Medium

Given a list of accounts where each account contains a name and emails, merge accounts belonging to the same person (accounts that share at least one common email).

Alien Dictionary
Hard

There is a new alien language that uses the English alphabet. However, the order among the letters is unknown to you. You are given a list of strings words from the alien language's dictionary, where the strings in words are sorted lexicographically by the rules of this new language. Return a string of the unique letters in the new alien language sorted in lexicographically increasing order by the new rules. If there is no solution, return "".

Min Cost to Connect All Points
Medium

You are given an array points representing integer coordinates of some points on a 2D-plane, where points[i] = [xi, yi]. The cost of connecting two points [xi, yi] and [xj, yj] is the manhattan distance between them: |xi - xj| + |yi - yj|. Return the minimum cost to make all points connected.

Network Delay Time
Medium

You are given a network of n nodes, labeled from 1 to n. You are also given times, a list of travel times as directed edges times[i] = (ui, vi, wi), where ui is the source node, vi is the target node, and wi is the time it takes for a signal to travel from source to target. We send a signal from a given node k. Return the minimum time it takes for all the n nodes to receive the signal. If it is impossible for all the n nodes to receive the signal, return -1.

Reconstruct Itinerary
Hard

You are given a list of airline tickets where tickets[i] = [fromi, toi] represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it.

Is Graph Bipartite?
Medium

There is an undirected graph with n nodes, where each node is numbered between 0 and n - 1. You are given a 2D array graph, where graph[u] is an array of nodes that node u is adjacent to. Return true if and only if it is bipartite.

Evaluate Division
Medium

You are given an array of variable pairs equations and an array of real numbers values, where equations[i] = [Ai, Bi] and values[i] represent the equation Ai / Bi = values[i]. Each Ai or Bi is a string that represents a single variable. You are also given some queries, where queries[j] = [Cj, Dj] represents the jth query where you must find the answer for Cj / Dj = ?. Return the answers to all queries.

Number of Provinces
Medium

There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b, and city b is connected directly with city c, then city a is connected indirectly with city c. A province is a group of directly or indirectly connected cities and no other cities outside of the group. Return the total number of provinces.

Shortest Path in Binary Matrix
Medium

Given an n x n binary matrix grid, return the length of the shortest clear path in the matrix. If there is no clear path, return -1. A clear path is a path from the top-left cell (0, 0) to the bottom-right cell (n-1, n-1) such that all the visited cells are 0. You may move 8-directionally (horizontal, vertical, and diagonal).

Path With Minimum Effort
Medium

You are a hiker preparing for an upcoming hike. You are given heights, a 2D array of size rows x columns, where heights[row][col] represents the height of cell (row, col). You are situated in the top-left cell, (0, 0), and you hope to travel to the bottom-right cell, (rows-1, columns-1). The effort required to travel from one cell to an adjacent cell is the absolute difference of their heights. Return the minimum effort required to travel from the top-left cell to the bottom-right cell.

Number of Connected Components
Medium

You have a graph of n nodes. You are given an integer n and an array edges where edges[i] = [ai, bi] indicates that there is an edge between ai and bi in the graph. Return the number of connected components in the graph.

Swim in Rising Water
Hard

You are given an n x n integer matrix grid where each value grid[i][j] represents the elevation at that point (i, j). The rain starts to fall. At time t, the depth of the water everywhere is t. You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both squares individually are at most t. You can swim infinite distances in zero time. Return the least time until you can reach the bottom right square (n - 1, n - 1) starting from the top left square (0, 0).

Minimum Height Trees
Medium

A tree is an undirected graph in which any two vertices are connected by exactly one path. Given a tree of n nodes labelled from 0 to n - 1, and an array of n - 1 edges, you can choose any node of the tree as the root. The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf. Return a list of all MHTs root labels. You can return the answer in any order.

Critical Connections in a Network
Hard

There are n servers numbered from 0 to n - 1 connected by undirected server-to-server connections forming a network where connections[i] = [ai, bi] represents a connection between servers ai and bi. Any server can reach other servers directly or indirectly through the network. A critical connection is a connection that, if removed, will make some servers unable to reach some other server. Return all critical connections in the network in any order.

Most Stones Removed with Same Row or Column
Medium

On a 2D plane, we place n stones at some integer coordinate points. Each coordinate point may have at most one stone. A stone can be removed if it shares either the same row or the same column as another stone that has not been removed. Given an array stones of length n where stones[i] = [xi, yi] represents the location of the ith stone, return the largest possible number of stones that can be removed.

Redundant Connection II
Hard

In this problem, a rooted tree is a directed graph such that, there is exactly one node (the root) for which all other nodes are descendants of this node, plus every node has exactly one parent, except for the root node which has no parents. The given input is a directed graph that started as a rooted tree with n nodes (with distinct values from 1 to n), with one additional directed edge added. Return an edge that can be removed so that the resulting graph is a rooted tree of n nodes.

Regions Cut By Slashes
Medium

An n x n grid is composed of 1 x 1 squares where each 1 x 1 square consists of a '/', '\', or blank space ' '. These characters divide the square into contiguous regions. Given the grid grid represented as a string array, return the number of regions.

Word Ladder II
Hard

A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that every adjacent pair differs by a single letter, every si is in wordList, and sk == endWord. Given two words and a dictionary, return all the shortest transformation sequences.

Couples Holding Hands
Hard

N couples sit in 2N seats arranged in a row. You want every couple to sit side by side. Couples are numbered (0,1), (2,3), etc. A swap consists of choosing any two people and having them swap seats. Return the minimum number of swaps so that every couple is sitting side by side.

Bus Routes
Hard

Given an array routes where routes[i] is a bus route that the ith bus repeats forever. You start at bus stop source and want to go to bus stop target. Return the least number of buses you must take to travel from source to target, or -1 if impossible.

Graphs
1
Walls and Gates
Medium

Given a m x n grid where -1 is a wall, 0 is a gate, and INF (2147483647) is an empty room. Fill each empty room with the distance to its nearest gate. If impossible to reach a gate, leave it as INF.

Greedy
12
Maximum Subarray
Medium

Given an integer array nums, find the subarray with the largest sum, and return its sum.

Jump Game
Medium

You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position. Return true if you can reach the last index, or false otherwise.

Valid Parenthesis String
Medium

Given a string s containing only three types of characters: '(', ')' and '*', return true if s is valid.

Partition Labels
Medium

You are given a string s. We want to partition the string into as many parts as possible so that each letter appears in at most one part. Return a list of integers representing the size of these parts.

Hand of Straights
Medium

Alice has some number of cards and she wants to rearrange the cards into groups so that each group is of size groupSize, and consists of groupSize consecutive cards. Given an integer array hand where hand[i] is the value written on the ith card and an integer groupSize, return true if she can rearrange the cards, or false otherwise.

Merge Triplets to Form Target Triplet
Medium

A triplet is an array of three integers. You are given a 2D integer array triplets, where triplets[i] = [ai, bi, ci]. You are also given an integer array target = [x, y, z] that describes the triplet you want to obtain. To obtain target, you may apply the following operation on triplets any number of times (possibly zero): Choose two indices (0-indexed) i and j (i != j) and update triplets[j] to become [max(ai, aj), max(bi, bj), max(ci, cj)]. Return true if it is possible to obtain the target triplet [x, y, z] as an element of triplets, or false otherwise.

Gas Station
Medium

There are n gas stations along a circular route, where the amount of gas at the ith station is gas[i]. You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from the ith station to its next (i + 1)th station. You begin the journey with an empty tank at one of the gas stations. Return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1.

Jump Game II
Medium

You are given a 0-indexed array of integers nums of length n. You are initially positioned at nums[0]. Each element nums[i] represents the maximum length of a forward jump from index i. Return the minimum number of jumps to reach nums[n - 1].

Best Time to Buy and Sell Stock II
Medium

Find the maximum profit from buying and selling stock with unlimited transactions. You may hold at most one share at a time.

Minimum Number of Arrows to Burst Balloons
Medium

There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array points where points[i] = [xstart, xend] denotes a balloon whose horizontal diameter stretches between xstart and xend. You need to find the minimum number of arrows that must be shot to burst all balloons. An arrow can be shot at any integer x coordinate. A balloon with xstart and xend is burst by an arrow shot at x if xstart <= x <= xend.

Candy
Hard

There are n children standing in a line. Each child is assigned a rating value given in the integer array ratings. You are giving candies to these children subjected to the following requirements: Each child must have at least one candy. Children with a higher rating get more candies than their neighbors. Return the minimum number of candies you need to have to distribute the candies to the children.

Queue Reconstruction by Height
Medium

You are given an array of people, people, which are the attributes of some people in a queue (not necessarily in order). Each people[i] = [hi, ki] represents the ith person of height hi with exactly ki other people in front who have a height >= hi. Reconstruct and return the queue that is represented by the input array.

Heap
14
Find Median from Data Stream
Hard

The median is the middle value in an ordered integer list. Implement the MedianFinder class.

Reorganize String
Medium

Given a string s, rearrange the characters of s so that any two adjacent characters are not the same. Return any possible rearrangement of s or return "" if not possible.

Task Scheduler
Medium

Given a characters array tasks, representing the tasks a CPU needs to do, where each letter represents a different task. Tasks could be done in any order. Each task is done in one unit of time. For each unit of time, the CPU could complete either one task or just be idle. However, there is a non-negative integer n that represents the cooldown period between two same tasks (the same letter in the array), that is that there must be at least n units of time between any two same tasks.

Kth Largest Element in a Stream
Easy

Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.

Last Stone Weight
Easy

You have a collection of stones with positive integer weights. Each turn, choose the two heaviest stones and smash them. If they have different weights, the lighter one is destroyed and the heavier one loses weight equal to the lighter. Return the weight of the last remaining stone, or 0 if none remain.

K Closest Points to Origin
Medium

Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0). The distance between two points is the Euclidean distance. You may return the answer in any order.

Kth Largest Element in an Array
Medium

Given an integer array nums and an integer k, return the kth largest element in the array. Note that it is the kth largest element in the sorted order, not the kth distinct element.

Find K Pairs with Smallest Sums
Medium

Given two sorted arrays nums1 and nums2, find k pairs (u1, v1), (u2, v2), ..., (uk, vk) with the smallest sums.

Design Twitter
Medium

Design a simplified version of Twitter where users can post tweets, follow/unfollow another user, and see the 10 most recent tweets in their news feed. Implement the Twitter class with postTweet, getNewsFeed, follow, and unfollow methods.

The Skyline Problem
Hard

A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return the skyline formed by these buildings collectively.

Smallest Range Covering Elements from K Lists
Hard

You have k lists of sorted integers. Find the smallest range that includes at least one number from each of the k lists.

Minimum Number of Refueling Stops
Hard

A car travels from a starting position to a destination which is target miles east. Along the way, there are gas stations. Return the minimum number of refueling stops the car must make to reach destination. If it cannot reach the destination, return -1.

Max Value of Equation
Hard

Given an array of points sorted by x-coordinate and an integer k, find the maximum value of the equation yi + yj + |xi - xj| where |xi - xj| <= k and i < j.

Sliding Window Median
Hard

Given an array nums and an integer k, return an array of the median of each window of size k moving from left to right.

Intervals
7
Non-overlapping Intervals
Medium

Given an array of intervals intervals where intervals[i] = [starti, endi], return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.

Meeting Rooms
Easy

Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), determine if a person could attend all meetings.

Meeting Rooms II
Medium

Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), find the minimum number of conference rooms required.

Insert Interval
Medium

You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start, end] that represents the start and end of another interval. Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary).

Merge Intervals
Medium

Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.

Meeting Rooms III
Hard

You are given an integer n. There are n rooms numbered from 0 to n - 1. You are given a 2D integer array meetings where meetings[i] = [starti, endi] means that a meeting will be held during the closed time interval [starti, endi]. All the values of starti are unique. Return the room number that held the most meetings.

Minimum Interval to Include Each Query
Hard

You are given a 2D integer array intervals, where intervals[i] = [lefti, righti] describes the ith interval starting at lefti and ending at righti (inclusive). The size of an interval is defined as the number of integers it contains, or more formally righti - lefti + 1. You are also given an integer array queries. The answer to the jth query is the size of the smallest interval i such that lefti <= queries[j] <= righti. If no such interval exists, the answer is -1.

Linked List
18
Reverse Linked List
Easy

Given the head of a singly linked list, reverse the list, and return the reversed list.

Linked List Cycle
Easy

Given head, the head of a linked list, determine if the linked list has a cycle in it. A cycle exists if there is some node that can be reached again by continuously following the next pointer.

Reorder List
Medium

You are given the head of a singly linked-list. The list can be represented as: L0 → L1 → … → Ln - 1 → Ln. Reorder the list to be on the following form: L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …

Merge Two Sorted Lists
Easy

You are given the heads of two sorted linked lists list1 and list2. Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists.

Remove Nth Node From End of List
Medium

Given the head of a linked list, remove the nth node from the end of the list and return its head.

Merge K Sorted Lists
Hard

You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.

Add Two Numbers
Medium

Given two non-empty linked lists representing two non-negative integers stored in reverse order, add them and return the sum as a linked list.

Copy List with Random Pointer
Medium

A linked list of length n is given such that each node contains an additional random pointer, which could point to any node in the list, or null. Construct a deep copy of the list.

Reverse Nodes in k-Group
Hard

Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list.

Palindrome Linked List
Easy

Given the head of a singly linked list, return true if it is a palindrome or false otherwise.

Swap Nodes in Pairs
Medium

Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the nodes.

Remove Linked List Elements
Easy

Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.

Linked List Cycle II
Medium

Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null.

Middle of the Linked List
Easy

Given the head of a singly linked list, return the middle node of the linked list. If there are two middle nodes, return the second middle node.

Intersection of Two Linked Lists
Easy

Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null.

Rotate List
Medium

Given the head of a linked list, rotate the list to the right by k places.

Odd Even Linked List
Medium

Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list. The first node is considered odd, and the second node is even, and so on.

Sort List
Medium

Sort a linked list in O(n log n) time and O(1) memory space using merge sort.

Math
7
Pow(x, n)
Medium

Implement pow(x, n), which calculates x raised to the power n (i.e., x^n). Use the fast exponentiation algorithm to achieve O(log n) time complexity.

Happy Number
Easy

Write an algorithm to determine if a number n is happy. A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.

Count Primes
Medium

Given an integer n, return the number of prime numbers that are strictly less than n.

Reverse Integer
Medium

Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range, return 0.

Palindrome Number
Easy

Given an integer x, return true if x is a palindrome, and false otherwise.

Excel Sheet Column Number
Easy

Given a string columnTitle that represents the column title as appears in an Excel sheet, return its corresponding column number.

Multiply Strings
Medium

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string. You must not use any built-in BigInteger library or convert the inputs to integer directly.

Matrix
4
Rotate Image
Medium

You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). You have to rotate the image in-place.

Spiral Matrix
Medium

Given an m x n matrix, return all elements of the matrix in spiral order.

Set Matrix Zeroes
Medium

Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0s. You must do it in place.

Spiral Matrix II
Medium

Given a positive integer n, generate an n x n matrix filled with elements from 1 to n² in spiral order.

Sliding Window
9
Best Time to Buy and Sell Stock
Easy

You are given an array prices where prices[i] is the price of a given stock on the ith day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Longest Substring Without Repeating Characters
Medium

Given a string s, find the length of the longest substring without repeating characters.

Longest Repeating Character Replacement
Medium

You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times. Return the length of the longest substring containing the same letter you can get after performing the above operations.

Minimum Size Subarray Sum
Medium

Given an array of positive integers nums and a positive integer target, return the minimal length of a subarray whose sum is greater than or equal to target. If there is no such subarray, return 0.

Permutation in String
Medium

Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise. In other words, return true if one of s1's permutations is the substring of s2.

Sliding Window Maximum
Hard

You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window.

Find All Anagrams
Medium

Given two strings s and p, return an array of all the start indices of p's anagrams in s. You may return the answer in any order.

Minimum Window Substring
Hard

Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string "".

Longest Substring with At Most K Distinct Characters
Medium

Given a string s and an integer k, return the length of the longest substring of s that contains at most k distinct characters.

Sorting
3
Bubble Sort
Easy

Repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. Return the sorted array.

Selection Sort
Easy

Repeatedly finds the minimum element from the unsorted part and puts it at the beginning. Return the sorted array.

Insertion Sort
Easy

Builds the final sorted array (or list) one item at a time by comparisons. Return the sorted array.

Stack
11
Valid Parentheses
Easy

Given a string s containing just the characters "(", ")", "{", "}", "[" and "]", determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order.

Daily Temperatures
Medium

Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0.

Evaluate Reverse Polish Notation
Medium

Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, and /. Each operand may be an integer or another expression. Note that division between two integers should truncate toward zero.

Car Fleet
Medium

There are n cars going to the same destination along a one-lane road. The destination is target miles away. You are given two integer arrays position and speed, both of length n, where position[i] is the position of the ith car and speed[i] is the speed of the ith car (in miles per hour). A car can never pass another car ahead of it, but it can catch up to it and drive bumper to bumper at the same speed. The distance between these two cars is ignored - they are assumed to have the same position. A car fleet is some non-empty set of cars driving at the same position and same speed. Note that a single car is also a car fleet. If a car catches up to a car fleet at the destination point, it will still be considered as one car fleet. Return the number of car fleets that will arrive at the destination.

Largest Rectangle in Histogram
Hard

Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.

Min Stack
Medium

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

Remove K Digits
Medium

Given string num representing a non-negative integer num, and an integer k, return the smallest possible integer after removing k digits from num.

Asteroid Collision
Medium

Given an array of asteroids, find out the state after all collisions. Positive means moving right, negative means moving left. The larger asteroid survives.

Next Greater Element II
Medium

Given a circular integer array nums, return the next greater number for every element. Search circularly if needed. Return -1 if no greater element exists.

Basic Calculator
Hard

Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation. The expression string may contain open ( and closing ) parentheses, the plus + or minus - sign, non-negative integers and empty spaces.

Decode String
Medium

Given an encoded string, return its decoded string. The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times.

Strings
8
Longest Common Prefix
Easy

Write a function to find the longest common prefix string amongst an array of strings.

Roman to Integer
Easy

Given a roman numeral, convert it to an integer.

Length of Last Word
Easy

Given a string s consisting of words and spaces, return the length of the last word in the string.

Add Binary
Easy

Given two binary strings a and b, return their sum as a binary string.

Find the Index of the First Occurrence in a String
Easy

Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Isomorphic Strings
Easy

Given two strings s and t, determine if they are isomorphic. Two strings are isomorphic if the characters in s can be replaced to get t.

Shortest Palindrome
Hard

You are given a string s. You can convert s to a palindrome by adding characters in front of it. Return the shortest palindrome you can find by performing this transformation.

Text Justification
Hard

Given an array of words and a maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified.

Trees
32
Maximum Depth of Binary Tree
Easy

Given the root of a binary tree, return its maximum depth.

Invert Binary Tree
Easy

Given the root of a binary tree, invert the tree, and return its root.

Same Tree
Easy

Given the roots of two binary trees p and q, write a function to check if they are the same or not.

Subtree of Another Tree
Easy

Given the roots of two binary trees root and subRoot, return true if there is a subtree of root with the same structure and node values of subRoot and false otherwise.

Lowest Common Ancestor of a BST
Medium

Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.

Lowest Common Ancestor of a Binary Tree
Medium

Find the lowest common ancestor (LCA) of two nodes in a binary tree. The LCA is the lowest node that has both p and q as descendants.

Binary Tree Level Order Traversal
Medium

Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).

Validate Binary Search Tree
Medium

Given the root of a binary tree, determine if it is a valid binary search tree (BST).

Kth Smallest Element in a BST
Medium

Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree.

Construct Binary Tree from Preorder and Inorder
Medium

Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree.

Serialize and Deserialize Binary Tree
Hard

Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work.

Binary Tree Maximum Path Sum
Hard

A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root. The path sum is the sum of the node's values in the path. Given the root of a binary tree, return the maximum path sum of any non-empty path.

Binary Tree Right Side View
Medium

Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

Count Good Nodes in Binary Tree
Medium

Given a binary tree root, a node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X. Return the number of good nodes in the binary tree.

Diameter of Binary Tree
Easy

Given the root of a binary tree, return the length of the diameter of the tree.

Balanced Binary Tree
Easy

Given a binary tree, determine if it is height-balanced. A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.

Symmetric Tree
Easy

Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).

Path Sum
Easy

Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.

Path Sum II
Medium

Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where the sum of the node values in the path equals targetSum.

Flatten Binary Tree to Linked List
Medium

Given the root of a binary tree, flatten the tree into a "linked list": The "linked list" should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null. The "linked list" should be in the same order as a pre-order traversal of the binary tree.

Populating Next Right Pointers
Medium

You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.

Zigzag Level Order Traversal
Medium

Given the root of a binary tree, return the zigzag level order traversal of its nodes values. (i.e., from left to right, then right to left for the next level and alternate between).

Minimum Depth of Binary Tree
Easy

Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

Binary Tree Paths
Easy

Given the root of a binary tree, return all root-to-leaf paths in any order.

Maximum Width of Binary Tree
Medium

Given the root of a binary tree, return the maximum width of the given tree. The maximum width of a tree is the maximum width among all levels. The width of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-nodes that would be present in a complete binary tree are also counted.

Sum of Left Leaves
Easy

Given the root of a binary tree, return the sum of all left leaves. A leaf is a node with no children. A left leaf is a leaf that is the left child of another node.

Convert Sorted Array to Binary Search Tree
Easy

Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.

Recover Binary Search Tree
Medium

Two nodes of a BST are swapped by mistake. Recover the tree without changing its structure.

Binary Search Tree Iterator
Medium

Implement the BSTIterator class that represents an iterator over the in-order traversal of a binary search tree (BST). The class should have a constructor that takes the root of a BST, a next() method that returns the next smallest number, and a hasNext() method that returns whether there is a next number.

Range Sum Query - Mutable
Medium

Given an integer array nums, handle multiple queries of the following types: Update the value of an element in nums. Calculate the sum of the elements of nums between indices left and right inclusive where left <= right. Implement the NumArray class with update(index, val) and sumRange(left, right) methods.

Binary Tree Cameras
Hard

You are given the root of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children. Return the minimum number of cameras needed to monitor all nodes of the tree.

Longest Path With Different Adjacent Characters
Hard

Given a tree represented by parent array and a string s where s[i] is the character assigned to node i, return the length of the longest path where adjacent nodes have different characters.

Trie
5
Implement Trie (Prefix Tree)
Medium

A trie (prefix tree) is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. Implement the Trie class with insert, search, and startsWith methods.

Design Add and Search Words Data Structure
Medium

Design a data structure that supports adding new words and finding if a string matches any previously added string. Implement the WordDictionary class with addWord(word) and search(word) methods. search(word) can search a literal word or a regular expression string containing only letters a-z or '.'. A '.' means it can represent any one letter.

Palindrome Pairs
Hard

Given a list of unique words, return all pairs of distinct indices (i, j) such that the concatenation of words[i] + words[j] is a palindrome.

Concatenated Words
Hard

Given an array of strings words (without duplicates), return all the concatenated words in the given list. A concatenated word is a string that is comprised entirely of at least two shorter words in the given array.

Prefix and Suffix Search
Hard

Design a special dictionary that searches words by a prefix and a suffix. Implement WordFilter with constructor that takes words array, and f(prefix, suffix) that returns the index of the word with given prefix and suffix. If multiple words match, return the largest index.

Two Pointers
10
Valid Palindrome
Easy

A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward.

Two Sum II - Input Array Is Sorted
Medium

Find two numbers that add up to a specific target number in a sorted array. Return 1-based indices.

3Sum
Medium

Find all unique triplets in the array which gives the sum of zero.

Container With Most Water
Medium

Find two lines that together with the x-axis form a container, such that the container contains the most water.

Trapping Rain Water
Hard

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.

Reverse String
Easy

Write a function that reverses a string. The input string is given as an array of characters s. You must do this by modifying the input array in-place with O(1) extra memory.

Remove Duplicates from Sorted Array
Easy

Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. Return the number of unique elements.

Sort Colors
Medium

Given an array with n objects colored red, white, or blue (represented by 0, 1, and 2), sort them in-place so that objects of the same color are adjacent (Dutch National Flag problem).

Valid Palindrome II
Easy

Given a string s, return true if the s can be palindrome after deleting at most one character from it.

Squares of a Sorted Array
Easy

Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.