2023-06-28
1514. Path with Maximum Probability
Topic: Array, Graph, Heap (Priority Queue), Shortest Path
Difficulty: Medium
Problem:
You are given an undirected weighted graph of
Given two nodes
If there is no path from
Example 1:
Image: https://assets.leetcode.com/uploads/2019/09/20/1558_ex1.png
Example 2:
Image: https://assets.leetcode.com/uploads/2019/09/20/1558_ex2.png
Example 3:
Image: https://assets.leetcode.com/uploads/2019/09/20/1558_ex3.png
Constraints:
•
•
•
•
•
•
•
• There is at most one edge between every two nodes.
1514. Path with Maximum Probability
Topic: Array, Graph, Heap (Priority Queue), Shortest Path
Difficulty: Medium
Problem:
You are given an undirected weighted graph of
n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i].Given two nodes
start and end, find the path with the maximum probability of success to go from start to end and return its success probability.If there is no path from
start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.Example 1:
Image: https://assets.leetcode.com/uploads/2019/09/20/1558_ex1.png
Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2
Output: 0.25000
Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25.
Example 2:
Image: https://assets.leetcode.com/uploads/2019/09/20/1558_ex2.png
Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2
Output: 0.30000
Example 3:
Image: https://assets.leetcode.com/uploads/2019/09/20/1558_ex3.png
Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2
Output: 0.00000
Explanation: There is no path between 0 and 2.
Constraints:
•
2 <= n <= 10^4•
0 <= start, end < n•
start != end•
0 <= a, b < n•
a != b•
0 <= succProb.length == edges.length <= 2*10^4•
0 <= succProb[i] <= 1• There is at most one edge between every two nodes.
2023-06-29
864. Shortest Path to Get All Keys
Topic: Array, Bit Manipulation, Breadth-First Search, Matrix
Difficulty: Hard
Problem:
You are given an
•
•
•
• Lowercase letters represent keys.
• Uppercase letters represent locks.
You start at the starting point and one move consists of walking one space in one of the four cardinal directions. You cannot walk outside the grid, or walk into a wall.
If you walk over a key, you can pick it up and you cannot walk over a lock unless you have its corresponding key.
For some
Return the lowest number of moves to acquire all keys. If it is impossible, return
Example 1:
Image: https://assets.leetcode.com/uploads/2021/07/23/lc-keys2.jpg
Example 2:
Image: https://assets.leetcode.com/uploads/2021/07/23/lc-key2.jpg
Example 3:
Image: https://assets.leetcode.com/uploads/2021/07/23/lc-keys3.jpg
Constraints:
•
•
•
•
• The number of keys in the grid is in the range
• Each key in the grid is unique.
• Each key in the grid has a matching lock.
864. Shortest Path to Get All Keys
Topic: Array, Bit Manipulation, Breadth-First Search, Matrix
Difficulty: Hard
Problem:
You are given an
m x n grid grid where:•
'.' is an empty cell.•
'#' is a wall.•
'@' is the starting point.• Lowercase letters represent keys.
• Uppercase letters represent locks.
You start at the starting point and one move consists of walking one space in one of the four cardinal directions. You cannot walk outside the grid, or walk into a wall.
If you walk over a key, you can pick it up and you cannot walk over a lock unless you have its corresponding key.
For some
1 <= k <= 6, there is exactly one lowercase and one uppercase letter of the first k letters of the English alphabet in the grid. This means that there is exactly one key for each lock, and one lock for each key; and also that the letters used to represent the keys and locks were chosen in the same order as the English alphabet.Return the lowest number of moves to acquire all keys. If it is impossible, return
-1.Example 1:
Image: https://assets.leetcode.com/uploads/2021/07/23/lc-keys2.jpg
Input: grid = ["@.a..","###.#","b.A.B"]
Output: 8
Explanation: Note that the goal is to obtain all the keys not to open all the locks.
Example 2:
Image: https://assets.leetcode.com/uploads/2021/07/23/lc-key2.jpg
Input: grid = ["@..aA","..B#.","....b"]
Output: 6
Example 3:
Image: https://assets.leetcode.com/uploads/2021/07/23/lc-keys3.jpg
Input: grid = ["@Aa"]
Output: -1
Constraints:
•
m == grid.length•
n == grid[i].length•
1 <= m, n <= 30•
grid[i][j] is either an English letter, '.', '#', or '@'.• The number of keys in the grid is in the range
[1, 6].• Each key in the grid is unique.
• Each key in the grid has a matching lock.
2023-06-30
1970. Last Day Where You Can Still Cross
Topic: Array, Binary Search, Depth-First Search, Breadth-First Search, Union Find, Matrix
Difficulty: Hard
Problem:
There is a 1-based binary matrix where
Initially on day
You want to find the last day that it is possible to walk from the top to the bottom by only walking on land cells. You can start from any cell in the top row and end at any cell in the bottom row. You can only travel in the four cardinal directions (left, right, up, and down).
Return the last day where it is possible to walk from the top to the bottom by only walking on land cells.
Example 1:
Image: https://assets.leetcode.com/uploads/2021/07/27/1.png
Example 2:
Image: https://assets.leetcode.com/uploads/2021/07/27/2.png
Example 3:
Image: https://assets.leetcode.com/uploads/2021/07/27/3.png
Constraints:
•
•
•
•
•
• All the values of
1970. Last Day Where You Can Still Cross
Topic: Array, Binary Search, Depth-First Search, Breadth-First Search, Union Find, Matrix
Difficulty: Hard
Problem:
There is a 1-based binary matrix where
0 represents land and 1 represents water. You are given integers row and col representing the number of rows and columns in the matrix, respectively.Initially on day
0, the entire matrix is land. However, each day a new cell becomes flooded with water. You are given a 1-based 2D array cells, where cells[i] = [r_i, c_i] represents that on the i^th day, the cell on the r_i^th row and c_i^th column (1-based coordinates) will be covered with water (i.e., changed to 1).You want to find the last day that it is possible to walk from the top to the bottom by only walking on land cells. You can start from any cell in the top row and end at any cell in the bottom row. You can only travel in the four cardinal directions (left, right, up, and down).
Return the last day where it is possible to walk from the top to the bottom by only walking on land cells.
Example 1:
Image: https://assets.leetcode.com/uploads/2021/07/27/1.png
Input: row = 2, col = 2, cells = [[1,1],[2,1],[1,2],[2,2]]
Output: 2
Explanation: The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 2.
Example 2:
Image: https://assets.leetcode.com/uploads/2021/07/27/2.png
Input: row = 2, col = 2, cells = [[1,1],[1,2],[2,1],[2,2]]
Output: 1
Explanation: The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 1.
Example 3:
Image: https://assets.leetcode.com/uploads/2021/07/27/3.png
Input: row = 3, col = 3, cells = [[1,2],[2,1],[3,3],[2,2],[1,1],[1,3],[2,3],[3,2],[3,1]]
Output: 3
Explanation: The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 3.
Constraints:
•
2 <= row, col <= 2 * 10^4•
4 <= row * col <= 2 * 10^4•
cells.length == row * col•
1 <= r_i <= row•
1 <= c_i <= col• All the values of
cells are unique.2023-07-01
2305. Fair Distribution of Cookies
Topic: Array, Dynamic Programming, Backtracking, Bit Manipulation, Bitmask
Difficulty: Medium
Problem:
You are given an integer array
The unfairness of a distribution is defined as the maximum total cookies obtained by a single child in the distribution.
Return the minimum unfairness of all distributions.
Example 1:
Example 2:
Constraints:
•
•
•
2305. Fair Distribution of Cookies
Topic: Array, Dynamic Programming, Backtracking, Bit Manipulation, Bitmask
Difficulty: Medium
Problem:
You are given an integer array
cookies, where cookies[i] denotes the number of cookies in the i^th bag. You are also given an integer k that denotes the number of children to distribute all the bags of cookies to. All the cookies in the same bag must go to the same child and cannot be split up.The unfairness of a distribution is defined as the maximum total cookies obtained by a single child in the distribution.
Return the minimum unfairness of all distributions.
Example 1:
Input: cookies = [8,15,10,20,8], k = 2
Output: 31
Explanation: One optimal distribution is [8,15,8] and [10,20]
- The 1^st child receives [8,15,8] which has a total of 8 + 15 + 8 = 31 cookies.
- The 2^nd child receives [10,20] which has a total of 10 + 20 = 30 cookies.
The unfairness of the distribution is max(31,30) = 31.
It can be shown that there is no distribution with an unfairness less than 31.
Example 2:
Input: cookies = [6,1,3,2,2,4,1,2], k = 3
Output: 7
Explanation: One optimal distribution is [6,1], [3,2,2], and [4,1,2]
- The 1^st child receives [6,1] which has a total of 6 + 1 = 7 cookies.
- The 2^nd child receives [3,2,2] which has a total of 3 + 2 + 2 = 7 cookies.
- The 3^rd child receives [4,1,2] which has a total of 4 + 1 + 2 = 7 cookies.
The unfairness of the distribution is max(7,7,7) = 7.
It can be shown that there is no distribution with an unfairness less than 7.
Constraints:
•
2 <= cookies.length <= 8•
1 <= cookies[i] <= 10^5•
2 <= k <= cookies.length2023-07-02
1601. Maximum Number of Achievable Transfer Requests
Topic: Array, Backtracking, Bit Manipulation, Enumeration
Difficulty: Hard
Problem:
We have
You are given an array
All buildings are full, so a list of requests is achievable only if for each building, the net change in employee transfers is zero. This means the number of employees leaving is equal to the number of employees moving in. For example if
Return the maximum number of achievable requests.
Example 1:
Image: https://assets.leetcode.com/uploads/2020/09/10/move1.jpg
Example 2:
Image: https://assets.leetcode.com/uploads/2020/09/10/move2.jpg
Example 3:
Constraints:
•
•
•
•
1601. Maximum Number of Achievable Transfer Requests
Topic: Array, Backtracking, Bit Manipulation, Enumeration
Difficulty: Hard
Problem:
We have
n buildings numbered from 0 to n - 1. Each building has a number of employees. It's transfer season, and some employees want to change the building they reside in.You are given an array
requests where requests[i] = [from_i, to_i] represents an employee's request to transfer from building from_i to building to_i.All buildings are full, so a list of requests is achievable only if for each building, the net change in employee transfers is zero. This means the number of employees leaving is equal to the number of employees moving in. For example if
n = 3 and two employees are leaving building 0, one is leaving building 1, and one is leaving building 2, there should be two employees moving to building 0, one employee moving to building 1, and one employee moving to building 2.Return the maximum number of achievable requests.
Example 1:
Image: https://assets.leetcode.com/uploads/2020/09/10/move1.jpg
Input: n = 5, requests = [[0,1],[1,0],[0,1],[1,2],[2,0],[3,4]]
Output: 5
Explantion: Let's see the requests:
From building 0 we have employees x and y and both want to move to building 1.
From building 1 we have employees a and b and they want to move to buildings 2 and 0 respectively.
From building 2 we have employee z and they want to move to building 0.
From building 3 we have employee c and they want to move to building 4.
From building 4 we don't have any requests.
We can achieve the requests of users x and b by swapping their places.
We can achieve the requests of users y, a and z by swapping the places in the 3 buildings.
Example 2:
Image: https://assets.leetcode.com/uploads/2020/09/10/move2.jpg
Input: n = 3, requests = [[0,0],[1,2],[2,1]]
Output: 3
Explantion: Let's see the requests:
From building 0 we have employee x and they want to stay in the same building 0.
From building 1 we have employee y and they want to move to building 2.
From building 2 we have employee z and they want to move to building 1.
We can achieve all the requests.
Example 3:
Input: n = 4, requests = [[0,3],[3,1],[1,2],[2,0]]
Output: 4
Constraints:
•
1 <= n <= 20•
1 <= requests.length <= 16•
requests[i].length == 2•
0 <= from_i, to_i < n2023-07-03
859. Buddy Strings
Topic: Hash Table, String
Difficulty: Easy
Problem:
Given two strings
Swapping letters is defined as taking two indices
• For example, swapping at indices
Example 1:
Example 2:
Example 3:
Constraints:
•
•
859. Buddy Strings
Topic: Hash Table, String
Difficulty: Easy
Problem:
Given two strings
s and goal, return true if you can swap two letters in s so the result is equal to goal, otherwise, return false.Swapping letters is defined as taking two indices
i and j (0-indexed) such that i != j and swapping the characters at s[i] and s[j].• For example, swapping at indices
0 and 2 in "abcd" results in "cbad".Example 1:
Input: s = "ab", goal = "ba"
Output: true
Explanation: You can swap s[0] = 'a' and s[1] = 'b' to get "ba", which is equal to goal.
Example 2:
Input: s = "ab", goal = "ab"
Output: false
Explanation: The only letters you can swap are s[0] = 'a' and s[1] = 'b', which results in "ba" != goal.
Example 3:
Input: s = "aa", goal = "aa"
Output: true
Explanation: You can swap s[0] = 'a' and s[1] = 'a' to get "aa", which is equal to goal.
Constraints:
•
1 <= s.length, goal.length <= 2 * 10^4•
s and goal consist of lowercase letters.2023-07-04
137. Single Number II
Topic: Array, Bit Manipulation
Difficulty: Medium
Problem:
Given an integer array
You must implement a solution with a linear runtime complexity and use only constant extra space.
Example 1:
Example 2:
Constraints:
•
•
• Each element in
137. Single Number II
Topic: Array, Bit Manipulation
Difficulty: Medium
Problem:
Given an integer array
nums where every element appears three times except for one, which appears exactly once. Find the single element and return it.You must implement a solution with a linear runtime complexity and use only constant extra space.
Example 1:
Input: nums = [2,2,3,2]
Output: 3
Example 2:
Input: nums = [0,1,0,1,0,1,99]
Output: 99
Constraints:
•
1 <= nums.length <= 3 * 10^4•
-2^31 <= nums[i] <= 2^31 - 1• Each element in
nums appears exactly three times except for one element which appears once.2023-07-05
1493. Longest Subarray of 1's After Deleting One Element
Topic: Array, Dynamic Programming, Sliding Window
Difficulty: Medium
Problem:
Given a binary array
Return the size of the longest non-empty subarray containing only
Example 1:
Example 2:
Example 3:
Constraints:
•
•
1493. Longest Subarray of 1's After Deleting One Element
Topic: Array, Dynamic Programming, Sliding Window
Difficulty: Medium
Problem:
Given a binary array
nums, you should delete one element from it.Return the size of the longest non-empty subarray containing only
1's in the resulting array. Return 0 if there is no such subarray.Example 1:
Input: nums = [1,1,0,1]
Output: 3
Explanation: After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1's.
Example 2:
Input: nums = [0,1,1,1,0,1,1,0,1]
Output: 5
Explanation: After deleting the number in position 4, [0,1,1,1,1,1,0,1] longest subarray with value of 1's is [1,1,1,1,1].
Example 3:
Input: nums = [1,1,1]
Output: 2
Explanation: You must delete one element.
Constraints:
•
1 <= nums.length <= 10^5•
nums[i] is either 0 or 1.2023-07-06
209. Minimum Size Subarray Sum
Topic: Array, Binary Search, Sliding Window, Prefix Sum
Difficulty: Medium
Problem:
Given an array of positive integers
Example 1:
Example 2:
Example 3:
Constraints:
•
•
•
Follow up: If you have figured out the
209. Minimum Size Subarray Sum
Topic: Array, Binary Search, Sliding Window, Prefix Sum
Difficulty: Medium
Problem:
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 instead.Example 1:
Input: target = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: The subarray [4,3] has the minimal length under the problem constraint.
Example 2:
Input: target = 4, nums = [1,4,4]
Output: 1
Example 3:
Input: target = 11, nums = [1,1,1,1,1,1,1,1]
Output: 0
Constraints:
•
1 <= target <= 10^9•
1 <= nums.length <= 10^5•
1 <= nums[i] <= 10^4Follow up: If you have figured out the
O(n) solution, try coding another solution of which the time complexity is O(n log(n)).2023-07-07
2024. Maximize the Confusion of an Exam
Topic: String, Binary Search, Sliding Window, Prefix Sum
Difficulty: Medium
Problem:
A teacher is writing a test with
You are given a string
• Change the answer key for any question to
Return the maximum number of consecutive
Example 1:
Example 2:
Example 3:
Constraints:
•
•
•
•
2024. Maximize the Confusion of an Exam
Topic: String, Binary Search, Sliding Window, Prefix Sum
Difficulty: Medium
Problem:
A teacher is writing a test with
n true/false questions, with 'T' denoting true and 'F' denoting false. He wants to confuse the students by maximizing the number of consecutive questions with the same answer (multiple trues or multiple falses in a row).You are given a string
answerKey, where answerKey[i] is the original answer to the i^th question. In addition, you are given an integer k, the maximum number of times you may perform the following operation:• Change the answer key for any question to
'T' or 'F' (i.e., set answerKey[i] to 'T' or 'F').Return the maximum number of consecutive
'T's or 'F's in the answer key after performing the operation at most k times.Example 1:
Input: answerKey = "TTFF", k = 2
Output: 4
Explanation: We can replace both the 'F's with 'T's to make answerKey = "TTTT".
There are four consecutive 'T's.
Example 2:
Input: answerKey = "TFFT", k = 1
Output: 3
Explanation: We can replace the first 'T' with an 'F' to make answerKey = "FFFT".
Alternatively, we can replace the second 'T' with an 'F' to make answerKey = "TFFF".
In both cases, there are three consecutive 'F's.
Example 3:
Input: answerKey = "TTFTTFTT", k = 1
Output: 5
Explanation: We can replace the first 'F' to make answerKey = "TTTTTFTT"
Alternatively, we can replace the second 'F' to make answerKey = "TTFTTTTT".
In both cases, there are five consecutive 'T's.
Constraints:
•
n == answerKey.length•
1 <= n <= 5 * 10^4•
answerKey[i] is either 'T' or 'F'•
1 <= k <= n2023-07-08
2551. Put Marbles in Bags
Topic: Array, Greedy, Sorting, Heap (Priority Queue)
Difficulty: Hard
Problem:
You have
Divide the marbles into the
• No bag is empty.
• If the
• If a bag consists of all the marbles with an index from
The score after distributing the marbles is the sum of the costs of all the
Return the difference between the maximum and minimum scores among marble distributions.
Example 1:
Example 2:
Constraints:
•
•
2551. Put Marbles in Bags
Topic: Array, Greedy, Sorting, Heap (Priority Queue)
Difficulty: Hard
Problem:
You have
k bags. You are given a 0-indexed integer array weights where weights[i] is the weight of the i^th marble. You are also given the integer k.Divide the marbles into the
k bags according to the following rules:• No bag is empty.
• If the
i^th marble and j^th marble are in a bag, then all marbles with an index between the i^th and j^th indices should also be in that same bag.• If a bag consists of all the marbles with an index from
i to j inclusively, then the cost of the bag is weights[i] + weights[j].The score after distributing the marbles is the sum of the costs of all the
k bags.Return the difference between the maximum and minimum scores among marble distributions.
Example 1:
Input: weights = [1,3,5,1], k = 2
Output: 4
Explanation:
The distribution [1],[3,5,1] results in the minimal score of (1+1) + (3+1) = 6.
The distribution [1,3],[5,1], results in the maximal score of (1+3) + (5+1) = 10.
Thus, we return their difference 10 - 6 = 4.
Example 2:
Input: weights = [1, 3], k = 2
Output: 0
Explanation: The only distribution possible is [1],[3].
Since both the maximal and minimal score are the same, we return 0.
Constraints:
•
1 <= k <= weights.length <= 10^5•
1 <= weights[i] <= 10^92023-07-09
2272. Substring With Largest Variance
Topic: Array, Dynamic Programming
Difficulty: Hard
Problem:
The variance of a string is defined as the largest difference between the number of occurrences of any
Given a string
A substring is a contiguous sequence of characters within a string.
Example 1:
Example 2:
Constraints:
•
•
2272. Substring With Largest Variance
Topic: Array, Dynamic Programming
Difficulty: Hard
Problem:
The variance of a string is defined as the largest difference between the number of occurrences of any
2 characters present in the string. Note the two characters may or may not be the same.Given a string
s consisting of lowercase English letters only, return the largest variance possible among all substrings of s.A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "aababbb"
Output: 3
Explanation:
All possible variances along with their respective substrings are listed below:
- Variance 0 for substrings "a", "aa", "ab", "abab", "aababb", "ba", "b", "bb", and "bbb".
- Variance 1 for substrings "aab", "aba", "abb", "aabab", "ababb", "aababbb", and "bab".
- Variance 2 for substrings "aaba", "ababbb", "abbb", and "babb".
- Variance 3 for substring "babbb".
Since the largest possible variance is 3, we return it.
Example 2:
Input: s = "abcde"
Output: 0
Explanation:
No letter occurs more than once in s, so the variance of every substring is 0.
Constraints:
•
1 <= s.length <= 10^4•
s consists of lowercase English letters.2023-07-10
111. Minimum Depth of Binary Tree
Topic: Tree, Depth-First Search, Breadth-First Search, Binary Tree
Difficulty: Easy
Problem:
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.
Note: A leaf is a node with no children.
Example 1:
Image: https://assets.leetcode.com/uploads/2020/10/12/ex_depth.jpg
Example 2:
Constraints:
• The number of nodes in the tree is in the range
•
111. Minimum Depth of Binary Tree
Topic: Tree, Depth-First Search, Breadth-First Search, Binary Tree
Difficulty: Easy
Problem:
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.
Note: A leaf is a node with no children.
Example 1:
Image: https://assets.leetcode.com/uploads/2020/10/12/ex_depth.jpg
Input: root = [3,9,20,null,null,15,7]
Output: 2
Example 2:
Input: root = [2,null,3,null,4,null,5,null,6]
Output: 5
Constraints:
• The number of nodes in the tree is in the range
[0, 10^5].•
-1000 <= Node.val <= 10002023-07-11
863. All Nodes Distance K in Binary Tree
Topic: Tree, Depth-First Search, Breadth-First Search, Binary Tree
Difficulty: Medium
Problem:
Given the
You can return the answer in any order.
Example 1:
Image: https://s3-lc-upload.s3.amazonaws.com/uploads/2018/06/28/sketch0.png
Example 2:
Constraints:
• The number of nodes in the tree is in the range
•
• All the values
•
•
863. All Nodes Distance K in Binary Tree
Topic: Tree, Depth-First Search, Breadth-First Search, Binary Tree
Difficulty: Medium
Problem:
Given the
root of a binary tree, the value of a target node target, and an integer k, return an array of the values of all nodes that have a distance k from the target node.You can return the answer in any order.
Example 1:
Image: https://s3-lc-upload.s3.amazonaws.com/uploads/2018/06/28/sketch0.png
Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, k = 2
Output: [7,4,1]
Explanation: The nodes that are a distance 2 from the target node (with value 5) have values 7, 4, and 1.
Example 2:
Input: root = [1], target = 1, k = 3
Output: []
Constraints:
• The number of nodes in the tree is in the range
[1, 500].•
0 <= Node.val <= 500• All the values
Node.val are unique.•
target is the value of one of the nodes in the tree.•
0 <= k <= 10002023-07-12
802. Find Eventual Safe States
Topic: Depth-First Search, Breadth-First Search, Graph, Topological Sort
Difficulty: Medium
Problem:
There is a directed graph of
A node is a terminal node if there are no outgoing edges. A node is a safe node if every possible path starting from that node leads to a terminal node (or another safe node).
Return an array containing all the safe nodes of the graph. The answer should be sorted in ascending order.
Example 1:
Image: https://s3-lc-upload.s3.amazonaws.com/uploads/2018/03/17/picture1.png
Example 2:
Constraints:
•
•
•
•
•
• The graph may contain self-loops.
• The number of edges in the graph will be in the range
802. Find Eventual Safe States
Topic: Depth-First Search, Breadth-First Search, Graph, Topological Sort
Difficulty: Medium
Problem:
There is a directed graph of
n nodes with each node labeled from 0 to n - 1. The graph is represented by a 0-indexed 2D integer array graph where graph[i] is an integer array of nodes adjacent to node i, meaning there is an edge from node i to each node in graph[i].A node is a terminal node if there are no outgoing edges. A node is a safe node if every possible path starting from that node leads to a terminal node (or another safe node).
Return an array containing all the safe nodes of the graph. The answer should be sorted in ascending order.
Example 1:
Image: https://s3-lc-upload.s3.amazonaws.com/uploads/2018/03/17/picture1.png
Input: graph = [[1,2],[2,3],[5],[0],[5],[],[]]
Output: [2,4,5,6]
Explanation: The given graph is shown above.
Nodes 5 and 6 are terminal nodes as there are no outgoing edges from either of them.
Every path starting at nodes 2, 4, 5, and 6 all lead to either node 5 or 6.
Example 2:
Input: graph = [[1,2,3,4],[1,2],[3,4],[0,4],[]]
Output: [4]
Explanation:
Only node 4 is a terminal node, and every path starting at node 4 leads to node 4.
Constraints:
•
n == graph.length•
1 <= n <= 10^4•
0 <= graph[i].length <= n•
0 <= graph[i][j] <= n - 1•
graph[i] is sorted in a strictly increasing order.• The graph may contain self-loops.
• The number of edges in the graph will be in the range
[1, 4 * 10^4].2023-07-13
207. Course Schedule
Topic: Depth-First Search, Breadth-First Search, Graph, Topological Sort
Difficulty: Medium
Problem:
There are a total of
• For example, the pair
Return
Example 1:
Example 2:
Constraints:
•
•
•
•
• All the pairs prerequisitesi are unique.
207. Course Schedule
Topic: Depth-First Search, Breadth-First Search, Graph, Topological Sort
Difficulty: Medium
Problem:
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] = [a_i, b_i] indicates that you must take course b_i first if you want to take course a_i.• For example, the pair
[0, 1], indicates that to take course 0 you have to first take course 1.Return
true if you can finish all courses. Otherwise, return false.Example 1:
Input: numCourses = 2, prerequisites = [[1,0]]
Output: true
Explanation: There are a total of 2 courses to take.
To take course 1 you should have finished course 0. So it is possible.
Example 2:
Input: numCourses = 2, prerequisites = [[1,0],[0,1]]
Output: false
Explanation: There are a total of 2 courses to take.
To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.
Constraints:
•
1 <= numCourses <= 2000•
0 <= prerequisites.length <= 5000•
prerequisites[i].length == 2•
0 <= a_i, b_i < numCourses• All the pairs prerequisitesi are unique.
2023-07-14
1218. Longest Arithmetic Subsequence of Given Difference
Topic: Array, Hash Table, Dynamic Programming
Difficulty: Medium
Problem:
Given an integer array
A subsequence is a sequence that can be derived from
Example 1:
Example 2:
Example 3:
Constraints:
•
•
1218. Longest Arithmetic Subsequence of Given Difference
Topic: Array, Hash Table, Dynamic Programming
Difficulty: Medium
Problem:
Given an integer array
arr and an integer difference, return the length of the longest subsequence in arr which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals difference.A subsequence is a sequence that can be derived from
arr by deleting some or no elements without changing the order of the remaining elements.Example 1:
Input: arr = [1,2,3,4], difference = 1
Output: 4
Explanation: The longest arithmetic subsequence is [1,2,3,4].
Example 2:
Input: arr = [1,3,5,7], difference = 1
Output: 1
Explanation: The longest arithmetic subsequence is any single element.
Example 3:
Input: arr = [1,5,7,8,5,3,4,2,1], difference = -2
Output: 4
Explanation: The longest arithmetic subsequence is [7,5,3,1].
Constraints:
•
1 <= arr.length <= 10^5•
-10^4 <= arr[i], difference <= 10^42023-07-15
1751. Maximum Number of Events That Can Be Attended II
Topic: Array, Binary Search, Dynamic Programming, Sorting
Difficulty: Hard
Problem:
You are given an array of
You can only attend one event at a time. If you choose to attend an event, you must attend the entire event. Note that the end day is inclusive: that is, you cannot attend two events where one of them starts and the other ends on the same day.
Return the maximum sum of values that you can receive by attending events.
Example 1:
Image: https://assets.leetcode.com/uploads/2021/01/10/screenshot-2021-01-11-at-60048-pm.png
Example 2:
Image: https://assets.leetcode.com/uploads/2021/01/10/screenshot-2021-01-11-at-60150-pm.png
Example 3:
Image: https://assets.leetcode.com/uploads/2021/01/10/screenshot-2021-01-11-at-60703-pm.png
Constraints:
•
•
•
•
1751. Maximum Number of Events That Can Be Attended II
Topic: Array, Binary Search, Dynamic Programming, Sorting
Difficulty: Hard
Problem:
You are given an array of
events where events[i] = [startDay_i, endDay_i, value_i]. The i^th event starts at startDay_i and ends at endDay_i, and if you attend this event, you will receive a value of value_i. You are also given an integer k which represents the maximum number of events you can attend.You can only attend one event at a time. If you choose to attend an event, you must attend the entire event. Note that the end day is inclusive: that is, you cannot attend two events where one of them starts and the other ends on the same day.
Return the maximum sum of values that you can receive by attending events.
Example 1:
Image: https://assets.leetcode.com/uploads/2021/01/10/screenshot-2021-01-11-at-60048-pm.png
Input: events = [[1,2,4],[3,4,3],[2,3,1]], k = 2
Output: 7
Explanation: Choose the green events, 0 and 1 (0-indexed) for a total value of 4 + 3 = 7.
Example 2:
Image: https://assets.leetcode.com/uploads/2021/01/10/screenshot-2021-01-11-at-60150-pm.png
Input: events = [[1,2,4],[3,4,3],[2,3,10]], k = 2
Output: 10
Explanation: Choose event 2 for a total value of 10.
Notice that you cannot attend any other event as they overlap, and that you do not have to attend k events.
Example 3:
Image: https://assets.leetcode.com/uploads/2021/01/10/screenshot-2021-01-11-at-60703-pm.png
Input: events = [[1,1,1],[2,2,2],[3,3,3],[4,4,4]], k = 3
Output: 9
Explanation: Although the events do not overlap, you can only attend 3 events. Pick the highest valued three.
Constraints:
•
1 <= k <= events.length•
1 <= k * events.length <= 10^6•
1 <= startDay_i <= endDay_i <= 10^9•
1 <= value_i <= 10^62023-07-16
1125. Smallest Sufficient Team
Topic: Array, Dynamic Programming, Bit Manipulation, Bitmask
Difficulty: Hard
Problem:
In a project, you have a list of required skills
Consider a sufficient team: a set of people such that for every required skill in
• For example,
Return any sufficient team of the smallest possible size, represented by the index of each person. You may return the answer in any order.
It is guaranteed an answer exists.
Example 1:
Example 2:
Constraints:
•
•
•
• All the strings of
•
•
•
•
• All the strings of
• Every skill in
• It is guaranteed a sufficient team exists.
1125. Smallest Sufficient Team
Topic: Array, Dynamic Programming, Bit Manipulation, Bitmask
Difficulty: Hard
Problem:
In a project, you have a list of required skills
req_skills, and a list of people. The i^th person people[i] contains a list of skills that the person has.Consider a sufficient team: a set of people such that for every required skill in
req_skills, there is at least one person in the team who has that skill. We can represent these teams by the index of each person.• For example,
team = [0, 1, 3] represents the people with skills people[0], people[1], and people[3].Return any sufficient team of the smallest possible size, represented by the index of each person. You may return the answer in any order.
It is guaranteed an answer exists.
Example 1:
Input: req_skills = ["java","nodejs","reactjs"], people = [["java"],["nodejs"],["nodejs","reactjs"]]
Output: [0,2]
Example 2:
Input: req_skills = ["algorithms","math","java","reactjs","csharp","aws"], people = [["algorithms","math","java"],["algorithms","math","reactjs"],["java","csharp","aws"],["reactjs","csharp"],["csharp","math"],["aws","java"]]
Output: [1,2]
Constraints:
•
1 <= req_skills.length <= 16•
1 <= req_skills[i].length <= 16•
req_skills[i] consists of lowercase English letters.• All the strings of
req_skills are unique.•
1 <= people.length <= 60•
0 <= people[i].length <= 16•
1 <= people[i][j].length <= 16•
people[i][j] consists of lowercase English letters.• All the strings of
people[i] are unique.• Every skill in
people[i] is a skill in req_skills.• It is guaranteed a sufficient team exists.
2023-07-17
445. Add Two Numbers II
Topic: Linked List, Math, Stack
Difficulty: Medium
Problem:
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example 1:
Image: https://assets.leetcode.com/uploads/2021/04/09/sumii-linked-list.jpg
Example 2:
Example 3:
Constraints:
• The number of nodes in each linked list is in the range
•
• It is guaranteed that the list represents a number that does not have leading zeros.
Follow up: Could you solve it without reversing the input lists?
445. Add Two Numbers II
Topic: Linked List, Math, Stack
Difficulty: Medium
Problem:
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example 1:
Image: https://assets.leetcode.com/uploads/2021/04/09/sumii-linked-list.jpg
Input: l1 = [7,2,4,3], l2 = [5,6,4]
Output: [7,8,0,7]
Example 2:
Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [8,0,7]
Example 3:
Input: l1 = [0], l2 = [0]
Output: [0]
Constraints:
• The number of nodes in each linked list is in the range
[1, 100].•
0 <= Node.val <= 9• It is guaranteed that the list represents a number that does not have leading zeros.
Follow up: Could you solve it without reversing the input lists?