2023-03-23
1319. Number of Operations to Make Network Connected
Topic: Depth-First Search, Breadth-First Search, Union Find, Graph
Difficulty: Medium
Problem:
There are
You are given an initial computer network
Return the minimum number of times you need to do this in order to make all the computers connected. If it is not possible, return
Example 1:
Image: https://assets.leetcode.com/uploads/2020/01/02/sample_1_1677.png
Example 2:
Image: https://assets.leetcode.com/uploads/2020/01/02/sample_2_1677.png
Example 3:
Constraints:
•
•
•
•
•
• There are no repeated connections.
• No two computers are connected by more than one cable.
1319. Number of Operations to Make Network Connected
Topic: Depth-First Search, Breadth-First Search, Union Find, Graph
Difficulty: Medium
Problem:
There are
n computers numbered from 0 to n - 1 connected by ethernet cables connections forming a network where connections[i] = [a_i, b_i] represents a connection between computers a_i and b_i. Any computer can reach any other computer directly or indirectly through the network.You are given an initial computer network
connections. You can extract certain cables between two directly connected computers, and place them between any pair of disconnected computers to make them directly connected.Return the minimum number of times you need to do this in order to make all the computers connected. If it is not possible, return
-1.Example 1:
Image: https://assets.leetcode.com/uploads/2020/01/02/sample_1_1677.png
Input: n = 4, connections = [[0,1],[0,2],[1,2]]
Output: 1
Explanation: Remove cable between computer 1 and 2 and place between computers 1 and 3.
Example 2:
Image: https://assets.leetcode.com/uploads/2020/01/02/sample_2_1677.png
Input: n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]]
Output: 2
Example 3:
Input: n = 6, connections = [[0,1],[0,2],[0,3],[1,2]]
Output: -1
Explanation: There are not enough cables.
Constraints:
•
1 <= n <= 10^5•
1 <= connections.length <= min(n * (n - 1) / 2, 10^5)•
connections[i].length == 2•
0 <= a_i, b_i < n•
a_i != b_i• There are no repeated connections.
• No two computers are connected by more than one cable.
2023-03-24
1466. Reorder Routes to Make All Paths Lead to the City Zero
Topic: Depth-First Search, Breadth-First Search, Graph
Difficulty: Medium
Problem:
There are
Roads are represented by
This year, there will be a big event in the capital (city
Your task consists of reorienting some roads such that each city can visit the city
It's guaranteed that each city can reach city
Example 1:
Image: https://assets.leetcode.com/uploads/2020/05/13/sample_1_1819.png
Example 2:
Image: https://assets.leetcode.com/uploads/2020/05/13/sample_2_1819.png
Example 3:
Constraints:
•
•
•
•
•
1466. Reorder Routes to Make All Paths Lead to the City Zero
Topic: Depth-First Search, Breadth-First Search, Graph
Difficulty: Medium
Problem:
There are
n cities numbered from 0 to n - 1 and n - 1 roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow.Roads are represented by
connections where connections[i] = [a_i, b_i] represents a road from city a_i to city b_i.This year, there will be a big event in the capital (city
0), and many people want to travel to this city.Your task consists of reorienting some roads such that each city can visit the city
0. Return the minimum number of edges changed.It's guaranteed that each city can reach city
0 after reorder.Example 1:
Image: https://assets.leetcode.com/uploads/2020/05/13/sample_1_1819.png
Input: n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]]
Output: 3
Explanation: Change the direction of edges show in red such that each node can reach the node 0 (capital).
Example 2:
Image: https://assets.leetcode.com/uploads/2020/05/13/sample_2_1819.png
Input: n = 5, connections = [[1,0],[1,2],[3,2],[3,4]]
Output: 2
Explanation: Change the direction of edges show in red such that each node can reach the node 0 (capital).
Example 3:
Input: n = 3, connections = [[1,0],[2,0]]
Output: 0
Constraints:
•
2 <= n <= 5 * 10^4•
connections.length == n - 1•
connections[i].length == 2•
0 <= a_i, b_i <= n - 1•
a_i != b_i2023-03-25
2316. Count Unreachable Pairs of Nodes in an Undirected Graph
Topic: Depth-First Search, Breadth-First Search, Union Find, Graph
Difficulty: Medium
Problem:
You are given an integer
Return the number of pairs of different nodes that are unreachable from each other.
Example 1:
Image: https://assets.leetcode.com/uploads/2022/05/05/tc-3.png
Example 2:
Image: https://assets.leetcode.com/uploads/2022/05/05/tc-2.png
Constraints:
•
•
•
•
•
• There are no repeated edges.
2316. Count Unreachable Pairs of Nodes in an Undirected Graph
Topic: Depth-First Search, Breadth-First Search, Union Find, Graph
Difficulty: Medium
Problem:
You are given an integer
n. There is an undirected graph with n nodes, numbered from 0 to n - 1. You are given a 2D integer array edges where edges[i] = [a_i, b_i] denotes that there exists an undirected edge connecting nodes a_i and b_i.Return the number of pairs of different nodes that are unreachable from each other.
Example 1:
Image: https://assets.leetcode.com/uploads/2022/05/05/tc-3.png
Input: n = 3, edges = [[0,1],[0,2],[1,2]]
Output: 0
Explanation: There are no pairs of nodes that are unreachable from each other. Therefore, we return 0.
Example 2:
Image: https://assets.leetcode.com/uploads/2022/05/05/tc-2.png
Input: n = 7, edges = [[0,2],[0,5],[2,4],[1,6],[5,4]]
Output: 14
Explanation: There are 14 pairs of nodes that are unreachable from each other:
[[0,1],[0,3],[0,6],[1,2],[1,3],[1,4],[1,5],[2,3],[2,6],[3,4],[3,5],[3,6],[4,6],[5,6]].
Therefore, we return 14.
Constraints:
•
1 <= n <= 10^5•
0 <= edges.length <= 2 * 10^5•
edges[i].length == 2•
0 <= a_i, b_i < n•
a_i != b_i• There are no repeated edges.
2023-03-26
2360. Longest Cycle in a Graph
Topic: Depth-First Search, Graph, Topological Sort
Difficulty: Hard
Problem:
You are given a directed graph of
The graph is represented with a given 0-indexed array
Return the length of the longest cycle in the graph. If no cycle exists, return
A cycle is a path that starts and ends at the same node.
Example 1:
Image: https://assets.leetcode.com/uploads/2022/06/08/graph4drawio-5.png
Example 2:
Image: https://assets.leetcode.com/uploads/2022/06/07/graph4drawio-1.png
Constraints:
•
•
•
•
2360. Longest Cycle in a Graph
Topic: Depth-First Search, Graph, Topological Sort
Difficulty: Hard
Problem:
You are given a directed graph of
n nodes numbered from 0 to n - 1, where each node has at most one outgoing edge.The graph is represented with a given 0-indexed array
edges of size n, indicating that there is a directed edge from node i to node edges[i]. If there is no outgoing edge from node i, then edges[i] == -1.Return the length of the longest cycle in the graph. If no cycle exists, return
-1.A cycle is a path that starts and ends at the same node.
Example 1:
Image: https://assets.leetcode.com/uploads/2022/06/08/graph4drawio-5.png
Input: edges = [3,3,4,2,3]
Output: 3
Explanation: The longest cycle in the graph is the cycle: 2 -> 4 -> 3 -> 2.
The length of this cycle is 3, so 3 is returned.
Example 2:
Image: https://assets.leetcode.com/uploads/2022/06/07/graph4drawio-1.png
Input: edges = [2,-1,3,1]
Output: -1
Explanation: There are no cycles in this graph.
Constraints:
•
n == edges.length•
2 <= n <= 10^5•
-1 <= edges[i] < n•
edges[i] != i2023-03-27
64. Minimum Path Sum
Topic: Array, Dynamic Programming, Matrix
Difficulty: Medium
Problem:
Given a
Note: You can only move either down or right at any point in time.
Example 1:
Image: https://assets.leetcode.com/uploads/2020/11/05/minpath.jpg
Example 2:
Constraints:
•
•
•
•
64. Minimum Path Sum
Topic: Array, Dynamic Programming, Matrix
Difficulty: Medium
Problem:
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.Note: You can only move either down or right at any point in time.
Example 1:
Image: https://assets.leetcode.com/uploads/2020/11/05/minpath.jpg
Input: grid = [[1,3,1],[1,5,1],[4,2,1]]
Output: 7
Explanation: Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.
Example 2:
Input: grid = [[1,2,3],[4,5,6]]
Output: 12
Constraints:
•
m == grid.length•
n == grid[i].length•
1 <= m, n <= 200•
0 <= grid[i][j] <= 1002023-03-28
983. Minimum Cost For Tickets
Topic: Array, Dynamic Programming
Difficulty: Medium
Problem:
You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array
Train tickets are sold in three different ways:
• a 1-day pass is sold for
• a 7-day pass is sold for
• a 30-day pass is sold for
The passes allow that many days of consecutive travel.
• For example, if we get a 7-day pass on day
Return the minimum number of dollars you need to travel every day in the given list of days.
Example 1:
Example 2:
Constraints:
•
•
•
•
•
983. Minimum Cost For Tickets
Topic: Array, Dynamic Programming
Difficulty: Medium
Problem:
You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array
days. Each day is an integer from 1 to 365.Train tickets are sold in three different ways:
• a 1-day pass is sold for
costs[0] dollars,• a 7-day pass is sold for
costs[1] dollars, and• a 30-day pass is sold for
costs[2] dollars.The passes allow that many days of consecutive travel.
• For example, if we get a 7-day pass on day
2, then we can travel for 7 days: 2, 3, 4, 5, 6, 7, and 8.Return the minimum number of dollars you need to travel every day in the given list of days.
Example 1:
Input: days = [1,4,6,7,8,20], costs = [2,7,15]
Output: 11
Explanation: For example, here is one way to buy passes that lets you travel your travel plan:
On day 1, you bought a 1-day pass for costs[0] = $2, which covered day 1.
On day 3, you bought a 7-day pass for costs[1] = $7, which covered days 3, 4, ..., 9.
On day 20, you bought a 1-day pass for costs[0] = $2, which covered day 20.
In total, you spent $11 and covered all the days of your travel.
Example 2:
Input: days = [1,2,3,4,5,6,7,8,9,10,30,31], costs = [2,7,15]
Output: 17
Explanation: For example, here is one way to buy passes that lets you travel your travel plan:
On day 1, you bought a 30-day pass for costs[2] = $15 which covered days 1, 2, ..., 30.
On day 31, you bought a 1-day pass for costs[0] = $2 which covered day 31.
In total, you spent $17 and covered all the days of your travel.
Constraints:
•
1 <= days.length <= 365•
1 <= days[i] <= 365•
days is in strictly increasing order.•
costs.length == 3•
1 <= costs[i] <= 10002023-03-29
1402. Reducing Dishes
Topic: Array, Dynamic Programming, Greedy, Sorting
Difficulty: Hard
Problem:
A chef has collected data on the
Like-time coefficient of a dish is defined as the time taken to cook that dish including previous dishes multiplied by its satisfaction level i.e.
Return the maximum sum of like-time coefficient that the chef can obtain after dishes preparation.
Dishes can be prepared in any order and the chef can discard some dishes to get this maximum value.
Example 1:
Example 2:
Example 3:
Constraints:
•
•
•
1402. Reducing Dishes
Topic: Array, Dynamic Programming, Greedy, Sorting
Difficulty: Hard
Problem:
A chef has collected data on the
satisfaction level of his n dishes. Chef can cook any dish in 1 unit of time.Like-time coefficient of a dish is defined as the time taken to cook that dish including previous dishes multiplied by its satisfaction level i.e.
time[i] * satisfaction[i].Return the maximum sum of like-time coefficient that the chef can obtain after dishes preparation.
Dishes can be prepared in any order and the chef can discard some dishes to get this maximum value.
Example 1:
Input: satisfaction = [-1,-8,0,5,-9]
Output: 14
Explanation: After Removing the second and last dish, the maximum total like-time coefficient will be equal to (-1*1 + 0*2 + 5*3 = 14).
Each dish is prepared in one unit of time.
Example 2:
Input: satisfaction = [4,3,2]
Output: 20
Explanation: Dishes can be prepared in any order, (2*1 + 3*2 + 4*3 = 20)
Example 3:
Input: satisfaction = [-1,-4,-5]
Output: 0
Explanation: People do not like the dishes. No dish is prepared.
Constraints:
•
n == satisfaction.length•
1 <= n <= 500•
-1000 <= satisfaction[i] <= 10002023-03-30
87. Scramble String
Topic: String, Dynamic Programming
Difficulty: Hard
Problem:
We can scramble a string s to get a string t using the following algorithm:
1. If the length of the string is 1, stop.
2. If the length of the string is > 1, do the following:
• Split the string into two non-empty substrings at a random index, i.e., if the string is
• Randomly decide to swap the two substrings or to keep them in the same order. i.e., after this step,
• Apply step 1 recursively on each of the two substrings
Given two strings
Example 1:
Example 2:
Example 3:
Constraints:
•
•
•
87. Scramble String
Topic: String, Dynamic Programming
Difficulty: Hard
Problem:
We can scramble a string s to get a string t using the following algorithm:
1. If the length of the string is 1, stop.
2. If the length of the string is > 1, do the following:
• Split the string into two non-empty substrings at a random index, i.e., if the string is
s, divide it to x and y where s = x + y.• Randomly decide to swap the two substrings or to keep them in the same order. i.e., after this step,
s may become s = x + y or s = y + x.• Apply step 1 recursively on each of the two substrings
x and y.Given two strings
s1 and s2 of the same length, return true if s2 is a scrambled string of s1, otherwise, return false.Example 1:
Input: s1 = "great", s2 = "rgeat"
Output: true
Explanation: One possible scenario applied on s1 is:
"great" --> "gr/eat" // divide at random index.
"gr/eat" --> "gr/eat" // random decision is not to swap the two substrings and keep them in order.
"gr/eat" --> "g/r / e/at" // apply the same algorithm recursively on both substrings. divide at random index each of them.
"g/r / e/at" --> "r/g / e/at" // random decision was to swap the first substring and to keep the second substring in the same order.
"r/g / e/at" --> "r/g / e/ a/t" // again apply the algorithm recursively, divide "at" to "a/t".
"r/g / e/ a/t" --> "r/g / e/ a/t" // random decision is to keep both substrings in the same order.
The algorithm stops now, and the result string is "rgeat" which is s2.
As one possible scenario led s1 to be scrambled to s2, we return true.
Example 2:
Input: s1 = "abcde", s2 = "caebd"
Output: false
Example 3:
Input: s1 = "a", s2 = "a"
Output: true
Constraints:
•
s1.length == s2.length•
1 <= s1.length <= 30•
s1 and s2 consist of lowercase English letters.2023-03-31
1444. Number of Ways of Cutting a Pizza
Topic: Array, Dynamic Programming, Memoization, Matrix
Difficulty: Hard
Problem:
Given a rectangular pizza represented as a
For each cut you choose the direction: vertical or horizontal, then you choose a cut position at the cell boundary and cut the pizza into two pieces. If you cut the pizza vertically, give the left part of the pizza to a person. If you cut the pizza horizontally, give the upper part of the pizza to a person. Give the last piece of pizza to the last person.
Return the number of ways of cutting the pizza such that each piece contains at least one apple. Since the answer can be a huge number, return this modulo 10^9 + 7.
Example 1:
Image: https://assets.leetcode.com/uploads/2020/04/23/ways_to_cut_apple_1.png
Example 2:
Example 3:
Constraints:
•
•
•
•
•
1444. Number of Ways of Cutting a Pizza
Topic: Array, Dynamic Programming, Memoization, Matrix
Difficulty: Hard
Problem:
Given a rectangular pizza represented as a
rows x cols matrix containing the following characters: 'A' (an apple) and '.' (empty cell) and given the integer k. You have to cut the pizza into k pieces using k-1 cuts. For each cut you choose the direction: vertical or horizontal, then you choose a cut position at the cell boundary and cut the pizza into two pieces. If you cut the pizza vertically, give the left part of the pizza to a person. If you cut the pizza horizontally, give the upper part of the pizza to a person. Give the last piece of pizza to the last person.
Return the number of ways of cutting the pizza such that each piece contains at least one apple. Since the answer can be a huge number, return this modulo 10^9 + 7.
Example 1:
Image: https://assets.leetcode.com/uploads/2020/04/23/ways_to_cut_apple_1.png
Input: pizza = ["A..","AAA","..."], k = 3
Output: 3
Explanation: The figure above shows the three ways to cut the pizza. Note that pieces must contain at least one apple.
Example 2:
Input: pizza = ["A..","AA.","..."], k = 3
Output: 1
Example 3:
Input: pizza = ["A..","A..","..."], k = 1
Output: 1
Constraints:
•
1 <= rows, cols <= 50•
rows == pizza.length•
cols == pizza[i].length•
1 <= k <= 10•
pizza consists of characters 'A' and '.' only.2023-04-01
704. Binary Search
Topic: Array, Binary Search
Difficulty: Easy
Problem:
Given an array of integers
You must write an algorithm with
Example 1:
Example 2:
Constraints:
•
•
• All the integers in
•
704. Binary Search
Topic: Array, Binary Search
Difficulty: Easy
Problem:
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.You must write an algorithm with
O(log n) runtime complexity.Example 1:
Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in nums and its index is 4
Example 2:
Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: 2 does not exist in nums so return -1
Constraints:
•
1 <= nums.length <= 10^4•
-10^4 < nums[i], target < 10^4• All the integers in
nums are unique.•
nums is sorted in ascending order.2023-04-02
2300. Successful Pairs of Spells and Potions
Topic: Array, Two Pointers, Binary Search, Sorting
Difficulty: Medium
Problem:
You are given two positive integer arrays
You are also given an integer
Return an integer array
Example 1:
Example 2:
Constraints:
•
•
•
•
•
2300. Successful Pairs of Spells and Potions
Topic: Array, Two Pointers, Binary Search, Sorting
Difficulty: Medium
Problem:
You are given two positive integer arrays
spells and potions, of length n and m respectively, where spells[i] represents the strength of the i^th spell and potions[j] represents the strength of the j^th potion.You are also given an integer
success. A spell and potion pair is considered successful if the product of their strengths is at least success.Return an integer array
pairs of length n where pairs[i] is the number of potions that will form a successful pair with the i^th spell.Example 1:
Input: spells = [5,1,3], potions = [1,2,3,4,5], success = 7
Output: [4,0,3]
Explanation:
- 0^th spell: 5 * [1,2,3,4,5] = [5,10,15,20,25]. 4 pairs are successful.
- 1^st spell: 1 * [1,2,3,4,5] = [1,2,3,4,5]. 0 pairs are successful.
- 2^nd spell: 3 * [1,2,3,4,5] = [3,6,9,12,15]. 3 pairs are successful.
Thus, [4,0,3] is returned.
Example 2:
Input: spells = [3,1,2], potions = [8,5,8], success = 16
Output: [2,0,2]
Explanation:
- 0^th spell: 3 * [8,5,8] = [24,15,24]. 2 pairs are successful.
- 1^st spell: 1 * [8,5,8] = [8,5,8]. 0 pairs are successful.
- 2^nd spell: 2 * [8,5,8] = [16,10,16]. 2 pairs are successful.
Thus, [2,0,2] is returned.
Constraints:
•
n == spells.length•
m == potions.length•
1 <= n, m <= 10^5•
1 <= spells[i], potions[i] <= 10^5•
1 <= success <= 10^102023-04-03
881. Boats to Save People
Topic: Array, Two Pointers, Greedy, Sorting
Difficulty: Medium
Problem:
You are given an array
Return the minimum number of boats to carry every given person.
Example 1:
Example 2:
Example 3:
Constraints:
•
•
881. Boats to Save People
Topic: Array, Two Pointers, Greedy, Sorting
Difficulty: Medium
Problem:
You are given an array
people where people[i] is the weight of the i^th person, and an infinite number of boats where each boat can carry a maximum weight of limit. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most limit.Return the minimum number of boats to carry every given person.
Example 1:
Input: people = [1,2], limit = 3
Output: 1
Explanation: 1 boat (1, 2)
Example 2:
Input: people = [3,2,2,1], limit = 3
Output: 3
Explanation: 3 boats (1, 2), (2) and (3)
Example 3:
Input: people = [3,5,3,4], limit = 5
Output: 4
Explanation: 4 boats (3), (3), (4), (5)
Constraints:
•
1 <= people.length <= 5 * 10^4•
1 <= people[i] <= limit <= 3 * 10^42023-04-04
2405. Optimal Partition of String
Topic: Hash Table, String, Greedy
Difficulty: Medium
Problem:
Given a string
Return the minimum number of substrings in such a partition.
Note that each character should belong to exactly one substring in a partition.
Example 1:
Example 2:
Constraints:
•
•
2405. Optimal Partition of String
Topic: Hash Table, String, Greedy
Difficulty: Medium
Problem:
Given a string
s, partition the string into one or more substrings such that the characters in each substring are unique. That is, no letter appears in a single substring more than once.Return the minimum number of substrings in such a partition.
Note that each character should belong to exactly one substring in a partition.
Example 1:
Input: s = "abacaba"
Output: 4
Explanation:
Two possible partitions are ("a","ba","cab","a") and ("ab","a","ca","ba").
It can be shown that 4 is the minimum number of substrings needed.
Example 2:
Input: s = "ssssss"
Output: 6
Explanation:
The only valid partition is ("s","s","s","s","s","s").
Constraints:
•
1 <= s.length <= 10^5•
s consists of only English lowercase letters.2023-04-05
2439. Minimize Maximum of Array
Topic: Array, Binary Search, Dynamic Programming, Greedy, Prefix Sum
Difficulty: Medium
Problem:
You are given a 0-indexed array
In one operation, you must:
• Choose an integer
• Decrease
• Increase
Return the minimum possible value of the maximum integer of
Example 1:
Example 2:
Constraints:
•
•
•
2439. Minimize Maximum of Array
Topic: Array, Binary Search, Dynamic Programming, Greedy, Prefix Sum
Difficulty: Medium
Problem:
You are given a 0-indexed array
nums comprising of n non-negative integers.In one operation, you must:
• Choose an integer
i such that 1 <= i < n and nums[i] > 0.• Decrease
nums[i] by 1.• Increase
nums[i - 1] by 1.Return the minimum possible value of the maximum integer of
nums after performing any number of operations.Example 1:
Input: nums = [3,7,1,6]
Output: 5
Explanation:
One set of optimal operations is as follows:
1. Choose i = 1, and nums becomes [4,6,1,6].
2. Choose i = 3, and nums becomes [4,6,2,5].
3. Choose i = 1, and nums becomes [5,5,2,5].
The maximum integer of nums is 5. It can be shown that the maximum number cannot be less than 5.
Therefore, we return 5.
Example 2:
Input: nums = [10,1]
Output: 10
Explanation:
It is optimal to leave nums as is, and since 10 is the maximum value, we return 10.
Constraints:
•
n == nums.length•
2 <= n <= 10^5•
0 <= nums[i] <= 10^92023-04-06
1254. Number of Closed Islands
Topic: Array, Depth-First Search, Breadth-First Search, Union Find, Matrix
Difficulty: Medium
Problem:
Given a 2D
Return the number of closed islands.
Example 1:
Image: https://assets.leetcode.com/uploads/2019/10/31/sample_3_1610.png
Example 2:
Image: https://assets.leetcode.com/uploads/2019/10/31/sample_4_1610.png
Example 3:
Constraints:
•
•
1254. Number of Closed Islands
Topic: Array, Depth-First Search, Breadth-First Search, Union Find, Matrix
Difficulty: Medium
Problem:
Given a 2D
grid consists of 0s (land) and 1s (water). An island is a maximal 4-directionally connected group of 0s and a closed island is an island totally (all left, top, right, bottom) surrounded by 1s.Return the number of closed islands.
Example 1:
Image: https://assets.leetcode.com/uploads/2019/10/31/sample_3_1610.png
Input: grid = [[1,1,1,1,1,1,1,0],[1,0,0,0,0,1,1,0],[1,0,1,0,1,1,1,0],[1,0,0,0,0,1,0,1],[1,1,1,1,1,1,1,0]]
Output: 2
Explanation:
Islands in gray are closed because they are completely surrounded by water (group of 1s).
Example 2:
Image: https://assets.leetcode.com/uploads/2019/10/31/sample_4_1610.png
Input: grid = [[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]]
Output: 1
Example 3:
Input: grid = [[1,1,1,1,1,1,1],
[1,0,0,0,0,0,1],
[1,0,1,1,1,0,1],
[1,0,1,0,1,0,1],
[1,0,1,1,1,0,1],
[1,0,0,0,0,0,1],
[1,1,1,1,1,1,1]]
Output: 2
Constraints:
•
1 <= grid.length, grid[0].length <= 100•
0 <= grid[i][j] <=12023-04-07
1020. Number of Enclaves
Topic: Array, Depth-First Search, Breadth-First Search, Union Find, Matrix
Difficulty: Medium
Problem:
You are given an
A move consists of walking from one land cell to another adjacent (4-directionally) land cell or walking off the boundary of the
Return the number of land cells in
Example 1:
Image: https://assets.leetcode.com/uploads/2021/02/18/enclaves1.jpg
Example 2:
Image: https://assets.leetcode.com/uploads/2021/02/18/enclaves2.jpg
Constraints:
•
•
•
•
1020. Number of Enclaves
Topic: Array, Depth-First Search, Breadth-First Search, Union Find, Matrix
Difficulty: Medium
Problem:
You are given an
m x n binary matrix grid, where 0 represents a sea cell and 1 represents a land cell.A move consists of walking from one land cell to another adjacent (4-directionally) land cell or walking off the boundary of the
grid.Return the number of land cells in
grid for which we cannot walk off the boundary of the grid in any number of moves.Example 1:
Image: https://assets.leetcode.com/uploads/2021/02/18/enclaves1.jpg
Input: grid = [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]
Output: 3
Explanation: There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary.
Example 2:
Image: https://assets.leetcode.com/uploads/2021/02/18/enclaves2.jpg
Input: grid = [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]]
Output: 0
Explanation: All 1s are either on the boundary or can reach the boundary.
Constraints:
•
m == grid.length•
n == grid[i].length•
1 <= m, n <= 500•
grid[i][j] is either 0 or 1.2023-04-08
133. Clone Graph
Topic: Hash Table, Depth-First Search, Breadth-First Search, Graph
Difficulty: Medium
Problem:
Given a reference of a node in a connected undirected graph.
Return a deep copy (clone) of the graph.
Each node in the graph contains a value (
Test case format:
For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with
An adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.
The given node will always be the first node with
Example 1:
Image: https://assets.leetcode.com/uploads/2019/11/04/133_clone_graph_question.png
Example 2:
Image: https://assets.leetcode.com/uploads/2020/01/07/graph.png
Example 3:
Constraints:
• The number of nodes in the graph is in the range
•
•
• There are no repeated edges and no self-loops in the graph.
• The Graph is connected and all nodes can be visited starting from the given node.
133. Clone Graph
Topic: Hash Table, Depth-First Search, Breadth-First Search, Graph
Difficulty: Medium
Problem:
Given a reference of a node in a connected undirected graph.
Return a deep copy (clone) of the graph.
Each node in the graph contains a value (
int) and a list (List[Node]) of its neighbors.class Node {
public int val;
public List<Node> neighbors;
}
Test case format:
For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with
val == 1, the second node with val == 2, and so on. The graph is represented in the test case using an adjacency list.An adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.
The given node will always be the first node with
val = 1. You must return the copy of the given node as a reference to the cloned graph.Example 1:
Image: https://assets.leetcode.com/uploads/2019/11/04/133_clone_graph_question.png
Input: adjList = [[2,4],[1,3],[2,4],[1,3]]
Output: [[2,4],[1,3],[2,4],[1,3]]
Explanation: There are 4 nodes in the graph.
1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
Example 2:
Image: https://assets.leetcode.com/uploads/2020/01/07/graph.png
Input: adjList = [[]]
Output: [[]]
Explanation: Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors.
Example 3:
Input: adjList = []
Output: []
Explanation: This an empty graph, it does not have any nodes.
Constraints:
• The number of nodes in the graph is in the range
[0, 100].•
1 <= Node.val <= 100•
Node.val is unique for each node.• There are no repeated edges and no self-loops in the graph.
• The Graph is connected and all nodes can be visited starting from the given node.
2023-04-09
1857. Largest Color Value in a Directed Graph
Topic: Hash Table, Dynamic Programming, Graph, Topological Sort, Memoization, Counting
Difficulty: Hard
Problem:
There is a directed graph of
You are given a string
A valid path in the graph is a sequence of nodes
Return the largest color value of any valid path in the given graph, or
Example 1:
Image: https://assets.leetcode.com/uploads/2021/04/21/leet1.png
Example 2:
Image: https://assets.leetcode.com/uploads/2021/04/21/leet2.png
Constraints:
•
•
•
•
•
•
1857. Largest Color Value in a Directed Graph
Topic: Hash Table, Dynamic Programming, Graph, Topological Sort, Memoization, Counting
Difficulty: Hard
Problem:
There is a directed graph of
n colored nodes and m edges. The nodes are numbered from 0 to n - 1.You are given a string
colors where colors[i] is a lowercase English letter representing the color of the i^th node in this graph (0-indexed). You are also given a 2D array edges where edges[j] = [a_j, b_j] indicates that there is a directed edge from node a_j to node b_j.A valid path in the graph is a sequence of nodes
x_1 -> x_2 -> x_3 -> ... -> x_k such that there is a directed edge from x_i to x_i+1 for every 1 <= i < k. The color value of the path is the number of nodes that are colored the most frequently occurring color along that path.Return the largest color value of any valid path in the given graph, or
-1 if the graph contains a cycle.Example 1:
Image: https://assets.leetcode.com/uploads/2021/04/21/leet1.png
Input: colors = "abaca", edges = [[0,1],[0,2],[2,3],[3,4]]
Output: 3
Explanation: The path 0 -> 2 -> 3 -> 4 contains 3 nodes that are colored "a" (red in the above image).
Example 2:
Image: https://assets.leetcode.com/uploads/2021/04/21/leet2.png
Input: colors = "a", edges = [[0,0]]
Output: -1
Explanation: There is a cycle from 0 to 0.
Constraints:
•
n == colors.length•
m == edges.length•
1 <= n <= 10^5•
0 <= m <= 10^5•
colors consists of lowercase English letters.•
0 <= a_j, b_j < n2023-04-10
20. Valid Parentheses
Topic: String, Stack
Difficulty: Easy
Problem:
Given a string
An input string is valid if:
1. Open brackets must be closed by the same type of brackets.
2. Open brackets must be closed in the correct order.
3. Every close bracket has a corresponding open bracket of the same type.
Example 1:
Example 2:
Example 3:
Constraints:
•
•
20. Valid Parentheses
Topic: String, Stack
Difficulty: Easy
Problem:
Given a string
s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.An input string is valid if:
1. Open brackets must be closed by the same type of brackets.
2. Open brackets must be closed in the correct order.
3. Every close bracket has a corresponding open bracket of the same type.
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
Constraints:
•
1 <= s.length <= 10^4•
s consists of parentheses only '()[]{}'.2023-04-11
2390. Removing Stars From a String
Topic: String, Stack, Simulation
Difficulty: Medium
Problem:
You are given a string
In one operation, you can:
• Choose a star in
• Remove the closest non-star character to its left, as well as remove the star itself.
Return the string after all stars have been removed.
Note:
• The input will be generated such that the operation is always possible.
• It can be shown that the resulting string will always be unique.
Example 1:
Example 2:
Constraints:
•
•
• The operation above can be performed on
2390. Removing Stars From a String
Topic: String, Stack, Simulation
Difficulty: Medium
Problem:
You are given a string
s, which contains stars *.In one operation, you can:
• Choose a star in
s.• Remove the closest non-star character to its left, as well as remove the star itself.
Return the string after all stars have been removed.
Note:
• The input will be generated such that the operation is always possible.
• It can be shown that the resulting string will always be unique.
Example 1:
Input: s = "leet**cod*e"
Output: "lecoe"
Explanation: Performing the removals from left to right:
- The closest character to the 1^st star is 't' in "leet**cod*e". s becomes "lee*cod*e".
- The closest character to the 2^nd star is 'e' in "lee*cod*e". s becomes "lecod*e".
- The closest character to the 3^rd star is 'd' in "lecod*e". s becomes "lecoe".
There are no more stars, so we return "lecoe".
Example 2:
Input: s = "erase*****"
Output: ""
Explanation: The entire string is removed, so we return an empty string.
Constraints:
•
1 <= s.length <= 10^5•
s consists of lowercase English letters and stars *.• The operation above can be performed on
s.