2023-03-06
1539. Kth Missing Positive Number
Topic: Array, Binary Search
Difficulty: Easy
Problem:
Given an array
Return the
Example 1:
Example 2:
Constraints:
•
•
•
•
Follow up:
Could you solve this problem in less than O(n) complexity?
1539. Kth Missing Positive Number
Topic: Array, Binary Search
Difficulty: Easy
Problem:
Given an array
arr of positive integers sorted in a strictly increasing order, and an integer k.Return the
k^th positive integer that is missing from this array.Example 1:
Input: arr = [2,3,4,7,11], k = 5
Output: 9
Explanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5^th missing positive integer is 9.
Example 2:
Input: arr = [1,2,3,4], k = 2
Output: 6
Explanation: The missing positive integers are [5,6,7,...]. The 2^nd missing positive integer is 6.
Constraints:
•
1 <= arr.length <= 1000•
1 <= arr[i] <= 1000•
1 <= k <= 1000•
arr[i] < arr[j] for 1 <= i < j <= arr.lengthFollow up:
Could you solve this problem in less than O(n) complexity?
2023-03-07
2187. Minimum Time to Complete Trips
Topic: Array, Binary Search
Difficulty: Medium
Problem:
You are given an array
Each bus can make multiple trips successively; that is, the next trip can start immediately after completing the current trip. Also, each bus operates independently; that is, the trips of one bus do not influence the trips of any other bus.
You are also given an integer
Example 1:
Example 2:
Constraints:
•
•
2187. Minimum Time to Complete Trips
Topic: Array, Binary Search
Difficulty: Medium
Problem:
You are given an array
time where time[i] denotes the time taken by the i^th bus to complete one trip.Each bus can make multiple trips successively; that is, the next trip can start immediately after completing the current trip. Also, each bus operates independently; that is, the trips of one bus do not influence the trips of any other bus.
You are also given an integer
totalTrips, which denotes the number of trips all buses should make in total. Return the minimum time required for all buses to complete at least totalTrips trips.Example 1:
Input: time = [1,2,3], totalTrips = 5
Output: 3
Explanation:
- At time t = 1, the number of trips completed by each bus are [1,0,0].
The total number of trips completed is 1 + 0 + 0 = 1.
- At time t = 2, the number of trips completed by each bus are [2,1,0].
The total number of trips completed is 2 + 1 + 0 = 3.
- At time t = 3, the number of trips completed by each bus are [3,1,1].
The total number of trips completed is 3 + 1 + 1 = 5.
So the minimum time needed for all buses to complete at least 5 trips is 3.
Example 2:
Input: time = [2], totalTrips = 1
Output: 2
Explanation:
There is only one bus, and it will complete its first trip at t = 2.
So the minimum time needed to complete 1 trip is 2.
Constraints:
•
1 <= time.length <= 10^5•
1 <= time[i], totalTrips <= 10^72023-03-08
875. Koko Eating Bananas
Topic: Array, Binary Search
Difficulty: Medium
Problem:
Koko loves to eat bananas. There are
Koko can decide her bananas-per-hour eating speed of
Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return.
Return the minimum integer
Example 1:
Example 2:
Example 3:
Constraints:
•
•
•
875. Koko Eating Bananas
Topic: Array, Binary Search
Difficulty: Medium
Problem:
Koko loves to eat bananas. There are
n piles of bananas, the i^th pile has piles[i] bananas. The guards have gone and will come back in h hours.Koko can decide her bananas-per-hour eating speed of
k. Each hour, she chooses some pile of bananas and eats k bananas from that pile. If the pile has less than k bananas, she eats all of them instead and will not eat any more bananas during this hour.Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return.
Return the minimum integer
k such that she can eat all the bananas within h hours.Example 1:
Input: piles = [3,6,7,11], h = 8
Output: 4
Example 2:
Input: piles = [30,11,23,4,20], h = 5
Output: 30
Example 3:
Input: piles = [30,11,23,4,20], h = 6
Output: 23
Constraints:
•
1 <= piles.length <= 10^4•
piles.length <= h <= 10^9•
1 <= piles[i] <= 10^92023-03-09
142. Linked List Cycle II
Topic: Hash Table, Linked List, Two Pointers
Difficulty: Medium
Problem:
Given the
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the
Do not modify the linked list.
Example 1:
Image: https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist.png
Example 2:
Image: https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test2.png
Example 3:
Image: https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test3.png
Constraints:
• The number of the nodes in the list is in the range
•
•
Follow up: Can you solve it using
142. Linked List Cycle II
Topic: Hash Table, Linked List, Two Pointers
Difficulty: Medium
Problem:
Given the
head of a linked list, return the node where the cycle begins. If there is no cycle, return null.There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the
next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to (0-indexed). It is -1 if there is no cycle. Note that pos is not passed as a parameter.Do not modify the linked list.
Example 1:
Image: https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist.png
Input: head = [3,2,0,-4], pos = 1
Output: tail connects to node index 1
Explanation: There is a cycle in the linked list, where tail connects to the second node.
Example 2:
Image: https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test2.png
Input: head = [1,2], pos = 0
Output: tail connects to node index 0
Explanation: There is a cycle in the linked list, where tail connects to the first node.
Example 3:
Image: https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test3.png
Input: head = [1], pos = -1
Output: no cycle
Explanation: There is no cycle in the linked list.
Constraints:
• The number of the nodes in the list is in the range
[0, 10^4].•
-10^5 <= Node.val <= 10^5•
pos is -1 or a valid index in the linked-list.Follow up: Can you solve it using
O(1) (i.e. constant) memory?2023-03-10
382. Linked List Random Node
Topic: Linked List, Math, Reservoir Sampling, Randomized
Difficulty: Medium
Problem:
Given a singly linked list, return a random node's value from the linked list. Each node must have the same probability of being chosen.
Implement the
•
•
Example 1:
Image: https://assets.leetcode.com/uploads/2021/03/16/getrand-linked-list.jpg
Constraints:
• The number of nodes in the linked list will be in the range
•
• At most
Follow up:
• What if the linked list is extremely large and its length is unknown to you?
• Could you solve this efficiently without using extra space?
382. Linked List Random Node
Topic: Linked List, Math, Reservoir Sampling, Randomized
Difficulty: Medium
Problem:
Given a singly linked list, return a random node's value from the linked list. Each node must have the same probability of being chosen.
Implement the
Solution class:•
Solution(ListNode head) Initializes the object with the head of the singly-linked list head.•
int getRandom() Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be chosen.Example 1:
Image: https://assets.leetcode.com/uploads/2021/03/16/getrand-linked-list.jpg
Input
["Solution", "getRandom", "getRandom", "getRandom", "getRandom", "getRandom"]
[[[1, 2, 3]], [], [], [], [], []]
Output
[null, 1, 3, 2, 2, 3]
Explanation
Solution solution = new Solution([1, 2, 3]);
solution.getRandom(); // return 1
solution.getRandom(); // return 3
solution.getRandom(); // return 2
solution.getRandom(); // return 2
solution.getRandom(); // return 3
// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.
Constraints:
• The number of nodes in the linked list will be in the range
[1, 10^4].•
-10^4 <= Node.val <= 10^4• At most
10^4 calls will be made to getRandom.Follow up:
• What if the linked list is extremely large and its length is unknown to you?
• Could you solve this efficiently without using extra space?
2023-03-11
109. Convert Sorted List to Binary Search Tree
Topic: Linked List, Divide and Conquer, Tree, Binary Search Tree, Binary Tree
Difficulty: Medium
Problem:
Given the
Example 1:
Image: https://assets.leetcode.com/uploads/2020/08/17/linked.jpg
Example 2:
Constraints:
• The number of nodes in
•
109. Convert Sorted List to Binary Search Tree
Topic: Linked List, Divide and Conquer, Tree, Binary Search Tree, Binary Tree
Difficulty: Medium
Problem:
Given the
head of a singly linked list where elements are sorted in ascending order, convert it to a height-balanced binary search tree.Example 1:
Image: https://assets.leetcode.com/uploads/2020/08/17/linked.jpg
Input: head = [-10,-3,0,5,9]
Output: [0,-3,9,-10,null,5]
Explanation: One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST.
Example 2:
Input: head = []
Output: []
Constraints:
• The number of nodes in
head is in the range [0, 2 * 10^4].•
-10^5 <= Node.val <= 10^52023-03-12
23. Merge k Sorted Lists
Topic: Linked List, Divide and Conquer, Heap (Priority Queue), Merge Sort
Difficulty: Hard
Problem:
You are given an array of
Merge all the linked-lists into one sorted linked-list and return it.
Example 1:
Example 2:
Example 3:
Constraints:
•
•
•
•
•
• The sum of
23. Merge k Sorted Lists
Topic: Linked List, Divide and Conquer, Heap (Priority Queue), Merge Sort
Difficulty: Hard
Problem:
You are given an array of
k linked-lists lists, each linked-list is sorted in ascending order.Merge all the linked-lists into one sorted linked-list and return it.
Example 1:
Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Explanation: The linked-lists are:
[
1->4->5,
1->3->4,
2->6
]
merging them into one sorted list:
1->1->2->3->4->4->5->6
Example 2:
Input: lists = []
Output: []
Example 3:
Input: lists = [[]]
Output: []
Constraints:
•
k == lists.length•
0 <= k <= 10^4•
0 <= lists[i].length <= 500•
-10^4 <= lists[i][j] <= 10^4•
lists[i] is sorted in ascending order.• The sum of
lists[i].length will not exceed 10^4.2023-03-13
101. Symmetric Tree
Topic: Tree, Depth-First Search, Breadth-First Search, Binary Tree
Difficulty: Easy
Problem:
Given the
Example 1:
Image: https://assets.leetcode.com/uploads/2021/02/19/symtree1.jpg
Example 2:
Image: https://assets.leetcode.com/uploads/2021/02/19/symtree2.jpg
Constraints:
• The number of nodes in the tree is in the range
•
Follow up: Could you solve it both recursively and iteratively?
101. Symmetric Tree
Topic: Tree, Depth-First Search, Breadth-First Search, Binary Tree
Difficulty: Easy
Problem:
Given the
root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).Example 1:
Image: https://assets.leetcode.com/uploads/2021/02/19/symtree1.jpg
Input: root = [1,2,2,3,4,4,3]
Output: true
Example 2:
Image: https://assets.leetcode.com/uploads/2021/02/19/symtree2.jpg
Input: root = [1,2,2,null,3,null,3]
Output: false
Constraints:
• The number of nodes in the tree is in the range
[1, 1000].•
-100 <= Node.val <= 100Follow up: Could you solve it both recursively and iteratively?
2023-03-14
129. Sum Root to Leaf Numbers
Topic: Tree, Depth-First Search, Binary Tree
Difficulty: Medium
Problem:
You are given the
Each root-to-leaf path in the tree represents a number.
• For example, the root-to-leaf path
Return the total sum of all root-to-leaf numbers. Test cases are generated so that the answer will fit in a 32-bit integer.
A leaf node is a node with no children.
Example 1:
Image: https://assets.leetcode.com/uploads/2021/02/19/num1tree.jpg
Example 2:
Image: https://assets.leetcode.com/uploads/2021/02/19/num2tree.jpg
Constraints:
• The number of nodes in the tree is in the range
•
• The depth of the tree will not exceed
129. Sum Root to Leaf Numbers
Topic: Tree, Depth-First Search, Binary Tree
Difficulty: Medium
Problem:
You are given the
root of a binary tree containing digits from 0 to 9 only.Each root-to-leaf path in the tree represents a number.
• For example, the root-to-leaf path
1 -> 2 -> 3 represents the number 123.Return the total sum of all root-to-leaf numbers. Test cases are generated so that the answer will fit in a 32-bit integer.
A leaf node is a node with no children.
Example 1:
Image: https://assets.leetcode.com/uploads/2021/02/19/num1tree.jpg
Input: root = [1,2,3]
Output: 25
Explanation:
The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.
Therefore, sum = 12 + 13 = 25.
Example 2:
Image: https://assets.leetcode.com/uploads/2021/02/19/num2tree.jpg
Input: root = [4,9,0,5,1]
Output: 1026
Explanation:
The root-to-leaf path 4->9->5 represents the number 495.
The root-to-leaf path 4->9->1 represents the number 491.
The root-to-leaf path 4->0 represents the number 40.
Therefore, sum = 495 + 491 + 40 = 1026.
Constraints:
• The number of nodes in the tree is in the range
[1, 1000].•
0 <= Node.val <= 9• The depth of the tree will not exceed
10.2023-03-15
958. Check Completeness of a Binary Tree
Topic: Tree, Breadth-First Search, Binary Tree
Difficulty: Medium
Problem:
Given the
In a complete binary tree, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between
Example 1:
Image: https://assets.leetcode.com/uploads/2018/12/15/complete-binary-tree-1.png
Example 2:
Image: https://assets.leetcode.com/uploads/2018/12/15/complete-binary-tree-2.png
Constraints:
• The number of nodes in the tree is in the range
•
958. Check Completeness of a Binary Tree
Topic: Tree, Breadth-First Search, Binary Tree
Difficulty: Medium
Problem:
Given the
root of a binary tree, determine if it is a complete binary tree.In a complete binary tree, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between
1 and 2^h nodes inclusive at the last level h.Example 1:
Image: https://assets.leetcode.com/uploads/2018/12/15/complete-binary-tree-1.png
Input: root = [1,2,3,4,5,6]
Output: true
Explanation: Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible.
Example 2:
Image: https://assets.leetcode.com/uploads/2018/12/15/complete-binary-tree-2.png
Input: root = [1,2,3,4,5,null,7]
Output: false
Explanation: The node with value 7 isn't as far left as possible.
Constraints:
• The number of nodes in the tree is in the range
[1, 100].•
1 <= Node.val <= 10002023-03-16
106. Construct Binary Tree from Inorder and Postorder Traversal
Topic: Array, Hash Table, Divide and Conquer, Tree, Binary Tree
Difficulty: Medium
Problem:
Given two integer arrays
Example 1:
Image: https://assets.leetcode.com/uploads/2021/02/19/tree.jpg
Example 2:
Constraints:
•
•
•
•
• Each value of
•
•
106. Construct Binary Tree from Inorder and Postorder Traversal
Topic: Array, Hash Table, Divide and Conquer, Tree, Binary Tree
Difficulty: Medium
Problem:
Given two integer arrays
inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree.Example 1:
Image: https://assets.leetcode.com/uploads/2021/02/19/tree.jpg
Input: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
Output: [3,9,20,null,null,15,7]
Example 2:
Input: inorder = [-1], postorder = [-1]
Output: [-1]
Constraints:
•
1 <= inorder.length <= 3000•
postorder.length == inorder.length•
-3000 <= inorder[i], postorder[i] <= 3000•
inorder and postorder consist of unique values.• Each value of
postorder also appears in inorder.•
inorder is guaranteed to be the inorder traversal of the tree.•
postorder is guaranteed to be the postorder traversal of the tree.2023-03-17
208. Implement Trie (Prefix Tree)
Topic: Hash Table, String, Design, Trie
Difficulty: Medium
Problem:
A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.
Implement the Trie class:
•
•
•
•
Example 1:
Constraints:
•
•
• At most
208. Implement Trie (Prefix Tree)
Topic: Hash Table, String, Design, Trie
Difficulty: Medium
Problem:
A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.
Implement the Trie class:
•
Trie() Initializes the trie object.•
void insert(String word) Inserts the string word into the trie.•
boolean search(String word) Returns true if the string word is in the trie (i.e., was inserted before), and false otherwise.•
boolean startsWith(String prefix) Returns true if there is a previously inserted string word that has the prefix prefix, and false otherwise.Example 1:
Input
["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
Output
[null, null, true, false, true, null, true]
Explanation
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // return True
trie.search("app"); // return False
trie.startsWith("app"); // return True
trie.insert("app");
trie.search("app"); // return True
Constraints:
•
1 <= word.length, prefix.length <= 2000•
word and prefix consist only of lowercase English letters.• At most
3 * 10^4 calls in total will be made to insert, search, and startsWith.2023-03-18
1472. Design Browser History
Topic: Array, Linked List, Stack, Design, Doubly-Linked List, Data Stream
Difficulty: Medium
Problem:
You have a browser of one tab where you start on the
Implement the
•
•
•
•
Example:
Constraints:
•
•
•
•
• At most
1472. Design Browser History
Topic: Array, Linked List, Stack, Design, Doubly-Linked List, Data Stream
Difficulty: Medium
Problem:
You have a browser of one tab where you start on the
homepage and you can visit another url, get back in the history number of steps or move forward in the history number of steps.Implement the
BrowserHistory class:•
BrowserHistory(string homepage) Initializes the object with the homepage of the browser.•
void visit(string url) Visits url from the current page. It clears up all the forward history.•
string back(int steps) Move steps back in history. If you can only return x steps in the history and steps > x, you will return only x steps. Return the current url after moving back in history at most steps.•
string forward(int steps) Move steps forward in history. If you can only forward x steps in the history and steps > x, you will forward only x steps. Return the current url after forwarding in history at most steps.Example:
Input:
["BrowserHistory","visit","visit","visit","back","back","forward","visit","forward","back","back"]
[["leetcode.com"],["google.com"],["facebook.com"],["youtube.com"],[1],[1],[1],["linkedin.com"],[2],[2],[7]]
Output:
[null,null,null,null,"facebook.com","google.com","facebook.com",null,"linkedin.com","google.com","leetcode.com"]
Explanation:
BrowserHistory browserHistory = new BrowserHistory("leetcode.com");
browserHistory.visit("google.com"); // You are in "leetcode.com". Visit "google.com"
browserHistory.visit("facebook.com"); // You are in "google.com". Visit "facebook.com"
browserHistory.visit("youtube.com"); // You are in "facebook.com". Visit "youtube.com"
browserHistory.back(1); // You are in "youtube.com", move back to "facebook.com" return "facebook.com"
browserHistory.back(1); // You are in "facebook.com", move back to "google.com" return "google.com"
browserHistory.forward(1); // You are in "google.com", move forward to "facebook.com" return "facebook.com"
browserHistory.visit("linkedin.com"); // You are in "facebook.com". Visit "linkedin.com"
browserHistory.forward(2); // You are in "linkedin.com", you cannot move forward any steps.
browserHistory.back(2); // You are in "linkedin.com", move back two steps to "facebook.com" then to "google.com". return "google.com"
browserHistory.back(7); // You are in "google.com", you can move back only one step to "leetcode.com". return "leetcode.com"
Constraints:
•
1 <= homepage.length <= 20•
1 <= url.length <= 20•
1 <= steps <= 100•
homepage and url consist of '.' or lower case English letters.• At most
5000 calls will be made to visit, back, and forward.2023-03-19
211. Design Add and Search Words Data Structure
Topic: String, Depth-First Search, Design, Trie
Difficulty: Medium
Problem:
Design a data structure that supports adding new words and finding if a string matches any previously added string.
Implement the
•
•
•
Example:
Constraints:
•
•
•
• There will be at most
• At most
211. Design Add and Search Words Data Structure
Topic: String, Depth-First Search, Design, Trie
Difficulty: Medium
Problem:
Design a data structure that supports adding new words and finding if a string matches any previously added string.
Implement the
WordDictionary class:•
WordDictionary() Initializes the object.•
void addWord(word) Adds word to the data structure, it can be matched later.•
bool search(word) Returns true if there is any string in the data structure that matches word or false otherwise. word may contain dots '.' where dots can be matched with any letter.Example:
Input
["WordDictionary","addWord","addWord","addWord","search","search","search","search"]
[[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]]
Output
[null,null,null,null,false,true,true,true]
Explanation
WordDictionary wordDictionary = new WordDictionary();
wordDictionary.addWord("bad");
wordDictionary.addWord("dad");
wordDictionary.addWord("mad");
wordDictionary.search("pad"); // return False
wordDictionary.search("bad"); // return True
wordDictionary.search(".ad"); // return True
wordDictionary.search("b.."); // return True
Constraints:
•
1 <= word.length <= 25•
word in addWord consists of lowercase English letters.•
word in search consist of '.' or lowercase English letters.• There will be at most
3 dots in word for search queries.• At most
10^4 calls will be made to addWord and search.2023-03-20
605. Can Place Flowers
Topic: Array, Greedy
Difficulty: Easy
Problem:
You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots.
Given an integer array
Example 1:
Example 2:
Constraints:
•
•
• There are no two adjacent flowers in
•
605. Can Place Flowers
Topic: Array, Greedy
Difficulty: Easy
Problem:
You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots.
Given an integer array
flowerbed containing 0's and 1's, where 0 means empty and 1 means not empty, and an integer n, return if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule.Example 1:
Input: flowerbed = [1,0,0,0,1], n = 1
Output: true
Example 2:
Input: flowerbed = [1,0,0,0,1], n = 2
Output: false
Constraints:
•
1 <= flowerbed.length <= 2 * 10^4•
flowerbed[i] is 0 or 1.• There are no two adjacent flowers in
flowerbed.•
0 <= n <= flowerbed.length2023-03-21
2348. Number of Zero-Filled Subarrays
Topic: Array, Math
Difficulty: Medium
Problem:
Given an integer array
A subarray is a contiguous non-empty sequence of elements within an array.
Example 1:
Example 2:
Example 3:
Constraints:
•
•
2348. Number of Zero-Filled Subarrays
Topic: Array, Math
Difficulty: Medium
Problem:
Given an integer array
nums, return the number of subarrays filled with 0.A subarray is a contiguous non-empty sequence of elements within an array.
Example 1:
Input: nums = [1,3,0,0,2,0,0,4]
Output: 6
Explanation:
There are 4 occurrences of [0] as a subarray.
There are 2 occurrences of [0,0] as a subarray.
There is no occurrence of a subarray with a size more than 2 filled with 0. Therefore, we return 6.
Example 2:
Input: nums = [0,0,0,2,0,0]
Output: 9
Explanation:
There are 5 occurrences of [0] as a subarray.
There are 3 occurrences of [0,0] as a subarray.
There is 1 occurrence of [0,0,0] as a subarray.
There is no occurrence of a subarray with a size more than 3 filled with 0. Therefore, we return 9.
Example 3:
Input: nums = [2,10,2019]
Output: 0
Explanation: There is no subarray filled with 0. Therefore, we return 0.
Constraints:
•
1 <= nums.length <= 10^5•
-10^9 <= nums[i] <= 10^92023-03-22
2492. Minimum Score of a Path Between Two Cities
Topic: Depth-First Search, Breadth-First Search, Union Find, Graph
Difficulty: Medium
Problem:
You are given a positive integer
The score of a path between two cities is defined as the minimum distance of a road in this path.
Return the minimum possible score of a path between cities
Note:
• A path is a sequence of roads between two cities.
• It is allowed for a path to contain the same road multiple times, and you can visit cities
• The test cases are generated such that there is at least one path between
Example 1:
Image: https://assets.leetcode.com/uploads/2022/10/12/graph11.png
Example 2:
Image: https://assets.leetcode.com/uploads/2022/10/12/graph22.png
Constraints:
•
•
•
•
•
•
• There are no repeated edges.
• There is at least one path between
2492. Minimum Score of a Path Between Two Cities
Topic: Depth-First Search, Breadth-First Search, Union Find, Graph
Difficulty: Medium
Problem:
You are given a positive integer
n representing n cities numbered from 1 to n. You are also given a 2D array roads where roads[i] = [a_i, b_i, distance_i] indicates that there is a bidirectional road between cities a_i and b_i with a distance equal to distance_i. The cities graph is not necessarily connected.The score of a path between two cities is defined as the minimum distance of a road in this path.
Return the minimum possible score of a path between cities
1 and n.Note:
• A path is a sequence of roads between two cities.
• It is allowed for a path to contain the same road multiple times, and you can visit cities
1 and n multiple times along the path.• The test cases are generated such that there is at least one path between
1 and n.Example 1:
Image: https://assets.leetcode.com/uploads/2022/10/12/graph11.png
Input: n = 4, roads = [[1,2,9],[2,3,6],[2,4,5],[1,4,7]]
Output: 5
Explanation: The path from city 1 to 4 with the minimum score is: 1 -> 2 -> 4. The score of this path is min(9,5) = 5.
It can be shown that no other path has less score.
Example 2:
Image: https://assets.leetcode.com/uploads/2022/10/12/graph22.png
Input: n = 4, roads = [[1,2,2],[1,3,4],[3,4,7]]
Output: 2
Explanation: The path from city 1 to 4 with the minimum score is: 1 -> 2 -> 1 -> 3 -> 4. The score of this path is min(2,2,4,7) = 2.
Constraints:
•
2 <= n <= 10^5•
1 <= roads.length <= 10^5•
roads[i].length == 3•
1 <= a_i, b_i <= n•
a_i != b_i•
1 <= distance_i <= 10^4• There are no repeated edges.
• There is at least one path between
1 and n.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] != i