2023-01-26
787. Cheapest Flights Within K Stops
Topic: Dynamic Programming, Depth-First Search, Breadth-First Search, Graph, Heap (Priority Queue), Shortest Path
Difficulty: Medium
Problem:
There are
You are also given three integers
Example 1:
Image: https://assets.leetcode.com/uploads/2022/03/18/cheapest-flights-within-k-stops-3drawio.png
Example 2:
Image: https://assets.leetcode.com/uploads/2022/03/18/cheapest-flights-within-k-stops-1drawio.png
Example 3:
Image: https://assets.leetcode.com/uploads/2022/03/18/cheapest-flights-within-k-stops-2drawio.png
Constraints:
•
•
•
•
•
•
• There will not be any multiple flights between two cities.
•
•
787. Cheapest Flights Within K Stops
Topic: Dynamic Programming, Depth-First Search, Breadth-First Search, Graph, Heap (Priority Queue), Shortest Path
Difficulty: Medium
Problem:
There are
n cities connected by some number of flights. You are given an array flights where flights[i] = [from_i, to_i, price_i] indicates that there is a flight from city from_i to city to_i with cost price_i.You are also given three integers
src, dst, and k, return the cheapest price from src to dst with at most k stops. If there is no such route, return -1.Example 1:
Image: https://assets.leetcode.com/uploads/2022/03/18/cheapest-flights-within-k-stops-3drawio.png
Input: n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1
Output: 700
Explanation:
The graph is shown above.
The optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700.
Note that the path through cities [0,1,2,3] is cheaper but is invalid because it uses 2 stops.
Example 2:
Image: https://assets.leetcode.com/uploads/2022/03/18/cheapest-flights-within-k-stops-1drawio.png
Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1
Output: 200
Explanation:
The graph is shown above.
The optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200.
Example 3:
Image: https://assets.leetcode.com/uploads/2022/03/18/cheapest-flights-within-k-stops-2drawio.png
Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0
Output: 500
Explanation:
The graph is shown above.
The optimal path with no stops from city 0 to 2 is marked in red and has cost 500.
Constraints:
•
1 <= n <= 100•
0 <= flights.length <= (n * (n - 1) / 2)•
flights[i].length == 3•
0 <= from_i, to_i < n•
from_i != to_i•
1 <= price_i <= 10^4• There will not be any multiple flights between two cities.
•
0 <= src, dst, k < n•
src != dst2023-01-27
472. Concatenated Words
Topic: Array, String, Dynamic Programming, Depth-First Search, Trie
Difficulty: Hard
Problem:
Given an array of strings
A concatenated word is defined as a string that is comprised entirely of at least two shorter words in the given array.
Example 1:
Example 2:
Constraints:
•
•
•
• All the strings of
•
472. Concatenated Words
Topic: Array, String, Dynamic Programming, Depth-First Search, Trie
Difficulty: Hard
Problem:
Given an array of strings
words (without duplicates), return all the concatenated words in the given list of words.A concatenated word is defined as a string that is comprised entirely of at least two shorter words in the given array.
Example 1:
Input: words = ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"]
Output: ["catsdogcats","dogcatsdog","ratcatdogcat"]
Explanation: "catsdogcats" can be concatenated by "cats", "dog" and "cats";
"dogcatsdog" can be concatenated by "dog", "cats" and "dog";
"ratcatdogcat" can be concatenated by "rat", "cat", "dog" and "cat".
Example 2:
Input: words = ["cat","dog","catdog"]
Output: ["catdog"]
Constraints:
•
1 <= words.length <= 10^4•
1 <= words[i].length <= 30•
words[i] consists of only lowercase English letters.• All the strings of
words are unique.•
1 <= sum(words[i].length) <= 10^52023-01-28
352. Data Stream as Disjoint Intervals
Topic: Binary Search, Design, Ordered Set
Difficulty: Hard
Problem:
Given a data stream input of non-negative integers
Implement the
•
•
•
Example 1:
Constraints:
•
• At most
Follow up: What if there are lots of merges and the number of disjoint intervals is small compared to the size of the data stream?
352. Data Stream as Disjoint Intervals
Topic: Binary Search, Design, Ordered Set
Difficulty: Hard
Problem:
Given a data stream input of non-negative integers
a_1, a_2, ..., a_n, summarize the numbers seen so far as a list of disjoint intervals.Implement the
SummaryRanges class:•
SummaryRanges() Initializes the object with an empty stream.•
void addNum(int value) Adds the integer value to the stream.•
int[][] getIntervals() Returns a summary of the integers in the stream currently as a list of disjoint intervals [start_i, end_i]. The answer should be sorted by start_i.Example 1:
Input
["SummaryRanges", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals"]
[[], [1], [], [3], [], [7], [], [2], [], [6], []]
Output
[null, null, [[1, 1]], null, [[1, 1], [3, 3]], null, [[1, 1], [3, 3], [7, 7]], null, [[1, 3], [7, 7]], null, [[1, 3], [6, 7]]]
Explanation
SummaryRanges summaryRanges = new SummaryRanges();
summaryRanges.addNum(1); // arr = [1]
summaryRanges.getIntervals(); // return [[1, 1]]
summaryRanges.addNum(3); // arr = [1, 3]
summaryRanges.getIntervals(); // return [[1, 1], [3, 3]]
summaryRanges.addNum(7); // arr = [1, 3, 7]
summaryRanges.getIntervals(); // return [[1, 1], [3, 3], [7, 7]]
summaryRanges.addNum(2); // arr = [1, 2, 3, 7]
summaryRanges.getIntervals(); // return [[1, 3], [7, 7]]
summaryRanges.addNum(6); // arr = [1, 2, 3, 6, 7]
summaryRanges.getIntervals(); // return [[1, 3], [6, 7]]
Constraints:
•
0 <= value <= 10^4• At most
3 * 10^4 calls will be made to addNum and getIntervals.Follow up: What if there are lots of merges and the number of disjoint intervals is small compared to the size of the data stream?
2023-01-29
460. LFU Cache
Topic: Hash Table, Linked List, Design, Doubly-Linked List
Difficulty: Hard
Problem:
Design and implement a data structure for a Least Frequently Used (LFU) cache.
Implement the
•
•
•
To determine the least frequently used key, a use counter is maintained for each key in the cache. The key with the smallest use counter is the least frequently used key.
When a key is first inserted into the cache, its use counter is set to
The functions
Example 1:
Constraints:
•
•
•
• At most
460. LFU Cache
Topic: Hash Table, Linked List, Design, Doubly-Linked List
Difficulty: Hard
Problem:
Design and implement a data structure for a Least Frequently Used (LFU) cache.
Implement the
LFUCache class:•
LFUCache(int capacity) Initializes the object with the capacity of the data structure.•
int get(int key) Gets the value of the key if the key exists in the cache. Otherwise, returns -1.•
void put(int key, int value) Update the value of the key if present, or inserts the key if not already present. When the cache reaches its capacity, it should invalidate and remove the least frequently used key before inserting a new item. For this problem, when there is a tie (i.e., two or more keys with the same frequency), the least recently used key would be invalidated.To determine the least frequently used key, a use counter is maintained for each key in the cache. The key with the smallest use counter is the least frequently used key.
When a key is first inserted into the cache, its use counter is set to
1 (due to the put operation). The use counter for a key in the cache is incremented either a get or put operation is called on it.The functions
get and put must each run in O(1) average time complexity.Example 1:
Input
["LFUCache", "put", "put", "get", "put", "get", "get", "put", "get", "get", "get"]
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [3], [4, 4], [1], [3], [4]]
Output
[null, null, null, 1, null, -1, 3, null, -1, 3, 4]
Explanation
// cnt(x) = the use counter for key x
// cache=[] will show the last used order for tiebreakers (leftmost element is most recent)
LFUCache lfu = new LFUCache(2);
lfu.put(1, 1); // cache=[1,_], cnt(1)=1
lfu.put(2, 2); // cache=[2,1], cnt(2)=1, cnt(1)=1
lfu.get(1); // return 1
// cache=[1,2], cnt(2)=1, cnt(1)=2
lfu.put(3, 3); // 2 is the LFU key because cnt(2)=1 is the smallest, invalidate 2.
// cache=[3,1], cnt(3)=1, cnt(1)=2
lfu.get(2); // return -1 (not found)
lfu.get(3); // return 3
// cache=[3,1], cnt(3)=2, cnt(1)=2
lfu.put(4, 4); // Both 1 and 3 have the same cnt, but 1 is LRU, invalidate 1.
// cache=[4,3], cnt(4)=1, cnt(3)=2
lfu.get(1); // return -1 (not found)
lfu.get(3); // return 3
// cache=[3,4], cnt(4)=1, cnt(3)=3
lfu.get(4); // return 4
// cache=[4,3], cnt(4)=2, cnt(3)=3
Constraints:
•
0 <= capacity <= 10^4•
0 <= key <= 10^5•
0 <= value <= 10^9• At most
2 * 10^5 calls will be made to get and put.2023-01-30
1137. N-th Tribonacci Number
Topic: Math, Dynamic Programming, Memoization
Difficulty: Easy
Problem:
The Tribonacci sequence
Given
Example 1:
Example 2:
Constraints:
•
• The answer is guaranteed to fit within a 32-bit integer, ie.
1137. N-th Tribonacci Number
Topic: Math, Dynamic Programming, Memoization
Difficulty: Easy
Problem:
The Tribonacci sequence
T_n is defined as follows: T_0 = 0, T_1 = 1, T_2 = 1, and T_n+3 = T_n + T_n+1 + T_n+2 for n >= 0.Given
n, return the value of T_n.Example 1:
Input: n = 4
Output: 4
Explanation:
T_3 = 0 + 1 + 1 = 2
T_4 = 1 + 1 + 2 = 4
Example 2:
Input: n = 25
Output: 1389537
Constraints:
•
0 <= n <= 37• The answer is guaranteed to fit within a 32-bit integer, ie.
answer <= 2^31 - 1.2023-01-31
1626. Best Team With No Conflicts
Topic: Array, Dynamic Programming, Sorting
Difficulty: Medium
Problem:
You are the manager of a basketball team. For the upcoming tournament, you want to choose the team with the highest overall score. The score of the team is the sum of scores of all the players in the team.
However, the basketball team is not allowed to have conflicts. A conflict exists if a younger player has a strictly higher score than an older player. A conflict does not occur between players of the same age.
Given two lists,
Example 1:
Example 2:
Example 3:
Constraints:
•
•
•
•
1626. Best Team With No Conflicts
Topic: Array, Dynamic Programming, Sorting
Difficulty: Medium
Problem:
You are the manager of a basketball team. For the upcoming tournament, you want to choose the team with the highest overall score. The score of the team is the sum of scores of all the players in the team.
However, the basketball team is not allowed to have conflicts. A conflict exists if a younger player has a strictly higher score than an older player. A conflict does not occur between players of the same age.
Given two lists,
scores and ages, where each scores[i] and ages[i] represents the score and age of the i^th player, respectively, return the highest overall score of all possible basketball teams.Example 1:
Input: scores = [1,3,5,10,15], ages = [1,2,3,4,5]
Output: 34
Explanation: You can choose all the players.
Example 2:
Input: scores = [4,5,6,5], ages = [2,1,2,1]
Output: 16
Explanation: It is best to choose the last 3 players. Notice that you are allowed to choose multiple people of the same age.
Example 3:
Input: scores = [1,2,3,5], ages = [8,9,10,1]
Output: 6
Explanation: It is best to choose the first 3 players.
Constraints:
•
1 <= scores.length, ages.length <= 1000•
scores.length == ages.length•
1 <= scores[i] <= 10^6•
1 <= ages[i] <= 10002023-02-01
1071. Greatest Common Divisor of Strings
Topic: Math, String
Difficulty: Easy
Problem:
For two strings
Given two strings
Example 1:
Example 2:
Example 3:
Constraints:
•
•
1071. Greatest Common Divisor of Strings
Topic: Math, String
Difficulty: Easy
Problem:
For two strings
s and t, we say "t divides s" if and only if s = t + ... + t (i.e., t is concatenated with itself one or more times).Given two strings
str1 and str2, return the largest string x such that x divides both str1 and str2.Example 1:
Input: str1 = "ABCABC", str2 = "ABC"
Output: "ABC"
Example 2:
Input: str1 = "ABABAB", str2 = "ABAB"
Output: "AB"
Example 3:
Input: str1 = "LEET", str2 = "CODE"
Output: ""
Constraints:
•
1 <= str1.length, str2.length <= 1000•
str1 and str2 consist of English uppercase letters.2023-02-02
953. Verifying an Alien Dictionary
Topic: Array, Hash Table, String
Difficulty: Easy
Problem:
In an alien language, surprisingly, they also use English lowercase letters, but possibly in a different
Given a sequence of
Example 1:
Example 2:
Example 3:
Constraints:
•
•
•
• All characters in
953. Verifying an Alien Dictionary
Topic: Array, Hash Table, String
Difficulty: Easy
Problem:
In an alien language, surprisingly, they also use English lowercase letters, but possibly in a different
order. The order of the alphabet is some permutation of lowercase letters.Given a sequence of
words written in the alien language, and the order of the alphabet, return true if and only if the given words are sorted lexicographically in this alien language.Example 1:
Input: words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz"
Output: true
Explanation: As 'h' comes before 'l' in this language, then the sequence is sorted.
Example 2:
Input: words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz"
Output: false
Explanation: As 'd' comes after 'l' in this language, then words[0] > words[1], hence the sequence is unsorted.
Example 3:
Input: words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz"
Output: false
Explanation: The first three characters "app" match, and the second string is shorter (in size.) According to lexicographical rules "apple" > "app", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character ([More info](https://en.wikipedia.org/wiki/Lexicographical_order)).
Constraints:
•
1 <= words.length <= 100•
1 <= words[i].length <= 20•
order.length == 26• All characters in
words[i] and order are English lowercase letters.2023-02-03
6. Zigzag Conversion
Topic: String
Difficulty: Medium
Problem:
The string
And then read line by line:
Write the code that will take a string and make this conversion given a number of rows:
Example 1:
Example 2:
Example 3:
Constraints:
•
•
•
6. Zigzag Conversion
Topic: String
Difficulty: Medium
Problem:
The string
"PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)P A H N
A P L S I I G
Y I R
And then read line by line:
"PAHNAPLSIIGYIR"Write the code that will take a string and make this conversion given a number of rows:
string convert(string s, int numRows);
Example 1:
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Example 2:
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:
P I N
A L S I G
Y A H R
P I
Example 3:
Input: s = "A", numRows = 1
Output: "A"
Constraints:
•
1 <= s.length <= 1000•
s consists of English letters (lower-case and upper-case), ',' and '.'.•
1 <= numRows <= 10002023-02-04
567. Permutation in String
Topic: Hash Table, Two Pointers, String, Sliding Window
Difficulty: Medium
Problem:
Given two strings
In other words, return
Example 1:
Example 2:
Constraints:
•
•
567. Permutation in String
Topic: Hash Table, Two Pointers, String, Sliding Window
Difficulty: Medium
Problem:
Given two strings
s1 and s2, return true if s2 contains a permutation of s1, or false otherwise.In other words, return
true if one of s1's permutations is the substring of s2.Example 1:
Input: s1 = "ab", s2 = "eidbaooo"
Output: true
Explanation: s2 contains one permutation of s1 ("ba").
Example 2:
Input: s1 = "ab", s2 = "eidboaoo"
Output: false
Constraints:
•
1 <= s1.length, s2.length <= 10^4•
s1 and s2 consist of lowercase English letters.2023-02-05
438. Find All Anagrams in a String
Topic: Hash Table, String, Sliding Window
Difficulty: Medium
Problem:
Given two strings
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Example 1:
Example 2:
Constraints:
•
•
438. Find All Anagrams in a String
Topic: Hash Table, String, Sliding Window
Difficulty: Medium
Problem:
Given two strings
s and p, return an array of all the start indices of p's anagrams in s. You may return the answer in any order.An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Example 1:
Input: s = "cbaebabacd", p = "abc"
Output: [0,6]
Explanation:
The substring with start index = 0 is "cba", which is an anagram of "abc".
The substring with start index = 6 is "bac", which is an anagram of "abc".
Example 2:
Input: s = "abab", p = "ab"
Output: [0,1,2]
Explanation:
The substring with start index = 0 is "ab", which is an anagram of "ab".
The substring with start index = 1 is "ba", which is an anagram of "ab".
The substring with start index = 2 is "ab", which is an anagram of "ab".
Constraints:
•
1 <= s.length, p.length <= 3 * 10^4•
s and p consist of lowercase English letters.2023-02-06
1470. Shuffle the Array
Topic: Array
Difficulty: Easy
Problem:
Given the array
Return the array in the form
Example 1:
Example 2:
Example 3:
Constraints:
•
•
•
1470. Shuffle the Array
Topic: Array
Difficulty: Easy
Problem:
Given the array
nums consisting of 2n elements in the form [x_1,x_2,...,x_n,y_1,y_2,...,y_n].Return the array in the form
[x_1,y_1,x_2,y_2,...,x_n,y_n].Example 1:
Input: nums = [2,5,1,3,4,7], n = 3
Output: [2,3,5,4,1,7]
Explanation: Since x_1=2, x_2=5, x_3=1, y_1=3, y_2=4, y_3=7 then the answer is [2,3,5,4,1,7].
Example 2:
Input: nums = [1,2,3,4,4,3,2,1], n = 4
Output: [1,4,2,3,3,2,4,1]
Example 3:
Input: nums = [1,1,2,2], n = 2
Output: [1,2,1,2]
Constraints:
•
1 <= n <= 500•
nums.length == 2n•
1 <= nums[i] <= 10^32023-02-07
904. Fruit Into Baskets
Topic: Array, Hash Table, Sliding Window
Difficulty: Medium
Problem:
You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array
You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow:
• You only have two baskets, and each basket can only hold a single type of fruit. There is no limit on the amount of fruit each basket can hold.
• Starting from any tree of your choice, you must pick exactly one fruit from every tree (including the start tree) while moving to the right. The picked fruits must fit in one of your baskets.
• Once you reach a tree with fruit that cannot fit in your baskets, you must stop.
Given the integer array
Example 1:
Example 2:
Example 3:
Constraints:
•
•
904. Fruit Into Baskets
Topic: Array, Hash Table, Sliding Window
Difficulty: Medium
Problem:
You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array
fruits where fruits[i] is the type of fruit the i^th tree produces.You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow:
• You only have two baskets, and each basket can only hold a single type of fruit. There is no limit on the amount of fruit each basket can hold.
• Starting from any tree of your choice, you must pick exactly one fruit from every tree (including the start tree) while moving to the right. The picked fruits must fit in one of your baskets.
• Once you reach a tree with fruit that cannot fit in your baskets, you must stop.
Given the integer array
fruits, return the maximum number of fruits you can pick.Example 1:
Input: fruits = [1,2,1]
Output: 3
Explanation: We can pick from all 3 trees.
Example 2:
Input: fruits = [0,1,2,2]
Output: 3
Explanation: We can pick from trees [1,2,2].
If we had started at the first tree, we would only pick from trees [0,1].
Example 3:
Input: fruits = [1,2,3,2,2]
Output: 4
Explanation: We can pick from trees [2,3,2,2].
If we had started at the first tree, we would only pick from trees [1,2].
Constraints:
•
1 <= fruits.length <= 10^5•
0 <= fruits[i] < fruits.length2023-02-08
45. Jump Game II
Topic: Array, Dynamic Programming, Greedy
Difficulty: Medium
Problem:
You are given a 0-indexed array of integers
Each element
•
•
Return the minimum number of jumps to reach
Example 1:
Example 2:
Constraints:
•
•
45. Jump Game II
Topic: Array, Dynamic Programming, Greedy
Difficulty: Medium
Problem:
You are given a 0-indexed array of integers
nums of length n. You are initially positioned at nums[0].Each element
nums[i] represents the maximum length of a forward jump from index i. In other words, if you are at nums[i], you can jump to any nums[i + j] where:•
0 <= j <= nums[i] and•
i + j < nReturn the minimum number of jumps to reach
nums[n - 1]. The test cases are generated such that you can reach nums[n - 1].Example 1:
Input: nums = [2,3,1,1,4]
Output: 2
Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2:
Input: nums = [2,3,0,1,4]
Output: 2
Constraints:
•
1 <= nums.length <= 10^4•
0 <= nums[i] <= 10002023-02-09
2306. Naming a Company
Topic: Array, Hash Table, String, Bit Manipulation, Enumeration
Difficulty: Hard
Problem:
You are given an array of strings
1. Choose 2 distinct names from
2. Swap the first letters of
3. If both of the new names are not found in the original
4. Otherwise, it is not a valid name.
Return the number of distinct valid names for the company.
Example 1:
Example 2:
Constraints:
•
•
•
• All the strings in
2306. Naming a Company
Topic: Array, Hash Table, String, Bit Manipulation, Enumeration
Difficulty: Hard
Problem:
You are given an array of strings
ideas that represents a list of names to be used in the process of naming a company. The process of naming a company is as follows:1. Choose 2 distinct names from
ideas, call them idea_A and idea_B.2. Swap the first letters of
idea_A and idea_B with each other.3. If both of the new names are not found in the original
ideas, then the name idea_A idea_B (the concatenation of idea_A and idea_B, separated by a space) is a valid company name.4. Otherwise, it is not a valid name.
Return the number of distinct valid names for the company.
Example 1:
Input: ideas = ["coffee","donuts","time","toffee"]
Output: 6
Explanation: The following selections are valid:
- ("coffee", "donuts"): The company name created is "doffee conuts".
- ("donuts", "coffee"): The company name created is "conuts doffee".
- ("donuts", "time"): The company name created is "tonuts dime".
- ("donuts", "toffee"): The company name created is "tonuts doffee".
- ("time", "donuts"): The company name created is "dime tonuts".
- ("toffee", "donuts"): The company name created is "doffee tonuts".
Therefore, there are a total of 6 distinct company names.
The following are some examples of invalid selections:
- ("coffee", "time"): The name "toffee" formed after swapping already exists in the original array.
- ("time", "toffee"): Both names are still the same after swapping and exist in the original array.
- ("coffee", "toffee"): Both names formed after swapping already exist in the original array.
Example 2:
Input: ideas = ["lack","back"]
Output: 0
Explanation: There are no valid selections. Therefore, 0 is returned.
Constraints:
•
2 <= ideas.length <= 5 * 10^4•
1 <= ideas[i].length <= 10•
ideas[i] consists of lowercase English letters.• All the strings in
ideas are unique.2023-02-10
1162. As Far from Land as Possible
Topic: Array, Dynamic Programming, Breadth-First Search, Matrix
Difficulty: Medium
Problem:
Given an
The distance used in this problem is the Manhattan distance: the distance between two cells
Example 1:
Image: https://assets.leetcode.com/uploads/2019/05/03/1336_ex1.JPG
Example 2:
Image: https://assets.leetcode.com/uploads/2019/05/03/1336_ex2.JPG
Constraints:
•
•
•
•
1162. As Far from Land as Possible
Topic: Array, Dynamic Programming, Breadth-First Search, Matrix
Difficulty: Medium
Problem:
Given an
n x n grid containing only values 0 and 1, where 0 represents water and 1 represents land, find a water cell such that its distance to the nearest land cell is maximized, and return the distance. If no land or water exists in the grid, return -1.The distance used in this problem is the Manhattan distance: the distance between two cells
(x0, y0) and (x1, y1) is |x0 - x1| + |y0 - y1|.Example 1:
Image: https://assets.leetcode.com/uploads/2019/05/03/1336_ex1.JPG
Input: grid = [[1,0,1],[0,0,0],[1,0,1]]
Output: 2
Explanation: The cell (1, 1) is as far as possible from all the land with distance 2.
Example 2:
Image: https://assets.leetcode.com/uploads/2019/05/03/1336_ex2.JPG
Input: grid = [[1,0,0],[0,0,0],[0,0,0]]
Output: 4
Explanation: The cell (2, 2) is as far as possible from all the land with distance 4.
Constraints:
•
n == grid.length•
n == grid[i].length•
1 <= n <= 100•
grid[i][j] is 0 or 12023-02-11
1129. Shortest Path with Alternating Colors
Topic: Breadth-First Search, Graph
Difficulty: Medium
Problem:
You are given an integer
You are given two arrays
•
•
Return an array
Example 1:
Example 2:
Constraints:
•
•
•
•
1129. Shortest Path with Alternating Colors
Topic: Breadth-First Search, Graph
Difficulty: Medium
Problem:
You are given an integer
n, the number of nodes in a directed graph where the nodes are labeled from 0 to n - 1. Each edge is red or blue in this graph, and there could be self-edges and parallel edges.You are given two arrays
redEdges and blueEdges where:•
redEdges[i] = [a_i, b_i] indicates that there is a directed red edge from node a_i to node b_i in the graph, and•
blueEdges[j] = [u_j, v_j] indicates that there is a directed blue edge from node u_j to node v_j in the graph.Return an array
answer of length n, where each answer[x] is the length of the shortest path from node 0 to node x such that the edge colors alternate along the path, or -1 if such a path does not exist.Example 1:
Input: n = 3, redEdges = [[0,1],[1,2]], blueEdges = []
Output: [0,1,-1]
Example 2:
Input: n = 3, redEdges = [[0,1]], blueEdges = [[2,1]]
Output: [0,1,-1]
Constraints:
•
1 <= n <= 100•
0 <= redEdges.length, blueEdges.length <= 400•
redEdges[i].length == blueEdges[j].length == 2•
0 <= a_i, b_i, u_j, v_j < n2023-02-12
2477. Minimum Fuel Cost to Report to the Capital
Topic: Tree, Depth-First Search, Breadth-First Search, Graph
Difficulty: Medium
Problem:
There is a tree (i.e., a connected, undirected graph with no cycles) structure country network consisting of
There is a meeting for the representatives of each city. The meeting is in the capital city.
There is a car in each city. You are given an integer
A representative can use the car in their city to travel or change the car and ride with another representative. The cost of traveling between two cities is one liter of fuel.
Return the minimum number of liters of fuel to reach the capital city.
Example 1:
Image: https://assets.leetcode.com/uploads/2022/09/22/a4c380025e3ff0c379525e96a7d63a3.png
Example 2:
Image: https://assets.leetcode.com/uploads/2022/11/16/2.png
Example 3:
Image: https://assets.leetcode.com/uploads/2022/09/27/efcf7f7be6830b8763639cfd01b690a.png
Constraints:
•
•
•
•
•
•
•
2477. Minimum Fuel Cost to Report to the Capital
Topic: Tree, Depth-First Search, Breadth-First Search, Graph
Difficulty: Medium
Problem:
There is a tree (i.e., a connected, undirected graph with no cycles) structure country network consisting of
n cities numbered from 0 to n - 1 and exactly n - 1 roads. The capital city is city 0. You are given a 2D integer array roads where roads[i] = [a_i, b_i] denotes that there exists a bidirectional road connecting cities a_i and b_i.There is a meeting for the representatives of each city. The meeting is in the capital city.
There is a car in each city. You are given an integer
seats that indicates the number of seats in each car.A representative can use the car in their city to travel or change the car and ride with another representative. The cost of traveling between two cities is one liter of fuel.
Return the minimum number of liters of fuel to reach the capital city.
Example 1:
Image: https://assets.leetcode.com/uploads/2022/09/22/a4c380025e3ff0c379525e96a7d63a3.png
Input: roads = [[0,1],[0,2],[0,3]], seats = 5
Output: 3
Explanation:
- Representative_1 goes directly to the capital with 1 liter of fuel.
- Representative_2 goes directly to the capital with 1 liter of fuel.
- Representative_3 goes directly to the capital with 1 liter of fuel.
It costs 3 liters of fuel at minimum.
It can be proven that 3 is the minimum number of liters of fuel needed.
Example 2:
Image: https://assets.leetcode.com/uploads/2022/11/16/2.png
Input: roads = [[3,1],[3,2],[1,0],[0,4],[0,5],[4,6]], seats = 2
Output: 7
Explanation:
- Representative_2 goes directly to city 3 with 1 liter of fuel.
- Representative_2 and representative_3 go together to city 1 with 1 liter of fuel.
- Representative_2 and representative_3 go together to the capital with 1 liter of fuel.
- Representative_1 goes directly to the capital with 1 liter of fuel.
- Representative_5 goes directly to the capital with 1 liter of fuel.
- Representative_6 goes directly to city 4 with 1 liter of fuel.
- Representative_4 and representative_6 go together to the capital with 1 liter of fuel.
It costs 7 liters of fuel at minimum.
It can be proven that 7 is the minimum number of liters of fuel needed.
Example 3:
Image: https://assets.leetcode.com/uploads/2022/09/27/efcf7f7be6830b8763639cfd01b690a.png
Input: roads = [], seats = 1
Output: 0
Explanation: No representatives need to travel to the capital city.
Constraints:
•
1 <= n <= 10^5•
roads.length == n - 1•
roads[i].length == 2•
0 <= a_i, b_i < n•
a_i != b_i•
roads represents a valid tree.•
1 <= seats <= 10^52023-02-13
1523. Count Odd Numbers in an Interval Range
Topic: Math
Difficulty: Easy
Problem:
Given two non-negative integers
Example 1:
Example 2:
Constraints:
•
1523. Count Odd Numbers in an Interval Range
Topic: Math
Difficulty: Easy
Problem:
Given two non-negative integers
low and high. Return the count of odd numbers between low and high (inclusive).Example 1:
Input: low = 3, high = 7
Output: 3
Explanation: The odd numbers between 3 and 7 are [3,5,7].
Example 2:
Input: low = 8, high = 10
Output: 1
Explanation: The odd numbers between 8 and 10 are [9].
Constraints:
•
0 <= low <= high <= 10^92023-02-14
67. Add Binary
Topic: Math, String, Bit Manipulation, Simulation
Difficulty: Easy
Problem:
Given two binary strings
Example 1:
Example 2:
Constraints:
•
•
• Each string does not contain leading zeros except for the zero itself.
67. Add Binary
Topic: Math, String, Bit Manipulation, Simulation
Difficulty: Easy
Problem:
Given two binary strings
a and b, return their sum as a binary string.Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
Constraints:
•
1 <= a.length, b.length <= 10^4•
a and b consist only of '0' or '1' characters.• Each string does not contain leading zeros except for the zero itself.