2023-05-04
649. Dota2 Senate
Topic: String, Greedy, Queue
Difficulty: Medium
Problem:
In the world of Dota2, there are two parties: the Radiant and the Dire.
The Dota2 senate consists of senators coming from two parties. Now the Senate wants to decide on a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise one of the two rights:
• Ban one senator's right: A senator can make another senator lose all his rights in this and all the following rounds.
• Announce the victory: If this senator found the senators who still have rights to vote are all from the same party, he can announce the victory and decide on the change in the game.
Given a string
The round-based procedure starts from the first senator to the last senator in the given order. This procedure will last until the end of voting. All the senators who have lost their rights will be skipped during the procedure.
Suppose every senator is smart enough and will play the best strategy for his own party. Predict which party will finally announce the victory and change the Dota2 game. The output should be
Example 1:
Example 2:
Constraints:
•
•
•
649. Dota2 Senate
Topic: String, Greedy, Queue
Difficulty: Medium
Problem:
In the world of Dota2, there are two parties: the Radiant and the Dire.
The Dota2 senate consists of senators coming from two parties. Now the Senate wants to decide on a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise one of the two rights:
• Ban one senator's right: A senator can make another senator lose all his rights in this and all the following rounds.
• Announce the victory: If this senator found the senators who still have rights to vote are all from the same party, he can announce the victory and decide on the change in the game.
Given a string
senate representing each senator's party belonging. The character 'R' and 'D' represent the Radiant party and the Dire party. Then if there are n senators, the size of the given string will be n.The round-based procedure starts from the first senator to the last senator in the given order. This procedure will last until the end of voting. All the senators who have lost their rights will be skipped during the procedure.
Suppose every senator is smart enough and will play the best strategy for his own party. Predict which party will finally announce the victory and change the Dota2 game. The output should be
"Radiant" or "Dire".Example 1:
Input: senate = "RD"
Output: "Radiant"
Explanation:
The first senator comes from Radiant and he can just ban the next senator's right in round 1.
And the second senator can't exercise any rights anymore since his right has been banned.
And in round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote.
Example 2:
Input: senate = "RDD"
Output: "Dire"
Explanation:
The first senator comes from Radiant and he can just ban the next senator's right in round 1.
And the second senator can't exercise any rights anymore since his right has been banned.
And the third senator comes from Dire and he can ban the first senator's right in round 1.
And in round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote.
Constraints:
•
n == senate.length•
1 <= n <= 10^4•
senate[i] is either 'R' or 'D'.2023-05-05
1456. Maximum Number of Vowels in a Substring of Given Length
Topic: String, Sliding Window
Difficulty: Medium
Problem:
Given a string
Vowel letters in English are
Example 1:
Example 2:
Example 3:
Constraints:
•
•
•
1456. Maximum Number of Vowels in a Substring of Given Length
Topic: String, Sliding Window
Difficulty: Medium
Problem:
Given a string
s and an integer k, return the maximum number of vowel letters in any substring of s with length k.Vowel letters in English are
'a', 'e', 'i', 'o', and 'u'.Example 1:
Input: s = "abciiidef", k = 3
Output: 3
Explanation: The substring "iii" contains 3 vowel letters.
Example 2:
Input: s = "aeiou", k = 2
Output: 2
Explanation: Any substring of length 2 contains 2 vowels.
Example 3:
Input: s = "leetcode", k = 3
Output: 2
Explanation: "lee", "eet" and "ode" contain 2 vowels.
Constraints:
•
1 <= s.length <= 10^5•
s consists of lowercase English letters.•
1 <= k <= s.length2023-05-06
1498. Number of Subsequences That Satisfy the Given Sum Condition
Topic: Array, Two Pointers, Binary Search, Sorting
Difficulty: Medium
Problem:
You are given an array of integers
Return the number of non-empty subsequences of
Example 1:
Example 2:
Example 3:
Constraints:
•
•
•
1498. Number of Subsequences That Satisfy the Given Sum Condition
Topic: Array, Two Pointers, Binary Search, Sorting
Difficulty: Medium
Problem:
You are given an array of integers
nums and an integer target.Return the number of non-empty subsequences of
nums such that the sum of the minimum and maximum element on it is less or equal to target. Since the answer may be too large, return it modulo 10^9 + 7.Example 1:
Input: nums = [3,5,6,7], target = 9
Output: 4
Explanation: There are 4 subsequences that satisfy the condition.
[3] -> Min value + max value <= target (3 + 3 <= 9)
[3,5] -> (3 + 5 <= 9)
[3,5,6] -> (3 + 6 <= 9)
[3,6] -> (3 + 6 <= 9)
Example 2:
Input: nums = [3,3,6,8], target = 10
Output: 6
Explanation: There are 6 subsequences that satisfy the condition. (nums can have repeated numbers).
[3] , [3] , [3,3], [3,6] , [3,6] , [3,3,6]
Example 3:
Input: nums = [2,3,3,4,6,7], target = 12
Output: 61
Explanation: There are 63 non-empty subsequences, two of them do not satisfy the condition ([6,7], [7]).
Number of valid subsequences (63 - 2 = 61).
Constraints:
•
1 <= nums.length <= 10^5•
1 <= nums[i] <= 10^6•
1 <= target <= 10^62023-05-07
1964. Find the Longest Valid Obstacle Course at Each Position
Topic: Array, Binary Search, Binary Indexed Tree
Difficulty: Hard
Problem:
You want to build some obstacle courses. You are given a 0-indexed integer array
For every index
• You choose any number of obstacles between
• You must include the
• You must put the chosen obstacles in the same order as they appear in
• Every obstacle (except the first) is taller than or the same height as the obstacle immediately before it.
Return an array
Example 1:
Example 2:
Example 3:
Constraints:
•
•
•
1964. Find the Longest Valid Obstacle Course at Each Position
Topic: Array, Binary Search, Binary Indexed Tree
Difficulty: Hard
Problem:
You want to build some obstacle courses. You are given a 0-indexed integer array
obstacles of length n, where obstacles[i] describes the height of the i^th obstacle.For every index
i between 0 and n - 1 (inclusive), find the length of the longest obstacle course in obstacles such that:• You choose any number of obstacles between
0 and i inclusive.• You must include the
i^th obstacle in the course.• You must put the chosen obstacles in the same order as they appear in
obstacles.• Every obstacle (except the first) is taller than or the same height as the obstacle immediately before it.
Return an array
ans of length n, where ans[i] is the length of the longest obstacle course for index i as described above.Example 1:
Input: obstacles = [1,2,3,2]
Output: [1,2,3,3]
Explanation: The longest valid obstacle course at each position is:
- i = 0: [1], [1] has length 1.
- i = 1: [1,2], [1,2] has length 2.
- i = 2: [1,2,3], [1,2,3] has length 3.
- i = 3: [1,2,3,2], [1,2,2] has length 3.
Example 2:
Input: obstacles = [2,2,1]
Output: [1,2,1]
Explanation: The longest valid obstacle course at each position is:
- i = 0: [2], [2] has length 1.
- i = 1: [2,2], [2,2] has length 2.
- i = 2: [2,2,1], [1] has length 1.
Example 3:
Input: obstacles = [3,1,5,6,4,2]
Output: [1,1,2,3,2,2]
Explanation: The longest valid obstacle course at each position is:
- i = 0: [3], [3] has length 1.
- i = 1: [3,1], [1] has length 1.
- i = 2: [3,1,5], [3,5] has length 2. [1,5] is also valid.
- i = 3: [3,1,5,6], [3,5,6] has length 3. [1,5,6] is also valid.
- i = 4: [3,1,5,6,4], [3,4] has length 2. [1,4] is also valid.
- i = 5: [3,1,5,6,4,2], [1,2] has length 2.
Constraints:
•
n == obstacles.length•
1 <= n <= 10^5•
1 <= obstacles[i] <= 10^72023-05-08
1572. Matrix Diagonal Sum
Topic: Array, Matrix
Difficulty: Easy
Problem:
Given a square matrix
Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.
Example 1:
Image: https://assets.leetcode.com/uploads/2020/08/14/sample_1911.png
Example 2:
Example 3:
Constraints:
•
•
•
1572. Matrix Diagonal Sum
Topic: Array, Matrix
Difficulty: Easy
Problem:
Given a square matrix
mat, return the sum of the matrix diagonals.Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.
Example 1:
Image: https://assets.leetcode.com/uploads/2020/08/14/sample_1911.png
Input: mat = [[1,2,3],
[4,5,6],
[7,8,9]]
Output: 25
Explanation: Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25
Notice that element mat[1][1] = 5 is counted only once.
Example 2:
Input: mat = [[1,1,1,1],
[1,1,1,1],
[1,1,1,1],
[1,1,1,1]]
Output: 8
Example 3:
Input: mat = [[5]]
Output: 5
Constraints:
•
n == mat.length == mat[i].length•
1 <= n <= 100•
1 <= mat[i][j] <= 1002023-05-09
54. Spiral Matrix
Topic: Array, Matrix, Simulation
Difficulty: Medium
Problem:
Given an
Example 1:
Image: https://assets.leetcode.com/uploads/2020/11/13/spiral1.jpg
Example 2:
Image: https://assets.leetcode.com/uploads/2020/11/13/spiral.jpg
Constraints:
•
•
•
•
54. Spiral Matrix
Topic: Array, Matrix, Simulation
Difficulty: Medium
Problem:
Given an
m x n matrix, return all elements of the matrix in spiral order.Example 1:
Image: https://assets.leetcode.com/uploads/2020/11/13/spiral1.jpg
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]
Example 2:
Image: https://assets.leetcode.com/uploads/2020/11/13/spiral.jpg
Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]
Constraints:
•
m == matrix.length•
n == matrix[i].length•
1 <= m, n <= 10•
-100 <= matrix[i][j] <= 1002023-05-10
59. Spiral Matrix II
Topic: Array, Matrix, Simulation
Difficulty: Medium
Problem:
Given a positive integer
Example 1:
Image: https://assets.leetcode.com/uploads/2020/11/13/spiraln.jpg
Example 2:
Constraints:
•
59. Spiral Matrix II
Topic: Array, Matrix, Simulation
Difficulty: Medium
Problem:
Given a positive integer
n, generate an n x n matrix filled with elements from 1 to n^2 in spiral order.Example 1:
Image: https://assets.leetcode.com/uploads/2020/11/13/spiraln.jpg
Input: n = 3
Output: [[1,2,3],[8,9,4],[7,6,5]]
Example 2:
Input: n = 1
Output: [[1]]
Constraints:
•
1 <= n <= 202023-05-11
1035. Uncrossed Lines
Topic: Array, Dynamic Programming
Difficulty: Medium
Problem:
You are given two integer arrays
We may draw connecting lines: a straight line connecting two numbers
•
• the line we draw does not intersect any other connecting (non-horizontal) line.
Note that a connecting line cannot intersect even at the endpoints (i.e., each number can only belong to one connecting line).
Return the maximum number of connecting lines we can draw in this way.
Example 1:
Image: https://assets.leetcode.com/uploads/2019/04/26/142.png
Example 2:
Example 3:
Constraints:
•
•
1035. Uncrossed Lines
Topic: Array, Dynamic Programming
Difficulty: Medium
Problem:
You are given two integer arrays
nums1 and nums2. We write the integers of nums1 and nums2 (in the order they are given) on two separate horizontal lines.We may draw connecting lines: a straight line connecting two numbers
nums1[i] and nums2[j] such that:•
nums1[i] == nums2[j], and• the line we draw does not intersect any other connecting (non-horizontal) line.
Note that a connecting line cannot intersect even at the endpoints (i.e., each number can only belong to one connecting line).
Return the maximum number of connecting lines we can draw in this way.
Example 1:
Image: https://assets.leetcode.com/uploads/2019/04/26/142.png
Input: nums1 = [1,4,2], nums2 = [1,2,4]
Output: 2
Explanation: We can draw 2 uncrossed lines as in the diagram.
We cannot draw 3 uncrossed lines, because the line from nums1[1] = 4 to nums2[2] = 4 will intersect the line from nums1[2]=2 to nums2[1]=2.
Example 2:
Input: nums1 = [2,5,1,2,5], nums2 = [10,5,2,1,5,2]
Output: 3
Example 3:
Input: nums1 = [1,3,7,1,7,5], nums2 = [1,9,2,5,1]
Output: 2
Constraints:
•
1 <= nums1.length, nums2.length <= 500•
1 <= nums1[i], nums2[j] <= 20002023-05-12
2140. Solving Questions With Brainpower
Topic: Array, Dynamic Programming
Difficulty: Medium
Problem:
You are given a 0-indexed 2D integer array
The array describes the questions of an exam, where you have to process the questions in order (i.e., starting from question
• For example, given
• If question
• If instead, question
Return the maximum points you can earn for the exam.
Example 1:
Example 2:
Constraints:
•
•
•
2140. Solving Questions With Brainpower
Topic: Array, Dynamic Programming
Difficulty: Medium
Problem:
You are given a 0-indexed 2D integer array
questions where questions[i] = [points_i, brainpower_i].The array describes the questions of an exam, where you have to process the questions in order (i.e., starting from question
0) and make a decision whether to solve or skip each question. Solving question i will earn you points_i points but you will be unable to solve each of the next brainpower_i questions. If you skip question i, you get to make the decision on the next question.• For example, given
questions = [[3, 2], [4, 3], [4, 4], [2, 5]]:• If question
0 is solved, you will earn 3 points but you will be unable to solve questions 1 and 2.• If instead, question
0 is skipped and question 1 is solved, you will earn 4 points but you will be unable to solve questions 2 and 3.Return the maximum points you can earn for the exam.
Example 1:
Input: questions = [[3,2],[4,3],[4,4],[2,5]]
Output: 5
Explanation: The maximum points can be earned by solving questions 0 and 3.
- Solve question 0: Earn 3 points, will be unable to solve the next 2 questions
- Unable to solve questions 1 and 2
- Solve question 3: Earn 2 points
Total points earned: 3 + 2 = 5. There is no other way to earn 5 or more points.
Example 2:
Input: questions = [[1,1],[2,2],[3,3],[4,4],[5,5]]
Output: 7
Explanation: The maximum points can be earned by solving questions 1 and 4.
- Skip question 0
- Solve question 1: Earn 2 points, will be unable to solve the next 2 questions
- Unable to solve questions 2 and 3
- Solve question 4: Earn 5 points
Total points earned: 2 + 5 = 7. There is no other way to earn 7 or more points.
Constraints:
•
1 <= questions.length <= 10^5•
questions[i].length == 2•
1 <= points_i, brainpower_i <= 10^52023-05-13
2466. Count Ways To Build Good Strings
Topic: Dynamic Programming
Difficulty: Medium
Problem:
Given the integers
• Append the character
• Append the character
This can be performed any number of times.
A good string is a string constructed by the above process having a length between
Return the number of different good strings that can be constructed satisfying these properties. Since the answer can be large, return it modulo
Example 1:
Example 2:
Constraints:
•
•
2466. Count Ways To Build Good Strings
Topic: Dynamic Programming
Difficulty: Medium
Problem:
Given the integers
zero, one, low, and high, we can construct a string by starting with an empty string, and then at each step perform either of the following:• Append the character
'0' zero times.• Append the character
'1' one times.This can be performed any number of times.
A good string is a string constructed by the above process having a length between
low and high (inclusive).Return the number of different good strings that can be constructed satisfying these properties. Since the answer can be large, return it modulo
10^9 + 7.Example 1:
Input: low = 3, high = 3, zero = 1, one = 1
Output: 8
Explanation:
One possible valid good string is "011".
It can be constructed as follows: "" -> "0" -> "01" -> "011".
All binary strings from "000" to "111" are good strings in this example.
Example 2:
Input: low = 2, high = 3, zero = 1, one = 2
Output: 5
Explanation: The good strings are "00", "11", "000", "110", and "011".
Constraints:
•
1 <= low <= high <= 10^5•
1 <= zero, one <= low2023-05-14
1799. Maximize Score After N Operations
Topic: Array, Math, Dynamic Programming, Backtracking, Bit Manipulation, Number Theory, Bitmask
Difficulty: Hard
Problem:
You are given
In the
• Choose two elements,
• Receive a score of
• Remove
Return the maximum score you can receive after performing
The function
Example 1:
Example 2:
Example 3:
Constraints:
•
•
•
1799. Maximize Score After N Operations
Topic: Array, Math, Dynamic Programming, Backtracking, Bit Manipulation, Number Theory, Bitmask
Difficulty: Hard
Problem:
You are given
nums, an array of positive integers of size 2 * n. You must perform n operations on this array.In the
i^th operation (1-indexed), you will:• Choose two elements,
x and y.• Receive a score of
i * gcd(x, y).• Remove
x and y from nums.Return the maximum score you can receive after performing
n operations.The function
gcd(x, y) is the greatest common divisor of x and y.Example 1:
Input: nums = [1,2]
Output: 1
Explanation: The optimal choice of operations is:
(1 * gcd(1, 2)) = 1
Example 2:
Input: nums = [3,4,6,8]
Output: 11
Explanation: The optimal choice of operations is:
(1 * gcd(3, 6)) + (2 * gcd(4, 8)) = 3 + 8 = 11
Example 3:
Input: nums = [1,2,3,4,5,6]
Output: 14
Explanation: The optimal choice of operations is:
(1 * gcd(1, 5)) + (2 * gcd(2, 4)) + (3 * gcd(3, 6)) = 1 + 4 + 9 = 14
Constraints:
•
1 <= n <= 7•
nums.length == 2 * n•
1 <= nums[i] <= 10^62023-05-15
1721. Swapping Nodes in a Linked List
Topic: Linked List, Two Pointers
Difficulty: Medium
Problem:
You are given the
Return the head of the linked list after swapping the values of the
Example 1:
Image: https://assets.leetcode.com/uploads/2020/09/21/linked1.jpg
Example 2:
Constraints:
• The number of nodes in the list is
•
•
1721. Swapping Nodes in a Linked List
Topic: Linked List, Two Pointers
Difficulty: Medium
Problem:
You are given the
head of a linked list, and an integer k.Return the head of the linked list after swapping the values of the
k^th node from the beginning and the k^th node from the end (the list is 1-indexed).Example 1:
Image: https://assets.leetcode.com/uploads/2020/09/21/linked1.jpg
Input: head = [1,2,3,4,5], k = 2
Output: [1,4,3,2,5]
Example 2:
Input: head = [7,9,6,6,7,8,3,0,9,5], k = 5
Output: [7,9,6,6,8,7,3,0,9,5]
Constraints:
• The number of nodes in the list is
n.•
1 <= k <= n <= 10^5•
0 <= Node.val <= 1002023-05-16
24. Swap Nodes in Pairs
Topic: Linked List, Recursion
Difficulty: Medium
Problem:
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Example 1:
Image: https://assets.leetcode.com/uploads/2020/10/03/swap_ex1.jpg
Example 2:
Example 3:
Constraints:
• The number of nodes in the list is in the range
•
24. Swap Nodes in Pairs
Topic: Linked List, Recursion
Difficulty: Medium
Problem:
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Example 1:
Image: https://assets.leetcode.com/uploads/2020/10/03/swap_ex1.jpg
Input: head = [1,2,3,4]
Output: [2,1,4,3]
Example 2:
Input: head = []
Output: []
Example 3:
Input: head = [1]
Output: [1]
Constraints:
• The number of nodes in the list is in the range
[0, 100].•
0 <= Node.val <= 1002023-05-17
2130. Maximum Twin Sum of a Linked List
Topic: Linked List, Two Pointers, Stack
Difficulty: Medium
Problem:
In a linked list of size
• For example, if
The twin sum is defined as the sum of a node and its twin.
Given the
Example 1:
Image: https://assets.leetcode.com/uploads/2021/12/03/eg1drawio.png
Example 2:
Image: https://assets.leetcode.com/uploads/2021/12/03/eg2drawio.png
Example 3:
Image: https://assets.leetcode.com/uploads/2021/12/03/eg3drawio.png
Constraints:
• The number of nodes in the list is an even integer in the range
•
2130. Maximum Twin Sum of a Linked List
Topic: Linked List, Two Pointers, Stack
Difficulty: Medium
Problem:
In a linked list of size
n, where n is even, the i^th node (0-indexed) of the linked list is known as the twin of the (n-1-i)^th node, if 0 <= i <= (n / 2) - 1.• For example, if
n = 4, then node 0 is the twin of node 3, and node 1 is the twin of node 2. These are the only nodes with twins for n = 4.The twin sum is defined as the sum of a node and its twin.
Given the
head of a linked list with even length, return the maximum twin sum of the linked list.Example 1:
Image: https://assets.leetcode.com/uploads/2021/12/03/eg1drawio.png
Input: head = [5,4,2,1]
Output: 6
Explanation:
Nodes 0 and 1 are the twins of nodes 3 and 2, respectively. All have twin sum = 6.
There are no other nodes with twins in the linked list.
Thus, the maximum twin sum of the linked list is 6.
Example 2:
Image: https://assets.leetcode.com/uploads/2021/12/03/eg2drawio.png
Input: head = [4,2,2,3]
Output: 7
Explanation:
The nodes with twins present in this linked list are:
- Node 0 is the twin of node 3 having a twin sum of 4 + 3 = 7.
- Node 1 is the twin of node 2 having a twin sum of 2 + 2 = 4.
Thus, the maximum twin sum of the linked list is max(7, 4) = 7.
Example 3:
Image: https://assets.leetcode.com/uploads/2021/12/03/eg3drawio.png
Input: head = [1,100000]
Output: 100001
Explanation:
There is only one node with a twin in the linked list having twin sum of 1 + 100000 = 100001.
Constraints:
• The number of nodes in the list is an even integer in the range
[2, 10^5].•
1 <= Node.val <= 10^52023-05-18
1557. Minimum Number of Vertices to Reach All Nodes
Topic: Graph
Difficulty: Medium
Problem:
Given a directed acyclic graph, with
Find the smallest set of vertices from which all nodes in the graph are reachable. It's guaranteed that a unique solution exists.
Notice that you can return the vertices in any order.
Example 1:
Image: https://assets.leetcode.com/uploads/2020/07/07/untitled22.png
Example 2:
Image: https://assets.leetcode.com/uploads/2020/07/07/untitled.png
Constraints:
•
•
•
•
• All pairs
1557. Minimum Number of Vertices to Reach All Nodes
Topic: Graph
Difficulty: Medium
Problem:
Given a directed acyclic graph, with
n vertices numbered from 0 to n-1, and an array edges where edges[i] = [from_i, to_i] represents a directed edge from node from_i to node to_i.Find the smallest set of vertices from which all nodes in the graph are reachable. It's guaranteed that a unique solution exists.
Notice that you can return the vertices in any order.
Example 1:
Image: https://assets.leetcode.com/uploads/2020/07/07/untitled22.png
Input: n = 6, edges = [[0,1],[0,2],[2,5],[3,4],[4,2]]
Output: [0,3]
Explanation: It's not possible to reach all the nodes from a single vertex. From 0 we can reach [0,1,2,5]. From 3 we can reach [3,4,2,5]. So we output [0,3].
Example 2:
Image: https://assets.leetcode.com/uploads/2020/07/07/untitled.png
Input: n = 5, edges = [[0,1],[2,1],[3,1],[1,4],[2,4]]
Output: [0,2,3]
Explanation: Notice that vertices 0, 3 and 2 are not reachable from any other node, so we must include them. Also any of these vertices can reach nodes 1 and 4.
Constraints:
•
2 <= n <= 10^5•
1 <= edges.length <= min(10^5, n * (n - 1) / 2)•
edges[i].length == 2•
0 <= from_i, to_i < n• All pairs
(from_i, to_i) are distinct.2023-05-19
785. Is Graph Bipartite?
Topic: Depth-First Search, Breadth-First Search, Union Find, Graph
Difficulty: Medium
Problem:
There is an undirected graph with
• There are no self-edges (
• There are no parallel edges (
• If
• The graph may not be connected, meaning there may be two nodes
A graph is bipartite if the nodes can be partitioned into two independent sets
Return
Example 1:
Image: https://assets.leetcode.com/uploads/2020/10/21/bi2.jpg
Example 2:
Image: https://assets.leetcode.com/uploads/2020/10/21/bi1.jpg
Constraints:
•
•
•
•
•
• All the values of
• If
785. Is Graph Bipartite?
Topic: Depth-First Search, Breadth-First Search, Union Find, Graph
Difficulty: Medium
Problem:
There is an undirected graph with
n nodes, where each node is numbered between 0 and n - 1. You are given a 2D array graph, where graph[u] is an array of nodes that node u is adjacent to. More formally, for each v in graph[u], there is an undirected edge between node u and node v. The graph has the following properties:• There are no self-edges (
graph[u] does not contain u).• There are no parallel edges (
graph[u] does not contain duplicate values).• If
v is in graph[u], then u is in graph[v] (the graph is undirected).• The graph may not be connected, meaning there may be two nodes
u and v such that there is no path between them.A graph is bipartite if the nodes can be partitioned into two independent sets
A and B such that every edge in the graph connects a node in set A and a node in set B.Return
true if and only if it is bipartite.Example 1:
Image: https://assets.leetcode.com/uploads/2020/10/21/bi2.jpg
Input: graph = [[1,2,3],[0,2],[0,1,3],[0,2]]
Output: false
Explanation: There is no way to partition the nodes into two independent sets such that every edge connects a node in one and a node in the other.
Example 2:
Image: https://assets.leetcode.com/uploads/2020/10/21/bi1.jpg
Input: graph = [[1,3],[0,2],[1,3],[0,2]]
Output: true
Explanation: We can partition the nodes into two sets: {0, 2} and {1, 3}.
Constraints:
•
graph.length == n•
1 <= n <= 100•
0 <= graph[u].length < n•
0 <= graph[u][i] <= n - 1•
graph[u] does not contain u.• All the values of
graph[u] are unique.• If
graph[u] contains v, then graph[v] contains u.2023-05-20
399. Evaluate Division
Topic: Array, Depth-First Search, Breadth-First Search, Union Find, Graph, Shortest Path
Difficulty: Medium
Problem:
You are given an array of variable pairs
You are also given some
Return the answers to all queries. If a single answer cannot be determined, return
Note: The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction.
Example 1:
Example 2:
Example 3:
Constraints:
•
•
•
•
•
•
•
•
•
399. Evaluate Division
Topic: Array, Depth-First Search, Breadth-First Search, Union Find, Graph, Shortest Path
Difficulty: Medium
Problem:
You are given an array of variable pairs
equations and an array of real numbers values, where equations[i] = [A_i, B_i] and values[i] represent the equation A_i / B_i = values[i]. Each A_i or B_i is a string that represents a single variable.You are also given some
queries, where queries[j] = [C_j, D_j] represents the j^th query where you must find the answer for C_j / D_j = ?.Return the answers to all queries. If a single answer cannot be determined, return
-1.0.Note: The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction.
Example 1:
Input: equations = [["a","b"],["b","c"]], values = [2.0,3.0], queries = [["a","c"],["b","a"],["a","e"],["a","a"],["x","x"]]
Output: [6.00000,0.50000,-1.00000,1.00000,-1.00000]
Explanation:
Given: a / b = 2.0, b / c = 3.0
queries are: a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ?
return: [6.0, 0.5, -1.0, 1.0, -1.0 ]
Example 2:
Input: equations = [["a","b"],["b","c"],["bc","cd"]], values = [1.5,2.5,5.0], queries = [["a","c"],["c","b"],["bc","cd"],["cd","bc"]]
Output: [3.75000,0.40000,5.00000,0.20000]
Example 3:
Input: equations = [["a","b"]], values = [0.5], queries = [["a","b"],["b","a"],["a","c"],["x","y"]]
Output: [0.50000,2.00000,-1.00000,-1.00000]
Constraints:
•
1 <= equations.length <= 20•
equations[i].length == 2•
1 <= A_i.length, B_i.length <= 5•
values.length == equations.length•
0.0 < values[i] <= 20.0•
1 <= queries.length <= 20•
queries[i].length == 2•
1 <= C_j.length, D_j.length <= 5•
A_i, B_i, C_j, D_j consist of lower case English letters and digits.2023-05-21
934. Shortest Bridge
Topic: Array, Depth-First Search, Breadth-First Search, Matrix
Difficulty: Medium
Problem:
You are given an
An island is a 4-directionally connected group of
You may change
Return the smallest number of
Example 1:
Example 2:
Example 3:
Constraints:
•
•
•
• There are exactly two islands in
934. Shortest Bridge
Topic: Array, Depth-First Search, Breadth-First Search, Matrix
Difficulty: Medium
Problem:
You are given an
n x n binary matrix grid where 1 represents land and 0 represents water.An island is a 4-directionally connected group of
1's not connected to any other 1's. There are exactly two islands in grid.You may change
0's to 1's to connect the two islands to form one island.Return the smallest number of
0's you must flip to connect the two islands.Example 1:
Input: grid = [[0,1],[1,0]]
Output: 1
Example 2:
Input: grid = [[0,1,0],[0,0,0],[0,0,1]]
Output: 2
Example 3:
Input: grid = [[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]]
Output: 1
Constraints:
•
n == grid.length == grid[i].length•
2 <= n <= 100•
grid[i][j] is either 0 or 1.• There are exactly two islands in
grid.2023-05-22
347. Top K Frequent Elements
Topic: Array, Hash Table, Divide and Conquer, Sorting, Heap (Priority Queue), Bucket Sort, Counting, Quickselect
Difficulty: Medium
Problem:
Given an integer array
Example 1:
Example 2:
Constraints:
•
•
•
• It is guaranteed that the answer is unique.
Follow up: Your algorithm's time complexity must be better than
347. Top K Frequent Elements
Topic: Array, Hash Table, Divide and Conquer, Sorting, Heap (Priority Queue), Bucket Sort, Counting, Quickselect
Difficulty: Medium
Problem:
Given an integer array
nums and an integer k, return the k most frequent elements. You may return the answer in any order.Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:
Input: nums = [1], k = 1
Output: [1]
Constraints:
•
1 <= nums.length <= 10^5•
-10^4 <= nums[i] <= 10^4•
k is in the range [1, the number of unique elements in the array].• It is guaranteed that the answer is unique.
Follow up: Your algorithm's time complexity must be better than
O(n log n), where n is the array's size.2023-05-23
703. Kth Largest Element in a Stream
Topic: Tree, Design, Binary Search Tree, Heap (Priority Queue), Binary Tree, Data Stream
Difficulty: Easy
Problem:
Design a class to find the
Implement
•
•
Example 1:
Constraints:
•
•
•
•
• At most
• It is guaranteed that there will be at least
703. Kth Largest Element in a Stream
Topic: Tree, Design, Binary Search Tree, Heap (Priority Queue), Binary Tree, Data Stream
Difficulty: Easy
Problem:
Design a class to find the
k^th largest element in a stream. Note that it is the k^th largest element in the sorted order, not the k^th distinct element.Implement
KthLargest class:•
KthLargest(int k, int[] nums) Initializes the object with the integer k and the stream of integers nums.•
int add(int val) Appends the integer val to the stream and returns the element representing the k^th largest element in the stream.Example 1:
Input
["KthLargest", "add", "add", "add", "add", "add"]
[[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]]
Output
[null, 4, 5, 5, 8, 8]
Explanation
KthLargest kthLargest = new KthLargest(3, [4, 5, 8, 2]);
kthLargest.add(3); // return 4
kthLargest.add(5); // return 5
kthLargest.add(10); // return 5
kthLargest.add(9); // return 8
kthLargest.add(4); // return 8
Constraints:
•
1 <= k <= 10^4•
0 <= nums.length <= 10^4•
-10^4 <= nums[i] <= 10^4•
-10^4 <= val <= 10^4• At most
10^4 calls will be made to add.• It is guaranteed that there will be at least
k elements in the array when you search for the k^th element.2023-05-24
2542. Maximum Subsequence Score
Topic: Array, Greedy, Sorting, Heap (Priority Queue)
Difficulty: Medium
Problem:
You are given two 0-indexed integer arrays
For chosen indices
• The sum of the selected elements from
• It can defined simply as:
Return the maximum possible score.
A subsequence of indices of an array is a set that can be derived from the set
Example 1:
Example 2:
Constraints:
•
•
•
•
2542. Maximum Subsequence Score
Topic: Array, Greedy, Sorting, Heap (Priority Queue)
Difficulty: Medium
Problem:
You are given two 0-indexed integer arrays
nums1 and nums2 of equal length n and a positive integer k. You must choose a subsequence of indices from nums1 of length k.For chosen indices
i_0, i_1, ..., i_k - 1, your score is defined as:• The sum of the selected elements from
nums1 multiplied with the minimum of the selected elements from nums2.• It can defined simply as:
(nums1[i_0] + nums1[i_1] +...+ nums1[i_k - 1]) * min(nums2[i_0] , nums2[i_1], ... ,nums2[i_k - 1]).Return the maximum possible score.
A subsequence of indices of an array is a set that can be derived from the set
{0, 1, ..., n-1} by deleting some or no elements.Example 1:
Input: nums1 = [1,3,3,2], nums2 = [2,1,3,4], k = 3
Output: 12
Explanation:
The four possible subsequence scores are:
- We choose the indices 0, 1, and 2 with score = (1+3+3) * min(2,1,3) = 7.
- We choose the indices 0, 1, and 3 with score = (1+3+2) * min(2,1,4) = 6.
- We choose the indices 0, 2, and 3 with score = (1+3+2) * min(2,3,4) = 12.
- We choose the indices 1, 2, and 3 with score = (3+3+2) * min(1,3,4) = 8.
Therefore, we return the max score, which is 12.
Example 2:
Input: nums1 = [4,2,3,1,1], nums2 = [7,5,10,9,6], k = 1
Output: 30
Explanation:
Choosing index 2 is optimal: nums1[2] * nums2[2] = 3 * 10 = 30 is the maximum possible score.
Constraints:
•
n == nums1.length == nums2.length•
1 <= n <= 10^5•
0 <= nums1[i], nums2[j] <= 10^5•
1 <= k <= n