2023-02-23
502. IPO
Topic: Array, Greedy, Sorting, Heap (Priority Queue)
Difficulty: Hard
Problem:
Suppose LeetCode will start its IPO soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the IPO. Since it has limited resources, it can only finish at most
You are given
Initially, you have
Pick a list of at most
The answer is guaranteed to fit in a 32-bit signed integer.
Example 1:
Example 2:
Constraints:
•
•
•
•
•
•
•
502. IPO
Topic: Array, Greedy, Sorting, Heap (Priority Queue)
Difficulty: Hard
Problem:
Suppose LeetCode will start its IPO soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the IPO. Since it has limited resources, it can only finish at most
k distinct projects before the IPO. Help LeetCode design the best way to maximize its total capital after finishing at most k distinct projects.You are given
n projects where the i^th project has a pure profit profits[i] and a minimum capital of capital[i] is needed to start it.Initially, you have
w capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital.Pick a list of at most
k distinct projects from given projects to maximize your final capital, and return the final maximized capital.The answer is guaranteed to fit in a 32-bit signed integer.
Example 1:
Input: k = 2, w = 0, profits = [1,2,3], capital = [0,1,1]
Output: 4
Explanation: Since your initial capital is 0, you can only start the project indexed 0.
After finishing it you will obtain profit 1 and your capital becomes 1.
With capital 1, you can either start the project indexed 1 or the project indexed 2.
Since you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital.
Therefore, output the final maximized capital, which is 0 + 1 + 3 = 4.
Example 2:
Input: k = 3, w = 0, profits = [1,2,3], capital = [0,1,2]
Output: 6
Constraints:
•
1 <= k <= 10^5•
0 <= w <= 10^9•
n == profits.length•
n == capital.length•
1 <= n <= 10^5•
0 <= profits[i] <= 10^4•
0 <= capital[i] <= 10^92023-02-24
1675. Minimize Deviation in Array
Topic: Array, Greedy, Heap (Priority Queue), Ordered Set
Difficulty: Hard
Problem:
You are given an array
You can perform two types of operations on any element of the array any number of times:
• If the element is even, divide it by
• For example, if the array is
• If the element is odd, multiply it by
• For example, if the array is
The deviation of the array is the maximum difference between any two elements in the array.
Return the minimum deviation the array can have after performing some number of operations.
Example 1:
Example 2:
Example 3:
Constraints:
•
•
•
1675. Minimize Deviation in Array
Topic: Array, Greedy, Heap (Priority Queue), Ordered Set
Difficulty: Hard
Problem:
You are given an array
nums of n positive integers.You can perform two types of operations on any element of the array any number of times:
• If the element is even, divide it by
2.• For example, if the array is
[1,2,3,4], then you can do this operation on the last element, and the array will be [1,2,3,2].• If the element is odd, multiply it by
2.• For example, if the array is
[1,2,3,4], then you can do this operation on the first element, and the array will be [2,2,3,4].The deviation of the array is the maximum difference between any two elements in the array.
Return the minimum deviation the array can have after performing some number of operations.
Example 1:
Input: nums = [1,2,3,4]
Output: 1
Explanation: You can transform the array to [1,2,3,2], then to [2,2,3,2], then the deviation will be 3 - 2 = 1.
Example 2:
Input: nums = [4,1,5,20,3]
Output: 3
Explanation: You can transform the array after two operations to [4,2,5,5,3], then the deviation will be 5 - 2 = 3.
Example 3:
Input: nums = [2,10,8]
Output: 3
Constraints:
•
n == nums.length•
2 <= n <= 5 * 10^4•
1 <= nums[i] <= 10^92023-02-25
121. Best Time to Buy and Sell Stock
Topic: Array, Dynamic Programming
Difficulty: Easy
Problem:
You are given an array
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.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return
Example 1:
Example 2:
Constraints:
•
•
121. Best Time to Buy and Sell Stock
Topic: Array, Dynamic Programming
Difficulty: Easy
Problem:
You are given an array
prices where prices[i] is the price of a given stock on the i^th 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.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return
0.Example 1:
Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
Example 2:
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.
Constraints:
•
1 <= prices.length <= 10^5•
0 <= prices[i] <= 10^42023-02-26
72. Edit Distance
Topic: String, Dynamic Programming
Difficulty: Hard
Problem:
Given two strings
You have the following three operations permitted on a word:
• Insert a character
• Delete a character
• Replace a character
Example 1:
Example 2:
Constraints:
•
•
72. Edit Distance
Topic: String, Dynamic Programming
Difficulty: Hard
Problem:
Given two strings
word1 and word2, return the minimum number of operations required to convert word1 to word2.You have the following three operations permitted on a word:
• Insert a character
• Delete a character
• Replace a character
Example 1:
Input: word1 = "horse", word2 = "ros"
Output: 3
Explanation:
horse -> rorse (replace 'h' with 'r')
rorse -> rose (remove 'r')
rose -> ros (remove 'e')
Example 2:
Input: word1 = "intention", word2 = "execution"
Output: 5
Explanation:
intention -> inention (remove 't')
inention -> enention (replace 'i' with 'e')
enention -> exention (replace 'n' with 'x')
exention -> exection (replace 'n' with 'c')
exection -> execution (insert 'u')
Constraints:
•
0 <= word1.length, word2.length <= 500•
word1 and word2 consist of lowercase English letters.2023-02-27
427. Construct Quad Tree
Topic: Array, Divide and Conquer, Tree, Matrix
Difficulty: Medium
Problem:
Given a
Return the root of the Quad-Tree representing the
Notice that you can assign the value of a node to True or False when
A Quad-Tree is a tree data structure in which each internal node has exactly four children. Besides, each node has two attributes:
•
•
We can construct a Quad-Tree from a two-dimensional area using the following steps:
1. If the current grid has the same value (i.e all
2. If the current grid has different values, set
3. Recurse for each of the children with the proper sub-grid.
Image: https://assets.leetcode.com/uploads/2020/02/11/new_top.png
If you want to know more about the Quad-Tree, you can refer to the wiki.
Quad-Tree format:
The output represents the serialized format of a Quad-Tree using level order traversal, where
It is very similar to the serialization of the binary tree. The only difference is that the node is represented as a list
If the value of
Example 1:
Image: https://assets.leetcode.com/uploads/2020/02/11/grid1.png
Example 2:
Image: https://assets.leetcode.com/uploads/2020/02/12/e2mat.png
Constraints:
•
•
427. Construct Quad Tree
Topic: Array, Divide and Conquer, Tree, Matrix
Difficulty: Medium
Problem:
Given a
n * n matrix grid of 0's and 1's only. We want to represent the grid with a Quad-Tree.Return the root of the Quad-Tree representing the
grid.Notice that you can assign the value of a node to True or False when
isLeaf is False, and both are accepted in the answer.A Quad-Tree is a tree data structure in which each internal node has exactly four children. Besides, each node has two attributes:
•
val: True if the node represents a grid of 1's or False if the node represents a grid of 0's.•
isLeaf: True if the node is leaf node on the tree or False if the node has the four children.class Node {
public boolean val;
public boolean isLeaf;
public Node topLeft;
public Node topRight;
public Node bottomLeft;
public Node bottomRight;
}
We can construct a Quad-Tree from a two-dimensional area using the following steps:
1. If the current grid has the same value (i.e all
1's or all 0's) set isLeaf True and set val to the value of the grid and set the four children to Null and stop.2. If the current grid has different values, set
isLeaf to False and set val to any value and divide the current grid into four sub-grids as shown in the photo.3. Recurse for each of the children with the proper sub-grid.
Image: https://assets.leetcode.com/uploads/2020/02/11/new_top.png
If you want to know more about the Quad-Tree, you can refer to the wiki.
Quad-Tree format:
The output represents the serialized format of a Quad-Tree using level order traversal, where
null signifies a path terminator where no node exists below.It is very similar to the serialization of the binary tree. The only difference is that the node is represented as a list
[isLeaf, val].If the value of
isLeaf or val is True we represent it as 1 in the list [isLeaf, val] and if the value of isLeaf or val is False we represent it as 0.Example 1:
Image: https://assets.leetcode.com/uploads/2020/02/11/grid1.png
Input: grid = [[0,1],[1,0]]
Output: [[0,1],[1,0],[1,1],[1,1],[1,0]]
Explanation: The explanation of this example is shown below:
Notice that 0 represnts False and 1 represents True in the photo representing the Quad-Tree.
Image: [https://assets.leetcode.com/uploads/2020/02/12/e1tree.png](https://assets.leetcode.com/uploads/2020/02/12/e1tree.png)
Example 2:
Image: https://assets.leetcode.com/uploads/2020/02/12/e2mat.png
Input: grid = [[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0]]
Output: [[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]]
Explanation: All values in the grid are not the same. We divide the grid into four sub-grids.
The topLeft, bottomLeft and bottomRight each has the same value.
The topRight have different values so we divide it into 4 sub-grids where each has the same value.
Explanation is shown in the photo below:
Image: [https://assets.leetcode.com/uploads/2020/02/12/e2tree.png](https://assets.leetcode.com/uploads/2020/02/12/e2tree.png)
Constraints:
•
n == grid.length == grid[i].length•
n == 2^x where 0 <= x <= 62023-02-28
652. Find Duplicate Subtrees
Topic: Hash Table, Tree, Depth-First Search, Binary Tree
Difficulty: Medium
Problem:
Given the
For each kind of duplicate subtrees, you only need to return the root node of any one of them.
Two trees are duplicate if they have the same structure with the same node values.
Example 1:
Image: https://assets.leetcode.com/uploads/2020/08/16/e1.jpg
Example 2:
Image: https://assets.leetcode.com/uploads/2020/08/16/e2.jpg
Example 3:
Image: https://assets.leetcode.com/uploads/2020/08/16/e33.jpg
Constraints:
• The number of the nodes in the tree will be in the range
•
652. Find Duplicate Subtrees
Topic: Hash Table, Tree, Depth-First Search, Binary Tree
Difficulty: Medium
Problem:
Given the
root of a binary tree, return all duplicate subtrees.For each kind of duplicate subtrees, you only need to return the root node of any one of them.
Two trees are duplicate if they have the same structure with the same node values.
Example 1:
Image: https://assets.leetcode.com/uploads/2020/08/16/e1.jpg
Input: root = [1,2,3,4,null,2,4,null,null,4]
Output: [[2,4],[4]]
Example 2:
Image: https://assets.leetcode.com/uploads/2020/08/16/e2.jpg
Input: root = [2,1,1]
Output: [[1]]
Example 3:
Image: https://assets.leetcode.com/uploads/2020/08/16/e33.jpg
Input: root = [2,2,2,3,null,3,null]
Output: [[2,3],[3]]
Constraints:
• The number of the nodes in the tree will be in the range
[1, 5000]•
-200 <= Node.val <= 2002023-03-01
912. Sort an Array
Topic: Array, Divide and Conquer, Sorting, Heap (Priority Queue), Merge Sort, Bucket Sort, Radix Sort, Counting Sort
Difficulty: Medium
Problem:
Given an array of integers
You must solve the problem without using any built-in functions in
Example 1:
Example 2:
Constraints:
•
•
912. Sort an Array
Topic: Array, Divide and Conquer, Sorting, Heap (Priority Queue), Merge Sort, Bucket Sort, Radix Sort, Counting Sort
Difficulty: Medium
Problem:
Given an array of integers
nums, sort the array in ascending order and return it.You must solve the problem without using any built-in functions in
O(nlog(n)) time complexity and with the smallest space complexity possible.Example 1:
Input: nums = [5,2,3,1]
Output: [1,2,3,5]
Explanation: After sorting the array, the positions of some numbers are not changed (for example, 2 and 3), while the positions of other numbers are changed (for example, 1 and 5).
Example 2:
Input: nums = [5,1,1,2,0,0]
Output: [0,0,1,1,2,5]
Explanation: Note that the values of nums are not necessairly unique.
Constraints:
•
1 <= nums.length <= 5 * 10^4•
-5 * 10^4 <= nums[i] <= 5 * 10^42023-03-02
443. String Compression
Topic: Two Pointers, String
Difficulty: Medium
Problem:
Given an array of characters
Begin with an empty string
• If the group's length is
• Otherwise, append the character followed by the group's length.
The compressed string
After you are done modifying the input array, return the new length of the array.
You must write an algorithm that uses only constant extra space.
Example 1:
Example 2:
Example 3:
Constraints:
•
•
443. String Compression
Topic: Two Pointers, String
Difficulty: Medium
Problem:
Given an array of characters
chars, compress it using the following algorithm:Begin with an empty string
s. For each group of consecutive repeating characters in chars:• If the group's length is
1, append the character to s.• Otherwise, append the character followed by the group's length.
The compressed string
s should not be returned separately, but instead, be stored in the input character array chars. Note that group lengths that are 10 or longer will be split into multiple characters in chars.After you are done modifying the input array, return the new length of the array.
You must write an algorithm that uses only constant extra space.
Example 1:
Input: chars = ["a","a","b","b","c","c","c"]
Output: Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"]
Explanation: The groups are "aa", "bb", and "ccc". This compresses to "a2b2c3".
Example 2:
Input: chars = ["a"]
Output: Return 1, and the first character of the input array should be: ["a"]
Explanation: The only group is "a", which remains uncompressed since it's a single character.
Example 3:
Input: chars = ["a","b","b","b","b","b","b","b","b","b","b","b","b"]
Output: Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"].
Explanation: The groups are "a" and "bbbbbbbbbbbb". This compresses to "ab12".
Constraints:
•
1 <= chars.length <= 2000•
chars[i] is a lowercase English letter, uppercase English letter, digit, or symbol.2023-03-03
28. Find the Index of the First Occurrence in a String
Topic: Two Pointers, String, String Matching
Difficulty: Medium
Problem:
Given two strings
Example 1:
Example 2:
Constraints:
•
•
28. Find the Index of the First Occurrence in a String
Topic: Two Pointers, String, String Matching
Difficulty: Medium
Problem:
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.Example 1:
Input: haystack = "sadbutsad", needle = "sad"
Output: 0
Explanation: "sad" occurs at index 0 and 6.
The first occurrence is at index 0, so we return 0.
Example 2:
Input: haystack = "leetcode", needle = "leeto"
Output: -1
Explanation: "leeto" did not occur in "leetcode", so we return -1.
Constraints:
•
1 <= haystack.length, needle.length <= 10^4•
haystack and needle consist of only lowercase English characters.2023-03-04
2444. Count Subarrays With Fixed Bounds
Topic: Array, Queue, Sliding Window, Monotonic Queue
Difficulty: Hard
Problem:
You are given an integer array
A fixed-bound subarray of
• The minimum value in the subarray is equal to
• The maximum value in the subarray is equal to
Return the number of fixed-bound subarrays.
A subarray is a contiguous part of an array.
Example 1:
Example 2:
Constraints:
•
•
2444. Count Subarrays With Fixed Bounds
Topic: Array, Queue, Sliding Window, Monotonic Queue
Difficulty: Hard
Problem:
You are given an integer array
nums and two integers minK and maxK.A fixed-bound subarray of
nums is a subarray that satisfies the following conditions:• The minimum value in the subarray is equal to
minK.• The maximum value in the subarray is equal to
maxK.Return the number of fixed-bound subarrays.
A subarray is a contiguous part of an array.
Example 1:
Input: nums = [1,3,5,2,7,5], minK = 1, maxK = 5
Output: 2
Explanation: The fixed-bound subarrays are [1,3,5] and [1,3,5,2].
Example 2:
Input: nums = [1,1,1,1], minK = 1, maxK = 1
Output: 10
Explanation: Every subarray of nums is a fixed-bound subarray. There are 10 possible subarrays.
Constraints:
•
2 <= nums.length <= 10^5•
1 <= nums[i], minK, maxK <= 10^62023-03-05
1345. Jump Game IV
Topic: Array, Hash Table, Breadth-First Search
Difficulty: Hard
Problem:
Given an array of integers
In one step you can jump from index
•
•
•
Return the minimum number of steps to reach the last index of the array.
Notice that you can not jump outside of the array at any time.
Example 1:
Example 2:
Example 3:
Constraints:
•
•
1345. Jump Game IV
Topic: Array, Hash Table, Breadth-First Search
Difficulty: Hard
Problem:
Given an array of integers
arr, you are initially positioned at the first index of the array.In one step you can jump from index
i to index:•
i + 1 where: i + 1 < arr.length.•
i - 1 where: i - 1 >= 0.•
j where: arr[i] == arr[j] and i != j.Return the minimum number of steps to reach the last index of the array.
Notice that you can not jump outside of the array at any time.
Example 1:
Input: arr = [100,-23,-23,404,100,23,23,23,3,404]
Output: 3
Explanation: You need three jumps from index 0 --> 4 --> 3 --> 9. Note that index 9 is the last index of the array.
Example 2:
Input: arr = [7]
Output: 0
Explanation: Start index is the last index. You do not need to jump.
Example 3:
Input: arr = [7,6,9,6,9,6,9,7]
Output: 1
Explanation: You can jump directly from index 0 to index 7 which is last index of the array.
Constraints:
•
1 <= arr.length <= 5 * 10^4•
-10^8 <= arr[i] <= 10^82023-03-06
1539. Kth Missing Positive Number
Topic: Array, Binary Search
Difficulty: Easy
Problem:
Given an array
Return the
Example 1:
Example 2:
Constraints:
•
•
•
•
Follow up:
Could you solve this problem in less than O(n) complexity?
1539. Kth Missing Positive Number
Topic: Array, Binary Search
Difficulty: Easy
Problem:
Given an array
arr of positive integers sorted in a strictly increasing order, and an integer k.Return the
k^th positive integer that is missing from this array.Example 1:
Input: arr = [2,3,4,7,11], k = 5
Output: 9
Explanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5^th missing positive integer is 9.
Example 2:
Input: arr = [1,2,3,4], k = 2
Output: 6
Explanation: The missing positive integers are [5,6,7,...]. The 2^nd missing positive integer is 6.
Constraints:
•
1 <= arr.length <= 1000•
1 <= arr[i] <= 1000•
1 <= k <= 1000•
arr[i] < arr[j] for 1 <= i < j <= arr.lengthFollow up:
Could you solve this problem in less than O(n) complexity?
2023-03-07
2187. Minimum Time to Complete Trips
Topic: Array, Binary Search
Difficulty: Medium
Problem:
You are given an array
Each bus can make multiple trips successively; that is, the next trip can start immediately after completing the current trip. Also, each bus operates independently; that is, the trips of one bus do not influence the trips of any other bus.
You are also given an integer
Example 1:
Example 2:
Constraints:
•
•
2187. Minimum Time to Complete Trips
Topic: Array, Binary Search
Difficulty: Medium
Problem:
You are given an array
time where time[i] denotes the time taken by the i^th bus to complete one trip.Each bus can make multiple trips successively; that is, the next trip can start immediately after completing the current trip. Also, each bus operates independently; that is, the trips of one bus do not influence the trips of any other bus.
You are also given an integer
totalTrips, which denotes the number of trips all buses should make in total. Return the minimum time required for all buses to complete at least totalTrips trips.Example 1:
Input: time = [1,2,3], totalTrips = 5
Output: 3
Explanation:
- At time t = 1, the number of trips completed by each bus are [1,0,0].
The total number of trips completed is 1 + 0 + 0 = 1.
- At time t = 2, the number of trips completed by each bus are [2,1,0].
The total number of trips completed is 2 + 1 + 0 = 3.
- At time t = 3, the number of trips completed by each bus are [3,1,1].
The total number of trips completed is 3 + 1 + 1 = 5.
So the minimum time needed for all buses to complete at least 5 trips is 3.
Example 2:
Input: time = [2], totalTrips = 1
Output: 2
Explanation:
There is only one bus, and it will complete its first trip at t = 2.
So the minimum time needed to complete 1 trip is 2.
Constraints:
•
1 <= time.length <= 10^5•
1 <= time[i], totalTrips <= 10^72023-03-08
875. Koko Eating Bananas
Topic: Array, Binary Search
Difficulty: Medium
Problem:
Koko loves to eat bananas. There are
Koko can decide her bananas-per-hour eating speed of
Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return.
Return the minimum integer
Example 1:
Example 2:
Example 3:
Constraints:
•
•
•
875. Koko Eating Bananas
Topic: Array, Binary Search
Difficulty: Medium
Problem:
Koko loves to eat bananas. There are
n piles of bananas, the i^th 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.Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return.
Return the minimum integer
k such that she can eat all the bananas within h hours.Example 1:
Input: piles = [3,6,7,11], h = 8
Output: 4
Example 2:
Input: piles = [30,11,23,4,20], h = 5
Output: 30
Example 3:
Input: piles = [30,11,23,4,20], h = 6
Output: 23
Constraints:
•
1 <= piles.length <= 10^4•
piles.length <= h <= 10^9•
1 <= piles[i] <= 10^92023-03-09
142. Linked List Cycle II
Topic: Hash Table, Linked List, Two Pointers
Difficulty: Medium
Problem:
Given the
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the
Do not modify the linked list.
Example 1:
Image: https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist.png
Example 2:
Image: https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test2.png
Example 3:
Image: https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test3.png
Constraints:
• The number of the nodes in the list is in the range
•
•
Follow up: Can you solve it using
142. Linked List Cycle II
Topic: Hash Table, Linked List, Two Pointers
Difficulty: Medium
Problem:
Given the
head of a linked list, return the node where the cycle begins. If there is no cycle, return null.There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the
next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to (0-indexed). It is -1 if there is no cycle. Note that pos is not passed as a parameter.Do not modify the linked list.
Example 1:
Image: https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist.png
Input: head = [3,2,0,-4], pos = 1
Output: tail connects to node index 1
Explanation: There is a cycle in the linked list, where tail connects to the second node.
Example 2:
Image: https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test2.png
Input: head = [1,2], pos = 0
Output: tail connects to node index 0
Explanation: There is a cycle in the linked list, where tail connects to the first node.
Example 3:
Image: https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test3.png
Input: head = [1], pos = -1
Output: no cycle
Explanation: There is no cycle in the linked list.
Constraints:
• The number of the nodes in the list is in the range
[0, 10^4].•
-10^5 <= Node.val <= 10^5•
pos is -1 or a valid index in the linked-list.Follow up: Can you solve it using
O(1) (i.e. constant) memory?2023-03-10
382. Linked List Random Node
Topic: Linked List, Math, Reservoir Sampling, Randomized
Difficulty: Medium
Problem:
Given a singly linked list, return a random node's value from the linked list. Each node must have the same probability of being chosen.
Implement the
•
•
Example 1:
Image: https://assets.leetcode.com/uploads/2021/03/16/getrand-linked-list.jpg
Constraints:
• The number of nodes in the linked list will be in the range
•
• At most
Follow up:
• What if the linked list is extremely large and its length is unknown to you?
• Could you solve this efficiently without using extra space?
382. Linked List Random Node
Topic: Linked List, Math, Reservoir Sampling, Randomized
Difficulty: Medium
Problem:
Given a singly linked list, return a random node's value from the linked list. Each node must have the same probability of being chosen.
Implement the
Solution class:•
Solution(ListNode head) Initializes the object with the head of the singly-linked list head.•
int getRandom() Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be chosen.Example 1:
Image: https://assets.leetcode.com/uploads/2021/03/16/getrand-linked-list.jpg
Input
["Solution", "getRandom", "getRandom", "getRandom", "getRandom", "getRandom"]
[[[1, 2, 3]], [], [], [], [], []]
Output
[null, 1, 3, 2, 2, 3]
Explanation
Solution solution = new Solution([1, 2, 3]);
solution.getRandom(); // return 1
solution.getRandom(); // return 3
solution.getRandom(); // return 2
solution.getRandom(); // return 2
solution.getRandom(); // return 3
// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.
Constraints:
• The number of nodes in the linked list will be in the range
[1, 10^4].•
-10^4 <= Node.val <= 10^4• At most
10^4 calls will be made to getRandom.Follow up:
• What if the linked list is extremely large and its length is unknown to you?
• Could you solve this efficiently without using extra space?
2023-03-11
109. Convert Sorted List to Binary Search Tree
Topic: Linked List, Divide and Conquer, Tree, Binary Search Tree, Binary Tree
Difficulty: Medium
Problem:
Given the
Example 1:
Image: https://assets.leetcode.com/uploads/2020/08/17/linked.jpg
Example 2:
Constraints:
• The number of nodes in
•
109. Convert Sorted List to Binary Search Tree
Topic: Linked List, Divide and Conquer, Tree, Binary Search Tree, Binary Tree
Difficulty: Medium
Problem:
Given the
head of a singly linked list where elements are sorted in ascending order, convert it to a height-balanced binary search tree.Example 1:
Image: https://assets.leetcode.com/uploads/2020/08/17/linked.jpg
Input: head = [-10,-3,0,5,9]
Output: [0,-3,9,-10,null,5]
Explanation: One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST.
Example 2:
Input: head = []
Output: []
Constraints:
• The number of nodes in
head is in the range [0, 2 * 10^4].•
-10^5 <= Node.val <= 10^52023-03-12
23. Merge k Sorted Lists
Topic: Linked List, Divide and Conquer, Heap (Priority Queue), Merge Sort
Difficulty: Hard
Problem:
You are given an array of
Merge all the linked-lists into one sorted linked-list and return it.
Example 1:
Example 2:
Example 3:
Constraints:
•
•
•
•
•
• The sum of
23. Merge k Sorted Lists
Topic: Linked List, Divide and Conquer, Heap (Priority Queue), Merge Sort
Difficulty: Hard
Problem:
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.
Example 1:
Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Explanation: The linked-lists are:
[
1->4->5,
1->3->4,
2->6
]
merging them into one sorted list:
1->1->2->3->4->4->5->6
Example 2:
Input: lists = []
Output: []
Example 3:
Input: lists = [[]]
Output: []
Constraints:
•
k == lists.length•
0 <= k <= 10^4•
0 <= lists[i].length <= 500•
-10^4 <= lists[i][j] <= 10^4•
lists[i] is sorted in ascending order.• The sum of
lists[i].length will not exceed 10^4.2023-03-13
101. Symmetric Tree
Topic: Tree, Depth-First Search, Breadth-First Search, Binary Tree
Difficulty: Easy
Problem:
Given the
Example 1:
Image: https://assets.leetcode.com/uploads/2021/02/19/symtree1.jpg
Example 2:
Image: https://assets.leetcode.com/uploads/2021/02/19/symtree2.jpg
Constraints:
• The number of nodes in the tree is in the range
•
Follow up: Could you solve it both recursively and iteratively?
101. Symmetric Tree
Topic: Tree, Depth-First Search, Breadth-First Search, Binary Tree
Difficulty: Easy
Problem:
Given the
root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).Example 1:
Image: https://assets.leetcode.com/uploads/2021/02/19/symtree1.jpg
Input: root = [1,2,2,3,4,4,3]
Output: true
Example 2:
Image: https://assets.leetcode.com/uploads/2021/02/19/symtree2.jpg
Input: root = [1,2,2,null,3,null,3]
Output: false
Constraints:
• The number of nodes in the tree is in the range
[1, 1000].•
-100 <= Node.val <= 100Follow up: Could you solve it both recursively and iteratively?
2023-03-14
129. Sum Root to Leaf Numbers
Topic: Tree, Depth-First Search, Binary Tree
Difficulty: Medium
Problem:
You are given the
Each root-to-leaf path in the tree represents a number.
• For example, the root-to-leaf path
Return the total sum of all root-to-leaf numbers. Test cases are generated so that the answer will fit in a 32-bit integer.
A leaf node is a node with no children.
Example 1:
Image: https://assets.leetcode.com/uploads/2021/02/19/num1tree.jpg
Example 2:
Image: https://assets.leetcode.com/uploads/2021/02/19/num2tree.jpg
Constraints:
• The number of nodes in the tree is in the range
•
• The depth of the tree will not exceed
129. Sum Root to Leaf Numbers
Topic: Tree, Depth-First Search, Binary Tree
Difficulty: Medium
Problem:
You are given the
root of a binary tree containing digits from 0 to 9 only.Each root-to-leaf path in the tree represents a number.
• For example, the root-to-leaf path
1 -> 2 -> 3 represents the number 123.Return the total sum of all root-to-leaf numbers. Test cases are generated so that the answer will fit in a 32-bit integer.
A leaf node is a node with no children.
Example 1:
Image: https://assets.leetcode.com/uploads/2021/02/19/num1tree.jpg
Input: root = [1,2,3]
Output: 25
Explanation:
The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.
Therefore, sum = 12 + 13 = 25.
Example 2:
Image: https://assets.leetcode.com/uploads/2021/02/19/num2tree.jpg
Input: root = [4,9,0,5,1]
Output: 1026
Explanation:
The root-to-leaf path 4->9->5 represents the number 495.
The root-to-leaf path 4->9->1 represents the number 491.
The root-to-leaf path 4->0 represents the number 40.
Therefore, sum = 495 + 491 + 40 = 1026.
Constraints:
• The number of nodes in the tree is in the range
[1, 1000].•
0 <= Node.val <= 9• The depth of the tree will not exceed
10.