diff --git a/1001-1100/1014. Best Sightseeing Pair.md b/1001-1100/1014. Best Sightseeing Pair.md new file mode 100644 index 0000000..90f0d79 --- /dev/null +++ b/1001-1100/1014. Best Sightseeing Pair.md @@ -0,0 +1,67 @@ +# 1014. Best Sightseeing Pair + +- Difficulty: Medium. +- Related Topics: Array, Dynamic Programming. +- Similar Questions: . + +## Problem + +You are given an integer array `values` where values[i] represents the value of the `ith` sightseeing spot. Two sightseeing spots `i` and `j` have a **distance** `j - i` between them. + +The score of a pair (`i < j`) of sightseeing spots is `values[i] + values[j] + i - j`: the sum of the values of the sightseeing spots, minus the distance between them. + +Return **the maximum score of a pair of sightseeing spots**. + +  +Example 1: + +``` +Input: values = [8,1,5,2,6] +Output: 11 +Explanation: i = 0, j = 2, values[i] + values[j] + i - j = 8 + 5 + 0 - 2 = 11 +``` + +Example 2: + +``` +Input: values = [1,2] +Output: 2 +``` + +  +**Constraints:** + + + +- `2 <= values.length <= 5 * 104` + +- `1 <= values[i] <= 1000` + + + +## Solution + +```javascript +/** + * @param {number[]} values + * @return {number} + */ +var maxScoreSightseeingPair = function(values) { + var last = 0; + var max = Number.MIN_SAFE_INTEGER; + for (var i = 0; i < values.length; i++) { + max = Math.max(max, last + values[i] - i); + last = Math.max(last, values[i] + i); + } + return max; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/1101-1200/1105. Filling Bookcase Shelves.md b/1101-1200/1105. Filling Bookcase Shelves.md new file mode 100644 index 0000000..d014682 --- /dev/null +++ b/1101-1200/1105. Filling Bookcase Shelves.md @@ -0,0 +1,93 @@ +# 1105. Filling Bookcase Shelves + +- Difficulty: Medium. +- Related Topics: Array, Dynamic Programming. +- Similar Questions: . + +## Problem + +You are given an array `books` where `books[i] = [thicknessi, heighti]` indicates the thickness and height of the `ith` book. You are also given an integer `shelfWidth`. + +We want to place these books in order onto bookcase shelves that have a total width `shelfWidth`. + +We choose some of the books to place on this shelf such that the sum of their thickness is less than or equal to `shelfWidth`, then build another level of the shelf of the bookcase so that the total height of the bookcase has increased by the maximum height of the books we just put down. We repeat this process until there are no more books to place. + +Note that at each step of the above process, the order of the books we place is the same order as the given sequence of books. + + + +- For example, if we have an ordered list of `5` books, we might place the first and second book onto the first shelf, the third book on the second shelf, and the fourth and fifth book on the last shelf. + + +Return **the minimum possible height that the total bookshelf can be after placing shelves in this manner**. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2019/06/24/shelves.png) + +``` +Input: books = [[1,1],[2,3],[2,3],[1,1],[1,1],[1,1],[1,2]], shelfWidth = 4 +Output: 6 +Explanation: +The sum of the heights of the 3 shelves is 1 + 3 + 2 = 6. +Notice that book number 2 does not have to be on the first shelf. +``` + +Example 2: + +``` +Input: books = [[1,3],[2,4],[3,2]], shelfWidth = 6 +Output: 4 +``` + +  +**Constraints:** + + + +- `1 <= books.length <= 1000` + +- `1 <= thicknessi <= shelfWidth <= 1000` + +- `1 <= heighti <= 1000` + + + +## Solution + +```javascript +/** + * @param {number[][]} books + * @param {number} shelfWidth + * @return {number} + */ +var minHeightShelves = function(books, shelfWidth) { + var dp = Array(books.length).fill(0).map(() => Array(shelfWidth)); + var helper = function(i, rowWidthLeft, rowHeight) { + if (i === books.length) return rowHeight; + if (dp[i][rowWidthLeft - 1]) return dp[i][rowWidthLeft - 1]; + var res = Number.MAX_SAFE_INTEGER; + // put current book on the same row + if (books[i][0] <= rowWidthLeft) { + res = Math.min(res, helper(i + 1, rowWidthLeft - books[i][0], Math.max(rowHeight, books[i][1]))); + } + // put current book on the next row + res = Math.min(res, rowHeight + helper(i + 1, shelfWidth - books[i][0], books[i][1])); + dp[i][rowWidthLeft - 1] = res; + return res; + }; + return helper(0, shelfWidth, 0); +}; + + +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * m). +* Space complexity : O(n * m). diff --git a/1101-1200/1140. Stone Game II.md b/1101-1200/1140. Stone Game II.md new file mode 100644 index 0000000..4c96580 --- /dev/null +++ b/1101-1200/1140. Stone Game II.md @@ -0,0 +1,87 @@ +# 1140. Stone Game II + +- Difficulty: Medium. +- Related Topics: Array, Math, Dynamic Programming, Prefix Sum, Game Theory. +- Similar Questions: Stone Game V, Stone Game VI, Stone Game VII, Stone Game VIII, Stone Game IX. + +## Problem + +Alice and Bob continue their games with piles of stones.  There are a number of piles **arranged in a row**, and each pile has a positive integer number of stones `piles[i]`.  The objective of the game is to end with the most stones.  + +Alice and Bob take turns, with Alice starting first.  Initially, `M = 1`. + +On each player's turn, that player can take **all the stones** in the **first** `X` remaining piles, where `1 <= X <= 2M`.  Then, we set `M = max(M, X)`. + +The game continues until all the stones have been taken. + +Assuming Alice and Bob play optimally, return the maximum number of stones Alice can get. + +  +Example 1: + +``` +Input: piles = [2,7,9,4,4] +Output: 10 +Explanation: If Alice takes one pile at the beginning, Bob takes two piles, then Alice takes 2 piles again. Alice can get 2 + 4 + 4 = 10 piles in total. If Alice takes two piles at the beginning, then Bob can take all three piles left. In this case, Alice get 2 + 7 = 9 piles in total. So we return 10 since it's larger. +``` + +Example 2: + +``` +Input: piles = [1,2,3,4,5,100] +Output: 104 +``` + +  +**Constraints:** + + + +- `1 <= piles.length <= 100` + +- `1 <= piles[i] <= 104` + + + +## Solution + +```javascript +/** + * @param {number[]} piles + * @return {number} + */ +var stoneGameII = function(piles) { + var dp = Array(piles.length).fill(0).map(() => ({})); + var suffixSum = Array(piles.length); + for (var i = piles.length - 1; i >= 0; i--) { + suffixSum[i] = (suffixSum[i + 1] || 0) + piles[i]; + } + return helper(piles, 0, 1, dp, suffixSum); +}; + +var helper = function(piles, i, M, dp, suffixSum) { + if (dp[i][M]) return dp[i][M]; + var res = 0; + var sum = 0; + for (var j = 0; j < 2 * M && i + j < piles.length; j++) { + sum += piles[i + j]; + res = Math.max( + res, + i + j + 1 === piles.length + ? sum + : sum + suffixSum[i + j + 1] - helper(piles, i + j + 1, Math.max(M, j + 1), dp, suffixSum) + ); + } + dp[i][M] = res; + return res; +} +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n ^ 3). +* Space complexity : O(n ^ 2). diff --git a/1301-1400/1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance.md b/1301-1400/1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance.md new file mode 100644 index 0000000..f89980b --- /dev/null +++ b/1301-1400/1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance.md @@ -0,0 +1,123 @@ +# 1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance + +- Difficulty: Medium. +- Related Topics: Dynamic Programming, Graph, Shortest Path. +- Similar Questions: Second Minimum Time to Reach Destination. + +## Problem + +There are `n` cities numbered from `0` to `n-1`. Given the array `edges` where `edges[i] = [fromi, toi, weighti]` represents a bidirectional and weighted edge between cities `fromi` and `toi`, and given the integer `distanceThreshold`. + +Return the city with the smallest number of cities that are reachable through some path and whose distance is **at most** `distanceThreshold`, If there are multiple such cities, return the city with the greatest number. + +Notice that the distance of a path connecting cities ****i**** and ****j**** is equal to the sum of the edges' weights along that path. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2020/01/16/find_the_city_01.png) + +``` +Input: n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4 +Output: 3 +Explanation: The figure above describes the graph.  +The neighboring cities at a distanceThreshold = 4 for each city are: +City 0 -> [City 1, City 2]  +City 1 -> [City 0, City 2, City 3]  +City 2 -> [City 0, City 1, City 3]  +City 3 -> [City 1, City 2]  +Cities 0 and 3 have 2 neighboring cities at a distanceThreshold = 4, but we have to return city 3 since it has the greatest number. +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2020/01/16/find_the_city_02.png) + +``` +Input: n = 5, edges = [[0,1,2],[0,4,8],[1,2,3],[1,4,2],[2,3,1],[3,4,1]], distanceThreshold = 2 +Output: 0 +Explanation: The figure above describes the graph.  +The neighboring cities at a distanceThreshold = 2 for each city are: +City 0 -> [City 1]  +City 1 -> [City 0, City 4]  +City 2 -> [City 3, City 4]  +City 3 -> [City 2, City 4] +City 4 -> [City 1, City 2, City 3]  +The city 0 has 1 neighboring city at a distanceThreshold = 2. +``` + +  +**Constraints:** + + + +- `2 <= n <= 100` + +- `1 <= edges.length <= n * (n - 1) / 2` + +- `edges[i].length == 3` + +- `0 <= fromi < toi < n` + +- `1 <= weighti, distanceThreshold <= 10^4` + +- All pairs `(fromi, toi)` are distinct. + + + +## Solution + +```javascript +/** + * @param {number} n + * @param {number[][]} edges + * @param {number} distanceThreshold + * @return {number} + */ +var findTheCity = function(n, edges, distanceThreshold) { + var map = {}; + for (var i = 0; i < edges.length; i++) { + map[edges[i][0]] = map[edges[i][0]] || {}; + map[edges[i][1]] = map[edges[i][1]] || {}; + map[edges[i][1]][edges[i][0]] = edges[i][2]; + map[edges[i][0]][edges[i][1]] = edges[i][2]; + } + var min = Number.MAX_SAFE_INTEGER; + var minNum = -1; + for (var j = 0; j < n; j++) { + var cities = dijkstra(j, map, distanceThreshold); + if (cities <= min) { + min = cities; + minNum = j; + } + } + return minNum; +}; + +var dijkstra = function(n, map, distanceThreshold) { + var visited = {}; + var queue = new MinPriorityQueue(); + queue.enqueue(n, 0); + while (queue.size() > 0) { + var { element, priority } = queue.dequeue(); + if (priority > distanceThreshold) break; + if (visited[element]) continue; + visited[element] = true; + var arr = Object.keys(map[element] || {}); + for (var i = 0; i < arr.length; i++) { + if (visited[arr[i]]) continue; + queue.enqueue(arr[i], priority + map[element][arr[i]]); + } + } + return Object.keys(visited).length; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n ^ 3 * log(n)). +* Space complexity : O(n ^ 2). diff --git a/1501-1600/1508. Range Sum of Sorted Subarray Sums.md b/1501-1600/1508. Range Sum of Sorted Subarray Sums.md new file mode 100644 index 0000000..4136776 --- /dev/null +++ b/1501-1600/1508. Range Sum of Sorted Subarray Sums.md @@ -0,0 +1,90 @@ +# 1508. Range Sum of Sorted Subarray Sums + +- Difficulty: Medium. +- Related Topics: Array, Two Pointers, Binary Search, Sorting. +- Similar Questions: . + +## Problem + +You are given the array `nums` consisting of `n` positive integers. You computed the sum of all non-empty continuous subarrays from the array and then sorted them in non-decreasing order, creating a new array of `n * (n + 1) / 2` numbers. + +**Return the sum of the numbers from index **`left`** to index **`right` (**indexed from 1**)**, inclusive, in the new array. **Since the answer can be a huge number return it modulo `109 + 7`. + +  +Example 1: + +``` +Input: nums = [1,2,3,4], n = 4, left = 1, right = 5 +Output: 13 +Explanation: All subarray sums are 1, 3, 6, 10, 2, 5, 9, 3, 7, 4. After sorting them in non-decreasing order we have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 1 to ri = 5 is 1 + 2 + 3 + 3 + 4 = 13. +``` + +Example 2: + +``` +Input: nums = [1,2,3,4], n = 4, left = 3, right = 4 +Output: 6 +Explanation: The given array is the same as example 1. We have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 3 to ri = 4 is 3 + 3 = 6. +``` + +Example 3: + +``` +Input: nums = [1,2,3,4], n = 4, left = 1, right = 10 +Output: 50 +``` + +  +**Constraints:** + + + +- `n == nums.length` + +- `1 <= nums.length <= 1000` + +- `1 <= nums[i] <= 100` + +- `1 <= left <= right <= n * (n + 1) / 2` + + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @param {number} n + * @param {number} left + * @param {number} right + * @return {number} + */ +var rangeSum = function(nums, n, left, right) { + var queue = new MinPriorityQueue(); + for (var i = 0; i < nums.length; i++) { + queue.enqueue(i, nums[i]); + } + var res = 0; + var mod = Math.pow(10, 9) + 7; + for (var j = 0; j < right; j++) { + var { element, priority } = queue.dequeue(); + if (element < nums.length - 1) { + queue.enqueue(element + 1, priority + nums[element + 1]); + } + if (j >= left - 1) { + res += priority; + res %= mod; + } + } + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n^2 * log(n)). +* Space complexity : O(n). diff --git a/1501-1600/1509. Minimum Difference Between Largest and Smallest Value in Three Moves.md b/1501-1600/1509. Minimum Difference Between Largest and Smallest Value in Three Moves.md new file mode 100644 index 0000000..1c4381d --- /dev/null +++ b/1501-1600/1509. Minimum Difference Between Largest and Smallest Value in Three Moves.md @@ -0,0 +1,133 @@ +# 1509. Minimum Difference Between Largest and Smallest Value in Three Moves + +- Difficulty: Medium. +- Related Topics: Array, Greedy, Sorting. +- Similar Questions: Minimize the Maximum Difference of Pairs. + +## Problem + +You are given an integer array `nums`. + +In one move, you can choose one element of `nums` and change it to **any value**. + +Return **the minimum difference between the largest and smallest value of `nums` **after performing at most three moves****. + +  +Example 1: + +``` +Input: nums = [5,3,2,4] +Output: 0 +Explanation: We can make at most 3 moves. +In the first move, change 2 to 3. nums becomes [5,3,3,4]. +In the second move, change 4 to 3. nums becomes [5,3,3,3]. +In the third move, change 5 to 3. nums becomes [3,3,3,3]. +After performing 3 moves, the difference between the minimum and maximum is 3 - 3 = 0. +``` + +Example 2: + +``` +Input: nums = [1,5,0,10,14] +Output: 1 +Explanation: We can make at most 3 moves. +In the first move, change 5 to 0. nums becomes [1,0,0,10,14]. +In the second move, change 10 to 0. nums becomes [1,0,0,0,14]. +In the third move, change 14 to 1. nums becomes [1,0,0,0,1]. +After performing 3 moves, the difference between the minimum and maximum is 1 - 0 = 1. +It can be shown that there is no way to make the difference 0 in 3 moves. +``` + +Example 3: + +``` +Input: nums = [3,100,20] +Output: 0 +Explanation: We can make at most 3 moves. +In the first move, change 100 to 7. nums becomes [3,7,20]. +In the second move, change 20 to 7. nums becomes [3,7,7]. +In the third move, change 3 to 7. nums becomes [7,7,7]. +After performing 3 moves, the difference between the minimum and maximum is 7 - 7 = 0. +``` + +  +**Constraints:** + + + +- `1 <= nums.length <= 105` + +- `-109 <= nums[i] <= 109` + + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @return {number} + */ +var minDifference = function(nums) { + if (nums.length <= 4) return 0; + nums.sort((a, b) => a - b); + return Math.min( + nums[nums.length - 4] - nums[0], + nums[nums.length - 3] - nums[1], + nums[nums.length - 2] - nums[2], + nums[nums.length - 1] - nums[3], + ); +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * log(n)). +* Space complexity : O(n). + +## Solution 2 + +```javascript +/** + * @param {number[]} nums + * @return {number} + */ +var minDifference = function(nums) { + if (nums.length <= 4) return 0; + var minQueue = new MinPriorityQueue(); + var maxQueue = new MaxPriorityQueue(); + for (var i = 0; i < nums.length; i++) { + minQueue.enqueue(nums[i], nums[i]); + if (minQueue.size() > 4) { + minQueue.dequeue(); + } + maxQueue.enqueue(nums[i], nums[i]); + if (maxQueue.size() > 4) { + maxQueue.dequeue(); + } + } + const arr = [ + ...maxQueue.toArray().map(item => item.element).reverse(), + ...minQueue.toArray().map(item => item.element), + ]; + return Math.min( + arr[arr.length - 4] - arr[0], + arr[arr.length - 3] - arr[1], + arr[arr.length - 2] - arr[2], + arr[arr.length - 1] - arr[3], + ); +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * log(4) * log(4)) = O(n). +* Space complexity : O(1). diff --git a/1501-1600/1544. Make The String Great.md b/1501-1600/1544. Make The String Great.md new file mode 100644 index 0000000..901dee2 --- /dev/null +++ b/1501-1600/1544. Make The String Great.md @@ -0,0 +1,95 @@ +# 1544. Make The String Great + +- Difficulty: Easy. +- Related Topics: String, Stack. +- Similar Questions: . + +## Problem + +Given a string `s` of lower and upper case English letters. + +A good string is a string which doesn't have **two adjacent characters** `s[i]` and `s[i + 1]` where: + + + +- `0 <= i <= s.length - 2` + +- `s[i]` is a lower-case letter and `s[i + 1]` is the same letter but in upper-case or **vice-versa**. + + +To make the string good, you can choose **two adjacent** characters that make the string bad and remove them. You can keep doing this until the string becomes good. + +Return **the string** after making it good. The answer is guaranteed to be unique under the given constraints. + +**Notice** that an empty string is also good. + +  +Example 1: + +``` +Input: s = "leEeetcode" +Output: "leetcode" +Explanation: In the first step, either you choose i = 1 or i = 2, both will result "leEeetcode" to be reduced to "leetcode". +``` + +Example 2: + +``` +Input: s = "abBAcC" +Output: "" +Explanation: We have many possible scenarios, and all lead to the same answer. For example: +"abBAcC" --> "aAcC" --> "cC" --> "" +"abBAcC" --> "abBA" --> "aA" --> "" +``` + +Example 3: + +``` +Input: s = "s" +Output: "s" +``` + +  +**Constraints:** + + + +- `1 <= s.length <= 100` + +- `s` contains only lower and upper case English letters. + + + +## Solution + +```javascript +/** + * @param {string} s + * @return {string} + */ +var makeGood = function(s) { + var i = 0; + var res = []; + while (i < s.length) { + if (res.length + && s[i] !== res[res.length - 1] + && s[i].toLowerCase() === res[res.length - 1].toLowerCase() + ) { + res.pop(); + } else { + res.push(s[i]); + } + i += 1; + } + return res.join(''); +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/1601-1700/1605. Find Valid Matrix Given Row and Column Sums.md b/1601-1700/1605. Find Valid Matrix Given Row and Column Sums.md new file mode 100644 index 0000000..756e8bf --- /dev/null +++ b/1601-1700/1605. Find Valid Matrix Given Row and Column Sums.md @@ -0,0 +1,88 @@ +# 1605. Find Valid Matrix Given Row and Column Sums + +- Difficulty: Medium. +- Related Topics: Array, Greedy, Matrix. +- Similar Questions: Reconstruct a 2-Row Binary Matrix. + +## Problem + +You are given two arrays `rowSum` and `colSum` of non-negative integers where `rowSum[i]` is the sum of the elements in the `ith` row and `colSum[j]` is the sum of the elements of the `jth` column of a 2D matrix. In other words, you do not know the elements of the matrix, but you do know the sums of each row and column. + +Find any matrix of **non-negative** integers of size `rowSum.length x colSum.length` that satisfies the `rowSum` and `colSum` requirements. + +Return **a 2D array representing **any** matrix that fulfills the requirements**. It's guaranteed that **at least one **matrix that fulfills the requirements exists. + +  +Example 1: + +``` +Input: rowSum = [3,8], colSum = [4,7] +Output: [[3,0], + [1,7]] +Explanation: +0th row: 3 + 0 = 3 == rowSum[0] +1st row: 1 + 7 = 8 == rowSum[1] +0th column: 3 + 1 = 4 == colSum[0] +1st column: 0 + 7 = 7 == colSum[1] +The row and column sums match, and all matrix elements are non-negative. +Another possible matrix is: [[1,2], + [3,5]] +``` + +Example 2: + +``` +Input: rowSum = [5,7,10], colSum = [8,6,8] +Output: [[0,5,0], + [6,1,0], + [2,0,8]] +``` + +  +**Constraints:** + + + +- `1 <= rowSum.length, colSum.length <= 500` + +- `0 <= rowSum[i], colSum[i] <= 108` + +- `sum(rowSum) == sum(colSum)` + + + +## Solution + +```javascript +/** + * @param {number[]} rowSum + * @param {number[]} colSum + * @return {number[][]} + */ +var restoreMatrix = function(rowSum, colSum) { + var m = rowSum.length; + var n = colSum.length; + var res = Array(m).fill(0).map(() => Array(n).fill(0)); + for (var i = 0; i < m; i++) { + res[i][0] = rowSum[i]; + } + for (var i = 0; i < n - 1; i++) { + for (var j = 0; j < m; j++) { + var num = Math.min(res[j][i], colSum[i]); + res[j][i + 1] = res[j][i] - num; + res[j][i] = num; + colSum[i] -= num; + } + } + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * m). +* Space complexity : O(n * m). diff --git a/1601-1700/1700. Number of Students Unable to Eat Lunch.md b/1601-1700/1700. Number of Students Unable to Eat Lunch.md new file mode 100644 index 0000000..e2e892a --- /dev/null +++ b/1601-1700/1700. Number of Students Unable to Eat Lunch.md @@ -0,0 +1,99 @@ +# 1700. Number of Students Unable to Eat Lunch + +- Difficulty: Easy. +- Related Topics: Array, Stack, Queue, Simulation. +- Similar Questions: Time Needed to Buy Tickets. + +## Problem + +The school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers `0` and `1` respectively. All students stand in a queue. Each student either prefers square or circular sandwiches. + +The number of sandwiches in the cafeteria is equal to the number of students. The sandwiches are placed in a **stack**. At each step: + + + +- If the student at the front of the queue **prefers** the sandwich on the top of the stack, they will **take it** and leave the queue. + +- Otherwise, they will **leave it** and go to the queue's end. + + +This continues until none of the queue students want to take the top sandwich and are thus unable to eat. + +You are given two integer arrays `students` and `sandwiches` where `sandwiches[i]` is the type of the `i​​​​​​th` sandwich in the stack (`i = 0` is the top of the stack) and `students[j]` is the preference of the `j​​​​​​th` student in the initial queue (`j = 0` is the front of the queue). Return **the number of students that are unable to eat.** + +  +Example 1: + +``` +Input: students = [1,1,0,0], sandwiches = [0,1,0,1] +Output: 0 +Explanation: +- Front student leaves the top sandwich and returns to the end of the line making students = [1,0,0,1]. +- Front student leaves the top sandwich and returns to the end of the line making students = [0,0,1,1]. +- Front student takes the top sandwich and leaves the line making students = [0,1,1] and sandwiches = [1,0,1]. +- Front student leaves the top sandwich and returns to the end of the line making students = [1,1,0]. +- Front student takes the top sandwich and leaves the line making students = [1,0] and sandwiches = [0,1]. +- Front student leaves the top sandwich and returns to the end of the line making students = [0,1]. +- Front student takes the top sandwich and leaves the line making students = [1] and sandwiches = [1]. +- Front student takes the top sandwich and leaves the line making students = [] and sandwiches = []. +Hence all students are able to eat. +``` + +Example 2: + +``` +Input: students = [1,1,1,0,0,1], sandwiches = [1,0,0,0,1,1] +Output: 3 +``` + +  +**Constraints:** + + + +- `1 <= students.length, sandwiches.length <= 100` + +- `students.length == sandwiches.length` + +- `sandwiches[i]` is `0` or `1`. + +- `students[i]` is `0` or `1`. + + + +## Solution + +```javascript +/** + * @param {number[]} students + * @param {number[]} sandwiches + * @return {number} + */ +var countStudents = function(students, sandwiches) { + var numOfOnes = 0; + var numOfZeros = 0; + for (var i = 0; i < students.length; i++) { + if (students[i] === 1) numOfOnes++; + else numOfZeros++; + } + for (var j = 0; j < sandwiches.length; j++) { + if (sandwiches[j] === 1) { + if (numOfOnes > 0) numOfOnes--; + else break; + } else { + if (numOfZeros > 0) numOfZeros--; + else break; + } + } + return numOfOnes + numOfZeros; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/1701-1800/1717. Maximum Score From Removing Substrings.md b/1701-1800/1717. Maximum Score From Removing Substrings.md new file mode 100644 index 0000000..d8706fc --- /dev/null +++ b/1701-1800/1717. Maximum Score From Removing Substrings.md @@ -0,0 +1,154 @@ +# 1717. Maximum Score From Removing Substrings + +- Difficulty: Medium. +- Related Topics: String, Stack, Greedy. +- Similar Questions: Count Words Obtained After Adding a Letter. + +## Problem + +You are given a string `s` and two integers `x` and `y`. You can perform two types of operations any number of times. + + + Remove substring `"ab"` and gain `x` points. + + + +- For example, when removing `"ab"` from `"cabxbae"` it becomes `"cxbae"`. + + + Remove substring `"ba"` and gain `y` points. + + +- For example, when removing `"ba"` from `"cabxbae"` it becomes `"cabxe"`. + + + + +Return **the maximum points you can gain after applying the above operations on** `s`. + +  +Example 1: + +``` +Input: s = "cdbcbbaaabab", x = 4, y = 5 +Output: 19 +Explanation: +- Remove the "ba" underlined in "cdbcbbaaabab". Now, s = "cdbcbbaaab" and 5 points are added to the score. +- Remove the "ab" underlined in "cdbcbbaaab". Now, s = "cdbcbbaa" and 4 points are added to the score. +- Remove the "ba" underlined in "cdbcbbaa". Now, s = "cdbcba" and 5 points are added to the score. +- Remove the "ba" underlined in "cdbcba". Now, s = "cdbc" and 5 points are added to the score. +Total score = 5 + 4 + 5 + 5 = 19. +``` + +Example 2: + +``` +Input: s = "aabbaaxybbaabb", x = 5, y = 4 +Output: 20 +``` + +  +**Constraints:** + + + +- `1 <= s.length <= 105` + +- `1 <= x, y <= 104` + +- `s` consists of lowercase English letters. + + + +## Solution 1 + +```javascript +/** + * @param {string} s + * @param {number} x + * @param {number} y + * @return {number} + */ +var maximumGain = function(s, x, y) { + var stack = []; + var score = 0; + var a = x > y ? 'ab' : 'ba'; + var b = x > y ? 'ba' : 'ab'; + var ax = x > y ? x : y; + var bx = x > y ? y : x; + var score = 0; + for (var i = 0; i < s.length; i++) { + if (stack[stack.length - 1] === a[0] && s[i] === a[1]) { + stack.pop(); + score += ax; + } else { + stack.push(s[i]); + } + } + s = stack.join(''); + stack = []; + for (var i = 0; i < s.length; i++) { + if (stack[stack.length - 1] === b[0] && s[i] === b[1]) { + stack.pop(); + score += bx; + } else { + stack.push(s[i]); + } + } + return score; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). + +## Solution 2 + +```javascript +/** + * @param {string} s + * @param {number} x + * @param {number} y + * @return {number} + */ +var maximumGain = function(s, x, y) { + if (y > x) { + return maximumGain(s.split('').reverse(), y, x); + } + var aCount = 0; + var bCount = 0; + var score = 0; + for (var i = 0; i <= s.length; i++) { + if (s[i] === 'a') { + aCount += 1; + } else if (s[i] === 'b') { + if (aCount > 0) { + aCount -= 1; + score += x; + } else { + bCount += 1; + } + } else { + score += Math.min(aCount, bCount) * y; + aCount = 0; + bCount = 0; + } + } + return score; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/1701-1800/1790. Check if One String Swap Can Make Strings Equal.md b/1701-1800/1790. Check if One String Swap Can Make Strings Equal.md new file mode 100644 index 0000000..4bad624 --- /dev/null +++ b/1701-1800/1790. Check if One String Swap Can Make Strings Equal.md @@ -0,0 +1,79 @@ +# 1790. Check if One String Swap Can Make Strings Equal + +- Difficulty: Easy. +- Related Topics: Hash Table, String, Counting. +- Similar Questions: Buddy Strings, Make Number of Distinct Characters Equal. + +## Problem + +You are given two strings `s1` and `s2` of equal length. A **string swap** is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices. + +Return `true` **if it is possible to make both strings equal by performing **at most one string swap **on **exactly one** of the strings. **Otherwise, return `false`. + +  +Example 1: + +``` +Input: s1 = "bank", s2 = "kanb" +Output: true +Explanation: For example, swap the first character with the last character of s2 to make "bank". +``` + +Example 2: + +``` +Input: s1 = "attack", s2 = "defend" +Output: false +Explanation: It is impossible to make them equal with one string swap. +``` + +Example 3: + +``` +Input: s1 = "kelb", s2 = "kelb" +Output: true +Explanation: The two strings are already equal, so no string swap operation is required. +``` + +  +**Constraints:** + + + +- `1 <= s1.length, s2.length <= 100` + +- `s1.length == s2.length` + +- `s1` and `s2` consist of only lowercase English letters. + + + +## Solution + +```javascript +/** + * @param {string} s1 + * @param {string} s2 + * @return {boolean} + */ +var areAlmostEqual = function(s1, s2) { + var diffs = []; + for (var i = 0; i < s1.length; i++) { + if (s1[i] !== s2[i]) diffs.push(i); + } + return diffs.length === 0 || ( + diffs.length === 2 && + s1[diffs[0]] === s2[diffs[1]] && + s1[diffs[1]] === s2[diffs[0]] + ); +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/1901-2000/1937. Maximum Number of Points with Cost.md b/1901-2000/1937. Maximum Number of Points with Cost.md new file mode 100644 index 0000000..a5cbccc --- /dev/null +++ b/1901-2000/1937. Maximum Number of Points with Cost.md @@ -0,0 +1,116 @@ +# 1937. Maximum Number of Points with Cost + +- Difficulty: Medium. +- Related Topics: Array, Dynamic Programming. +- Similar Questions: Minimum Path Sum, Minimize the Difference Between Target and Chosen Elements. + +## Problem + +You are given an `m x n` integer matrix `points` (**0-indexed**). Starting with `0` points, you want to **maximize** the number of points you can get from the matrix. + +To gain points, you must pick one cell in **each row**. Picking the cell at coordinates `(r, c)` will **add** `points[r][c]` to your score. + +However, you will lose points if you pick a cell too far from the cell that you picked in the previous row. For every two adjacent rows `r` and `r + 1` (where `0 <= r < m - 1`), picking cells at coordinates `(r, c1)` and `(r + 1, c2)` will **subtract** `abs(c1 - c2)` from your score. + +Return **the **maximum** number of points you can achieve**. + +`abs(x)` is defined as: + + + +- `x` for `x >= 0`. + +- `-x` for `x < 0`. + + +  +Example 1:** ** + +![](https://assets.leetcode.com/uploads/2021/07/12/screenshot-2021-07-12-at-13-40-26-diagram-drawio-diagrams-net.png) + +``` +Input: points = [[1,2,3],[1,5,1],[3,1,1]] +Output: 9 +Explanation: +The blue cells denote the optimal cells to pick, which have coordinates (0, 2), (1, 1), and (2, 0). +You add 3 + 5 + 3 = 11 to your score. +However, you must subtract abs(2 - 1) + abs(1 - 0) = 2 from your score. +Your final score is 11 - 2 = 9. +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2021/07/12/screenshot-2021-07-12-at-13-42-14-diagram-drawio-diagrams-net.png) + +``` +Input: points = [[1,5],[2,3],[4,2]] +Output: 11 +Explanation: +The blue cells denote the optimal cells to pick, which have coordinates (0, 1), (1, 1), and (2, 0). +You add 5 + 3 + 4 = 12 to your score. +However, you must subtract abs(1 - 1) + abs(1 - 0) = 1 from your score. +Your final score is 12 - 1 = 11. +``` + +  +**Constraints:** + + + +- `m == points.length` + +- `n == points[r].length` + +- `1 <= m, n <= 105` + +- `1 <= m * n <= 105` + +- `0 <= points[r][c] <= 105` + + + +## Solution + +```javascript +/** + * @param {number[][]} points + * @return {number} + */ +var maxPoints = function(points) { + var m = points.length; + var n = points[0].length; + var maxArr = points[m - 1]; + for (var i = m - 2; i >= 0; i--) { + var [prefixMaxArr, suffixMaxArr] = getMaxArr(maxArr); + for (var j = 0; j < n; j++) { + maxArr[j] = points[i][j] + Math.max(prefixMaxArr[j] - j, suffixMaxArr[j] + j); + } + } + return Math.max(...maxArr); +}; + +var getMaxArr = function(arr) { + var prefixMaxArr = Array(arr.length); + var max = Number.MIN_SAFE_INTEGER; + for (var i = 0; i < arr.length; i++) { + max = Math.max(max, arr[i] + i); + prefixMaxArr[i] = max; + } + var suffixMaxArr = Array(arr.length); + max = Number.MIN_SAFE_INTEGER; + for (var i = arr.length - 1; i >= 0; i--) { + max = Math.max(max, arr[i] - i); + suffixMaxArr[i] = max; + } + return [prefixMaxArr, suffixMaxArr]; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(m * n). +* Space complexity : O(n). diff --git a/1901-2000/1971. Find if Path Exists in Graph.md b/1901-2000/1971. Find if Path Exists in Graph.md new file mode 100644 index 0000000..a180eaa --- /dev/null +++ b/1901-2000/1971. Find if Path Exists in Graph.md @@ -0,0 +1,101 @@ +# 1971. Find if Path Exists in Graph + +- Difficulty: Easy. +- Related Topics: Depth-First Search, Breadth-First Search, Union Find, Graph. +- Similar Questions: Valid Arrangement of Pairs, Paths in Maze That Lead to Same Room. + +## Problem + +There is a **bi-directional** graph with `n` vertices, where each vertex is labeled from `0` to `n - 1` (**inclusive**). The edges in the graph are represented as a 2D integer array `edges`, where each `edges[i] = [ui, vi]` denotes a bi-directional edge between vertex `ui` and vertex `vi`. Every vertex pair is connected by **at most one** edge, and no vertex has an edge to itself. + +You want to determine if there is a **valid path** that exists from vertex `source` to vertex `destination`. + +Given `edges` and the integers `n`, `source`, and `destination`, return `true`** if there is a **valid path** from **`source`** to **`destination`**, or **`false`** otherwise****.** + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2021/08/14/validpath-ex1.png) + +``` +Input: n = 3, edges = [[0,1],[1,2],[2,0]], source = 0, destination = 2 +Output: true +Explanation: There are two paths from vertex 0 to vertex 2: +- 0 → 1 → 2 +- 0 → 2 +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2021/08/14/validpath-ex2.png) + +``` +Input: n = 6, edges = [[0,1],[0,2],[3,5],[5,4],[4,3]], source = 0, destination = 5 +Output: false +Explanation: There is no path from vertex 0 to vertex 5. +``` + +  +**Constraints:** + + + +- `1 <= n <= 2 * 105` + +- `0 <= edges.length <= 2 * 105` + +- `edges[i].length == 2` + +- `0 <= ui, vi <= n - 1` + +- `ui != vi` + +- `0 <= source, destination <= n - 1` + +- There are no duplicate edges. + +- There are no self edges. + + + +## Solution + +```javascript +/** + * @param {number} n + * @param {number[][]} edges + * @param {number} source + * @param {number} destination + * @return {boolean} + */ +var validPath = function(n, edges, source, destination) { + var dp = Array(n); + var map = Array(n).fill(0).map(() => []); + for (var i = 0; i < edges.length; i++) { + map[edges[i][0]].push(edges[i][1]); + map[edges[i][1]].push(edges[i][0]); + } + var dfs = function(i) { + if (i === destination) return true; + if (dp[i] !== undefined) return dp[i]; + dp[i] = false; + for (var j = 0; j < map[i].length; j++) { + if (dfs(map[i][j])) { + dp[i] = true; + break; + } + } + return dp[i]; + }; + return dfs(source); +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/1901-2000/2000. Reverse Prefix of Word.md b/1901-2000/2000. Reverse Prefix of Word.md new file mode 100644 index 0000000..57f7a57 --- /dev/null +++ b/1901-2000/2000. Reverse Prefix of Word.md @@ -0,0 +1,87 @@ +# 2000. Reverse Prefix of Word + +- Difficulty: Easy. +- Related Topics: Two Pointers, String. +- Similar Questions: . + +## Problem + +Given a **0-indexed** string `word` and a character `ch`, **reverse** the segment of `word` that starts at index `0` and ends at the index of the **first occurrence** of `ch` (**inclusive**). If the character `ch` does not exist in `word`, do nothing. + + + +- For example, if `word = "abcdefd"` and `ch = "d"`, then you should **reverse** the segment that starts at `0` and ends at `3` (**inclusive**). The resulting string will be `"dcbaefd"`. + + +Return **the resulting string**. + +  +Example 1: + +``` +Input: word = "abcdefd", ch = "d" +Output: "dcbaefd" +Explanation: The first occurrence of "d" is at index 3. +Reverse the part of word from 0 to 3 (inclusive), the resulting string is "dcbaefd". +``` + +Example 2: + +``` +Input: word = "xyxzxe", ch = "z" +Output: "zxyxxe" +Explanation: The first and only occurrence of "z" is at index 3. +Reverse the part of word from 0 to 3 (inclusive), the resulting string is "zxyxxe". +``` + +Example 3: + +``` +Input: word = "abcd", ch = "z" +Output: "abcd" +Explanation: "z" does not exist in word. +You should not do any reverse operation, the resulting string is "abcd". +``` + +  +**Constraints:** + + + +- `1 <= word.length <= 250` + +- `word` consists of lowercase English letters. + +- `ch` is a lowercase English letter. + + + +## Solution + +```javascript +/** + * @param {string} word + * @param {character} ch + * @return {string} + */ +var reversePrefix = function(word, ch) { + var index = word.indexOf(ch); + if (index === -1) return word; + var arr = word.split(''); + for (var i = 0; i < index / 2; i++) { + var tmp = arr[i]; + arr[i] = arr[index - i]; + arr[index - i] = tmp; + } + return arr.join(''); +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/2001-2100/2053. Kth Distinct String in an Array.md b/2001-2100/2053. Kth Distinct String in an Array.md new file mode 100644 index 0000000..a06e3c5 --- /dev/null +++ b/2001-2100/2053. Kth Distinct String in an Array.md @@ -0,0 +1,89 @@ +# 2053. Kth Distinct String in an Array + +- Difficulty: Easy. +- Related Topics: Array, Hash Table, String, Counting. +- Similar Questions: Count Common Words With One Occurrence. + +## Problem + +A **distinct string** is a string that is present only **once** in an array. + +Given an array of strings `arr`, and an integer `k`, return **the **`kth`** **distinct string** present in **`arr`. If there are **fewer** than `k` distinct strings, return **an **empty string ****`""`. + +Note that the strings are considered in the **order in which they appear** in the array. + +  +Example 1: + +``` +Input: arr = ["d","b","c","b","c","a"], k = 2 +Output: "a" +Explanation: +The only distinct strings in arr are "d" and "a". +"d" appears 1st, so it is the 1st distinct string. +"a" appears 2nd, so it is the 2nd distinct string. +Since k == 2, "a" is returned. +``` + +Example 2: + +``` +Input: arr = ["aaa","aa","a"], k = 1 +Output: "aaa" +Explanation: +All strings in arr are distinct, so the 1st string "aaa" is returned. +``` + +Example 3: + +``` +Input: arr = ["a","b","a"], k = 3 +Output: "" +Explanation: +The only distinct string is "b". Since there are fewer than 3 distinct strings, we return an empty string "". +``` + +  +**Constraints:** + + + +- `1 <= k <= arr.length <= 1000` + +- `1 <= arr[i].length <= 5` + +- `arr[i]` consists of lowercase English letters. + + + +## Solution + +```javascript +/** + * @param {string[]} arr + * @param {number} k + * @return {string} + */ +var kthDistinct = function(arr, k) { + var map = {}; + for (var i = 0; i < arr.length; i++) { + map[arr[i]] = (map[arr[i]] || 0) + 1; + } + for (var j = 0; j < arr.length; j++) { + if (map[arr[j]] === 1) { + k--; + if (k === 0) return arr[j]; + } + } + return ''; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/2001-2100/2058. Find the Minimum and Maximum Number of Nodes Between Critical Points.md b/2001-2100/2058. Find the Minimum and Maximum Number of Nodes Between Critical Points.md new file mode 100644 index 0000000..1694447 --- /dev/null +++ b/2001-2100/2058. Find the Minimum and Maximum Number of Nodes Between Critical Points.md @@ -0,0 +1,116 @@ +# 2058. Find the Minimum and Maximum Number of Nodes Between Critical Points + +- Difficulty: Medium. +- Related Topics: Linked List. +- Similar Questions: . + +## Problem + +A **critical point** in a linked list is defined as **either** a **local maxima** or a **local minima**. + +A node is a **local maxima** if the current node has a value **strictly greater** than the previous node and the next node. + +A node is a **local minima** if the current node has a value **strictly smaller** than the previous node and the next node. + +Note that a node can only be a local maxima/minima if there exists **both** a previous node and a next node. + +Given a linked list `head`, return **an array of length 2 containing **`[minDistance, maxDistance]`** where **`minDistance`** is the **minimum distance** between **any two distinct** critical points and **`maxDistance`** is the **maximum distance** between **any two distinct** critical points. If there are **fewer** than two critical points, return **`[-1, -1]`. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2021/10/13/a1.png) + +``` +Input: head = [3,1] +Output: [-1,-1] +Explanation: There are no critical points in [3,1]. +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2021/10/13/a2.png) + +``` +Input: head = [5,3,1,2,5,1,2] +Output: [1,3] +Explanation: There are three critical points: +- [5,3,1,2,5,1,2]: The third node is a local minima because 1 is less than 3 and 2. +- [5,3,1,2,5,1,2]: The fifth node is a local maxima because 5 is greater than 2 and 1. +- [5,3,1,2,5,1,2]: The sixth node is a local minima because 1 is less than 5 and 2. +The minimum distance is between the fifth and the sixth node. minDistance = 6 - 5 = 1. +The maximum distance is between the third and the sixth node. maxDistance = 6 - 3 = 3. +``` + +Example 3: + +![](https://assets.leetcode.com/uploads/2021/10/14/a5.png) + +``` +Input: head = [1,3,2,2,3,2,2,2,7] +Output: [3,3] +Explanation: There are two critical points: +- [1,3,2,2,3,2,2,2,7]: The second node is a local maxima because 3 is greater than 1 and 2. +- [1,3,2,2,3,2,2,2,7]: The fifth node is a local maxima because 3 is greater than 2 and 2. +Both the minimum and maximum distances are between the second and the fifth node. +Thus, minDistance and maxDistance is 5 - 2 = 3. +Note that the last node is not considered a local maxima because it does not have a next node. +``` + +  +**Constraints:** + + + +- The number of nodes in the list is in the range `[2, 105]`. + +- `1 <= Node.val <= 105` + + + +## Solution + +```javascript +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @return {number[]} + */ +var nodesBetweenCriticalPoints = function(head) { + var firstPoint = -1; + var lastPoint = -1; + var last = null; + var now = head; + var i = 0; + var minDistance = Number.MAX_SAFE_INTEGER; + while (now) { + if (last && now.next && ((now.val > last.val && now.val > now.next.val) || (now.val < last.val && now.val < now.next.val))) { + if (firstPoint === -1) firstPoint = i; + if (lastPoint !== -1) minDistance = Math.min(minDistance, i - lastPoint); + lastPoint = i; + } + last = now; + now = now.next; + i += 1; + } + if (firstPoint !== -1 && lastPoint !== -1 && lastPoint !== firstPoint) { + return [minDistance, lastPoint - firstPoint]; + } + return [-1, -1]; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/2001-2100/2096. Step-By-Step Directions From a Binary Tree Node to Another.md b/2001-2100/2096. Step-By-Step Directions From a Binary Tree Node to Another.md new file mode 100644 index 0000000..15c0fed --- /dev/null +++ b/2001-2100/2096. Step-By-Step Directions From a Binary Tree Node to Another.md @@ -0,0 +1,129 @@ +# 2096. Step-By-Step Directions From a Binary Tree Node to Another + +- Difficulty: Medium. +- Related Topics: String, Tree, Depth-First Search, Binary Tree. +- Similar Questions: Path Sum II, Lowest Common Ancestor of a Binary Tree, Binary Tree Paths, Find Distance in a Binary Tree. + +## Problem + +You are given the `root` of a **binary tree** with `n` nodes. Each node is uniquely assigned a value from `1` to `n`. You are also given an integer `startValue` representing the value of the start node `s`, and a different integer `destValue` representing the value of the destination node `t`. + +Find the **shortest path** starting from node `s` and ending at node `t`. Generate step-by-step directions of such path as a string consisting of only the **uppercase** letters `'L'`, `'R'`, and `'U'`. Each letter indicates a specific direction: + + + +- `'L'` means to go from a node to its **left child** node. + +- `'R'` means to go from a node to its **right child** node. + +- `'U'` means to go from a node to its **parent** node. + + +Return **the step-by-step directions of the **shortest path** from node **`s`** to node** `t`. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2021/11/15/eg1.png) + +``` +Input: root = [5,1,2,3,null,6,4], startValue = 3, destValue = 6 +Output: "UURL" +Explanation: The shortest path is: 3 → 1 → 5 → 2 → 6. +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2021/11/15/eg2.png) + +``` +Input: root = [2,1], startValue = 2, destValue = 1 +Output: "L" +Explanation: The shortest path is: 2 → 1. +``` + +  +**Constraints:** + + + +- The number of nodes in the tree is `n`. + +- `2 <= n <= 105` + +- `1 <= Node.val <= n` + +- All the values in the tree are **unique**. + +- `1 <= startValue, destValue <= n` + +- `startValue != destValue` + + + +## Solution + +```javascript +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @param {number} startValue + * @param {number} destValue + * @return {string} + */ +var getDirections = function(root, startValue, destValue) { + var findLCA = function(node) { + if (!node) return false; + if (node.val === startValue || node.val === destValue) { + return node; + } + var left = findLCA(node.left); + var right = findLCA(node.right); + return (left && right) ? node : (left || right || false); + }; + var findStart = function(node) { + if (!node) return null; + if (node.val === startValue) return ''; + + var left = findStart(node.left); + if (left !== null) return left + 'U'; + + var right = findStart(node.right); + if (right !== null) return right + 'U'; + + return null; + }; + var findDest = function(node) { + if (!node) return null; + if (node.val === destValue) return ''; + + var left = findDest(node.left); + if (left !== null) return 'L' + left; + + var right = findDest(node.right); + if (right !== null) return 'R' + right; + + return null; + }; + var LCA = findLCA(root); + var startPath = findStart(LCA); + var destPath = findDest(LCA); + return startPath + destPath; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/201-300/205. Isomorphic Strings.md b/201-300/205. Isomorphic Strings.md new file mode 100644 index 0000000..bcc68e4 --- /dev/null +++ b/201-300/205. Isomorphic Strings.md @@ -0,0 +1,74 @@ +# 205. Isomorphic Strings + +- Difficulty: Easy. +- Related Topics: Hash Table, String. +- Similar Questions: Word Pattern. + +## Problem + +Given two strings `s` and `t`, **determine if they are isomorphic**. + +Two strings `s` and `t` are isomorphic if the characters in `s` can be replaced to get `t`. + +All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself. + +  +Example 1: +``` +Input: s = "egg", t = "add" +Output: true +```Example 2: +``` +Input: s = "foo", t = "bar" +Output: false +```Example 3: +``` +Input: s = "paper", t = "title" +Output: true +``` +  +**Constraints:** + + + +- `1 <= s.length <= 5 * 104` + +- `t.length == s.length` + +- `s` and `t` consist of any valid ascii character. + + + +## Solution + +```javascript +/** + * @param {string} s + * @param {string} t + * @return {boolean} + */ +var isIsomorphic = function(s, t) { + if (s.length !== t.length) return false; + var map = {}; + var used = {}; + for (var i = 0; i < s.length; i++) { + if (map[s[i]]) { + if (map[s[i]] !== t[i]) return false; + } else { + if (used[t[i]]) return false; + used[t[i]] = true; + map[s[i]] = t[i]; + } + } + return true; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/201-300/210. Course Schedule II.md b/201-300/210. Course Schedule II.md new file mode 100644 index 0000000..833c296 --- /dev/null +++ b/201-300/210. Course Schedule II.md @@ -0,0 +1,101 @@ +# 210. Course Schedule II + +- Difficulty: Medium. +- Related Topics: Depth-First Search, Breadth-First Search, Graph, Topological Sort. +- Similar Questions: Course Schedule, Alien Dictionary, Minimum Height Trees, Sequence Reconstruction, Course Schedule III, Parallel Courses, Find All Possible Recipes from Given Supplies, Build a Matrix With Conditions, Sort Array by Moving Items to Empty Space. + +## Problem + +There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you **must** take course `bi` first if you want to take course `ai`. + + + +- For example, the pair `[0, 1]`, indicates that to take course `0` you have to first take course `1`. + + +Return **the ordering of courses you should take to finish all courses**. If there are many valid answers, return **any** of them. If it is impossible to finish all courses, return **an empty array**. + +  +Example 1: + +``` +Input: numCourses = 2, prerequisites = [[1,0]] +Output: [0,1] +Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1]. +``` + +Example 2: + +``` +Input: numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]] +Output: [0,2,1,3] +Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. +So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3]. +``` + +Example 3: + +``` +Input: numCourses = 1, prerequisites = [] +Output: [0] +``` + +  +**Constraints:** + + + +- `1 <= numCourses <= 2000` + +- `0 <= prerequisites.length <= numCourses * (numCourses - 1)` + +- `prerequisites[i].length == 2` + +- `0 <= ai, bi < numCourses` + +- `ai != bi` + +- All the pairs `[ai, bi]` are **distinct**. + + + +## Solution + +```javascript +/** + * @param {number} numCourses + * @param {number[][]} prerequisites + * @return {number[]} + */ +var findOrder = function(numCourses, prerequisites) { + var requiredByMap = Array(numCourses).fill(0).map(() => []); + var requiringMap = Array(numCourses).fill(0); + for (var i = 0; i < prerequisites.length; i++) { + requiringMap[prerequisites[i][0]]++; + requiredByMap[prerequisites[i][1]].push(prerequisites[i][0]); + } + var queue = []; + for (var j = 0; j < numCourses; j++) { + requiringMap[j] === 0 && queue.push(j); + } + var res = []; + while (queue.length) { + var course = queue.pop(); + res.push(course); + for (var k = 0; k < requiredByMap[course].length; k++) { + requiringMap[requiredByMap[course][k]]--; + requiringMap[requiredByMap[course][k]] === 0 && queue.push(requiredByMap[course][k]); + } + } + return res.length === numCourses ? res : []; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/201-300/219. Contains Duplicate II.md b/201-300/219. Contains Duplicate II.md new file mode 100644 index 0000000..841ded0 --- /dev/null +++ b/201-300/219. Contains Duplicate II.md @@ -0,0 +1,71 @@ +# 219. Contains Duplicate II + +- Difficulty: Easy. +- Related Topics: Array, Hash Table, Sliding Window. +- Similar Questions: Contains Duplicate, Contains Duplicate III. + +## Problem + +Given an integer array `nums` and an integer `k`, return `true` **if there are two **distinct indices** **`i`** and **`j`** in the array such that **`nums[i] == nums[j]`** and **`abs(i - j) <= k`. + +  +Example 1: + +``` +Input: nums = [1,2,3,1], k = 3 +Output: true +``` + +Example 2: + +``` +Input: nums = [1,0,1,1], k = 1 +Output: true +``` + +Example 3: + +``` +Input: nums = [1,2,3,1,2,3], k = 2 +Output: false +``` + +  +**Constraints:** + + + +- `1 <= nums.length <= 105` + +- `-109 <= nums[i] <= 109` + +- `0 <= k <= 105` + + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @param {number} k + * @return {boolean} + */ +var containsNearbyDuplicate = function(nums, k) { + var map = {}; + for (var i = 0; i < nums.length; i++) { + if (map[nums[i]] !== undefined && i - map[nums[i]] <= k) return true; + map[nums[i]] = i; + } + return false; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/201-300/228. Summary Ranges.md b/201-300/228. Summary Ranges.md new file mode 100644 index 0000000..3a01a9c --- /dev/null +++ b/201-300/228. Summary Ranges.md @@ -0,0 +1,87 @@ +# 228. Summary Ranges + +- Difficulty: Easy. +- Related Topics: Array. +- Similar Questions: Missing Ranges, Data Stream as Disjoint Intervals, Find Maximal Uncovered Ranges. + +## Problem + +You are given a **sorted unique** integer array `nums`. + +A **range** `[a,b]` is the set of all integers from `a` to `b` (inclusive). + +Return **the **smallest sorted** list of ranges that **cover all the numbers in the array exactly****. That is, each element of `nums` is covered by exactly one of the ranges, and there is no integer `x` such that `x` is in one of the ranges but not in `nums`. + +Each range `[a,b]` in the list should be output as: + + + +- `"a->b"` if `a != b` + +- `"a"` if `a == b` + + +  +Example 1: + +``` +Input: nums = [0,1,2,4,5,7] +Output: ["0->2","4->5","7"] +Explanation: The ranges are: +[0,2] --> "0->2" +[4,5] --> "4->5" +[7,7] --> "7" +``` + +Example 2: + +``` +Input: nums = [0,2,3,4,6,8,9] +Output: ["0","2->4","6","8->9"] +Explanation: The ranges are: +[0,0] --> "0" +[2,4] --> "2->4" +[6,6] --> "6" +[8,9] --> "8->9" +``` + +  +**Constraints:** + + + +- `0 <= nums.length <= 20` + +- `-231 <= nums[i] <= 231 - 1` + +- All the values of `nums` are **unique**. + +- `nums` is sorted in ascending order. + + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @return {string[]} + */ +var summaryRanges = function(nums) { + var res = []; + for (var i = 0; i < nums.length; i++) { + if (i === 0 || nums[i] !== nums[i - 1] + 1) res.push(`${nums[i]}`); + else if (i === nums.length - 1 || nums[i] !== nums[i + 1] - 1) res[res.length - 1] += `->${nums[i]}`; + } + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/201-300/237. Delete Node in a Linked List.md b/201-300/237. Delete Node in a Linked List.md new file mode 100644 index 0000000..d3fd1f7 --- /dev/null +++ b/201-300/237. Delete Node in a Linked List.md @@ -0,0 +1,106 @@ +# 237. Delete Node in a Linked List + +- Difficulty: Medium. +- Related Topics: Linked List. +- Similar Questions: Remove Linked List Elements, Remove Nodes From Linked List. + +## Problem + +There is a singly-linked list `head` and we want to delete a node `node` in it. + +You are given the node to be deleted `node`. You will **not be given access** to the first node of `head`. + +All the values of the linked list are **unique**, and it is guaranteed that the given node `node` is not the last node in the linked list. + +Delete the given node. Note that by deleting the node, we do not mean removing it from memory. We mean: + + + +- The value of the given node should not exist in the linked list. + +- The number of nodes in the linked list should decrease by one. + +- All the values before `node` should be in the same order. + +- All the values after `node` should be in the same order. + + +**Custom testing:** + + + +- For the input, you should provide the entire linked list `head` and the node to be given `node`. `node` should not be the last node of the list and should be an actual node in the list. + +- We will build the linked list and pass the node to your function. + +- The output will be the entire list after calling your function. + + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2020/09/01/node1.jpg) + +``` +Input: head = [4,5,1,9], node = 5 +Output: [4,1,9] +Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function. +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2020/09/01/node2.jpg) + +``` +Input: head = [4,5,1,9], node = 1 +Output: [4,5,9] +Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function. +``` + +  +**Constraints:** + + + +- The number of the nodes in the given list is in the range `[2, 1000]`. + +- `-1000 <= Node.val <= 1000` + +- The value of each node in the list is **unique**. + +- The `node` to be deleted is **in the list** and is **not a tail** node. + + + +## Solution + +```javascript +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ +/** + * @param {ListNode} node + * @return {void} Do not return anything, modify node in-place instead. + */ +var deleteNode = function(node) { + while (node.next.next) { + node.val = node.next.val; + node = node.next; + } + node.val = node.next.val; + node.next = null; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/201-300/273. Integer to English Words.md b/201-300/273. Integer to English Words.md new file mode 100644 index 0000000..357a494 --- /dev/null +++ b/201-300/273. Integer to English Words.md @@ -0,0 +1,132 @@ +# 273. Integer to English Words + +- Difficulty: Hard. +- Related Topics: Math, String, Recursion. +- Similar Questions: Integer to Roman. + +## Problem + +Convert a non-negative integer `num` to its English words representation. + +  +Example 1: + +``` +Input: num = 123 +Output: "One Hundred Twenty Three" +``` + +Example 2: + +``` +Input: num = 12345 +Output: "Twelve Thousand Three Hundred Forty Five" +``` + +Example 3: + +``` +Input: num = 1234567 +Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven" +``` + +  +**Constraints:** + + + +- `0 <= num <= 231 - 1` + + + +## Solution + +```javascript +/** + * @param {number} num + * @return {string} + */ +var numberToWords = function(num) { + if (num === 0) return 'Zero'; + var words1 = [ + 'One', + 'Two', + 'Three', + 'Four', + "Five", + "Six", + 'Seven', + 'Eight', + 'Nine', + ]; + var words2 = [ + 'Ten', + 'Eleven', + 'Twelve', + 'Thirteen', + 'Fourteen', + 'Fifteen', + 'Sixteen', + 'Seventeen', + 'Eighteen', + 'Nineteen', + ]; + var words3 = [ + 'Ten', + 'Twenty', + 'Thirty', + 'Forty', + 'Fifty', + 'Sixty', + 'Seventy', + 'Eighty', + 'Ninety', + ]; + var getStr = function(number) { + var res = []; + var num1 = Math.floor(number / 100); + if (num1 > 0) { + res.push(`${words1[num1 - 1]} Hundred`); + } + number %= 100; + if (number >= 10 && number <= 19) { + res.push(words2[number - 10]); + } else { + var num2 = Math.floor(number / 10); + if (num2 > 0) { + res.push(words3[num2 - 1]); + } + number %= 10; + if (number > 0) { + res.push(words1[number - 1]); + } + } + return res.join(' '); + }; + var res = []; + [ + [Math.pow(10, 9), 'Billion'], + [Math.pow(10, 6), 'Million'], + [Math.pow(10, 3), 'Thousand'], + ].forEach(item => { + var num1 = Math.floor(num / item[0]); + if (num1 > 0) { + res.push(`${getStr(num1)} ${item[1]}`); + } + num %= item[0]; + }); + if (num > 0) { + res.push(getStr(num)); + } + return res.join(' '); +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(log(n)). +* Space complexity : O(log(n)). diff --git a/201-300/289. Game of Life.md b/201-300/289. Game of Life.md new file mode 100644 index 0000000..ae130f1 --- /dev/null +++ b/201-300/289. Game of Life.md @@ -0,0 +1,133 @@ +# 289. Game of Life + +- Difficulty: Medium. +- Related Topics: Array, Matrix, Simulation. +- Similar Questions: Set Matrix Zeroes. + +## Problem + +According to Wikipedia's article: "The **Game of Life**, also known simply as **Life**, is a cellular automaton devised by the British mathematician John Horton Conway in 1970." + +The board is made up of an `m x n` grid of cells, where each cell has an initial state: **live** (represented by a `1`) or **dead** (represented by a `0`). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article): + + + +- Any live cell with fewer than two live neighbors dies as if caused by under-population. + +- Any live cell with two or three live neighbors lives on to the next generation. + +- Any live cell with more than three live neighbors dies, as if by over-population. + +- Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction. + + +The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously. Given the current state of the `m x n` grid `board`, return **the next state**. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2020/12/26/grid1.jpg) + +``` +Input: board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]] +Output: [[0,0,0],[1,0,1],[0,1,1],[0,1,0]] +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2020/12/26/grid2.jpg) + +``` +Input: board = [[1,1],[1,0]] +Output: [[1,1],[1,1]] +``` + +  +**Constraints:** + + + +- `m == board.length` + +- `n == board[i].length` + +- `1 <= m, n <= 25` + +- `board[i][j]` is `0` or `1`. + + +  +**Follow up:** + + + +- Could you solve it in-place? Remember that the board needs to be updated simultaneously: You cannot update some cells first and then use their updated values to update other cells. + +- In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches upon the border of the array (i.e., live cells reach the border). How would you address these problems? + + + +## Solution + +```javascript +/** + * @param {number[][]} board + * @return {void} Do not return anything, modify board in-place instead. + */ +var gameOfLife = function(board) { + for (var i = 0; i < board.length; i++) { + for (var j = 0; j < board[i].length; j++) { + var count = countLiveneighbors(board, i, j); + if (board[i][j] === 1) { + if (count < 2 || count > 3) { + board[i][j] = 2; + } + } else { + if (count === 3) { + board[i][j] = 3; + } + } + } + } + for (var i = 0; i < board.length; i++) { + for (var j = 0; j < board[i].length; j++) { + if (board[i][j] === 2) { + board[i][j] = 0; + } else if (board[i][j] === 3) { + board[i][j] = 1; + } + } + } +}; + +var countLiveneighbors = function(board, i, j) { + var directions = [ + [0, 1], + [0, -1], + [1, 0], + [-1, 0], + [1, 1], + [1, -1], + [-1, 1], + [-1, -1], + ]; + var count = 0; + for (var m = 0; m < directions.length; m++) { + var [y, x] = directions[m]; + if (!board[i + y]) continue; + if (board[i + y][j + x] === 1 || board[i + y][j + x] === 2) { + count += 1; + } + } + return count; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/201-300/290. Word Pattern.md b/201-300/290. Word Pattern.md new file mode 100644 index 0000000..4c4ba4c --- /dev/null +++ b/201-300/290. Word Pattern.md @@ -0,0 +1,87 @@ +# 290. Word Pattern + +- Difficulty: Easy. +- Related Topics: Hash Table, String. +- Similar Questions: Isomorphic Strings, Word Pattern II. + +## Problem + +Given a `pattern` and a string `s`, find if `s` follows the same pattern. + +Here **follow** means a full match, such that there is a bijection between a letter in `pattern` and a **non-empty** word in `s`. + +  +Example 1: + +``` +Input: pattern = "abba", s = "dog cat cat dog" +Output: true +``` + +Example 2: + +``` +Input: pattern = "abba", s = "dog cat cat fish" +Output: false +``` + +Example 3: + +``` +Input: pattern = "aaaa", s = "dog cat cat dog" +Output: false +``` + +  +**Constraints:** + + + +- `1 <= pattern.length <= 300` + +- `pattern` contains only lower-case English letters. + +- `1 <= s.length <= 3000` + +- `s` contains only lowercase English letters and spaces `' '`. + +- `s` **does not contain** any leading or trailing spaces. + +- All the words in `s` are separated by a **single space**. + + + +## Solution + +```javascript +/** + * @param {string} pattern + * @param {string} s + * @return {boolean} + */ +var wordPattern = function(pattern, s) { + var map = {}; + var used = new Map(); + var words = s.split(' '); + if (pattern.length !== words.length) return false; + for (var i = 0; i < pattern.length; i++) { + if (!map[pattern[i]]) { + if (used.has(words[i])) return false; + used.set(words[i], true); + map[pattern[i]] = words[i]; + } else if (map[pattern[i]] !== words[i]) { + return false; + } + } + return true; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/2101-2200/2181. Merge Nodes in Between Zeros.md b/2101-2200/2181. Merge Nodes in Between Zeros.md new file mode 100644 index 0000000..f367c9a --- /dev/null +++ b/2101-2200/2181. Merge Nodes in Between Zeros.md @@ -0,0 +1,96 @@ +# 2181. Merge Nodes in Between Zeros + +- Difficulty: Medium. +- Related Topics: Linked List, Simulation. +- Similar Questions: Linked List Components. + +## Problem + +You are given the `head` of a linked list, which contains a series of integers **separated** by `0`'s. The **beginning** and **end** of the linked list will have `Node.val == 0`. + +For **every **two consecutive `0`'s, **merge** all the nodes lying in between them into a single node whose value is the **sum** of all the merged nodes. The modified list should not contain any `0`'s. + +Return **the** `head` **of the modified linked list**. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2022/02/02/ex1-1.png) + +``` +Input: head = [0,3,1,0,4,5,2,0] +Output: [4,11] +Explanation: +The above figure represents the given linked list. The modified list contains +- The sum of the nodes marked in green: 3 + 1 = 4. +- The sum of the nodes marked in red: 4 + 5 + 2 = 11. +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2022/02/02/ex2-1.png) + +``` +Input: head = [0,1,0,3,0,2,2,0] +Output: [1,3,4] +Explanation: +The above figure represents the given linked list. The modified list contains +- The sum of the nodes marked in green: 1 = 1. +- The sum of the nodes marked in red: 3 = 3. +- The sum of the nodes marked in yellow: 2 + 2 = 4. +``` + +  +**Constraints:** + + + +- The number of nodes in the list is in the range `[3, 2 * 105]`. + +- `0 <= Node.val <= 1000` + +- There are **no** two consecutive nodes with `Node.val == 0`. + +- The **beginning** and **end** of the linked list have `Node.val == 0`. + + + +## Solution + +```javascript +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ +var mergeNodes = function(head) { + var newHead = new ListNode(); + var resNow = newHead; + var now = head; + while (now) { + if (now.val === 0 && now.next) { + resNow.next = new ListNode(); + resNow = resNow.next; + } else if (now.val !== 0) { + resNow.val += now.val; + } + now = now.next; + } + return newHead.next; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/2301-2400/2392. Build a Matrix With Conditions.md b/2301-2400/2392. Build a Matrix With Conditions.md new file mode 100644 index 0000000..63d3707 --- /dev/null +++ b/2301-2400/2392. Build a Matrix With Conditions.md @@ -0,0 +1,138 @@ +# 2392. Build a Matrix With Conditions + +- Difficulty: Hard. +- Related Topics: Array, Graph, Topological Sort, Matrix. +- Similar Questions: Course Schedule, Course Schedule II, Find Eventual Safe States, Loud and Rich. + +## Problem + +You are given a **positive** integer `k`. You are also given: + + + +- a 2D integer array `rowConditions` of size `n` where `rowConditions[i] = [abovei, belowi]`, and + +- a 2D integer array `colConditions` of size `m` where `colConditions[i] = [lefti, righti]`. + + +The two arrays contain integers from `1` to `k`. + +You have to build a `k x k` matrix that contains each of the numbers from `1` to `k` **exactly once**. The remaining cells should have the value `0`. + +The matrix should also satisfy the following conditions: + + + +- The number `abovei` should appear in a **row** that is strictly **above** the row at which the number `belowi` appears for all `i` from `0` to `n - 1`. + +- The number `lefti` should appear in a **column** that is strictly **left** of the column at which the number `righti` appears for all `i` from `0` to `m - 1`. + + +Return ****any** matrix that satisfies the conditions**. If no answer exists, return an empty matrix. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2022/07/06/gridosdrawio.png) + +``` +Input: k = 3, rowConditions = [[1,2],[3,2]], colConditions = [[2,1],[3,2]] +Output: [[3,0,0],[0,0,1],[0,2,0]] +Explanation: The diagram above shows a valid example of a matrix that satisfies all the conditions. +The row conditions are the following: +- Number 1 is in row 1, and number 2 is in row 2, so 1 is above 2 in the matrix. +- Number 3 is in row 0, and number 2 is in row 2, so 3 is above 2 in the matrix. +The column conditions are the following: +- Number 2 is in column 1, and number 1 is in column 2, so 2 is left of 1 in the matrix. +- Number 3 is in column 0, and number 2 is in column 1, so 3 is left of 2 in the matrix. +Note that there may be multiple correct answers. +``` + +Example 2: + +``` +Input: k = 3, rowConditions = [[1,2],[2,3],[3,1],[2,3]], colConditions = [[2,1]] +Output: [] +Explanation: From the first two conditions, 3 has to be below 1 but the third conditions needs 3 to be above 1 to be satisfied. +No matrix can satisfy all the conditions, so we return the empty matrix. +``` + +  +**Constraints:** + + + +- `2 <= k <= 400` + +- `1 <= rowConditions.length, colConditions.length <= 104` + +- `rowConditions[i].length == colConditions[i].length == 2` + +- `1 <= abovei, belowi, lefti, righti <= k` + +- `abovei != belowi` + +- `lefti != righti` + + + +## Solution + +```javascript +/** + * @param {number} k + * @param {number[][]} rowConditions + * @param {number[][]} colConditions + * @return {number[][]} + */ +var buildMatrix = function(k, rowConditions, colConditions) { + var rowOrder = topologicalSort(k, rowConditions); + var colOrder = topologicalSort(k, colConditions); + if (!rowOrder || !colOrder) return []; + var colOrderMap = colOrder.reduce((map, n, i) => { + map[n] = i; + return map; + }, {}); + var matrix = Array(k).fill(0).map(() => Array(k).fill(0)); + rowOrder.forEach((n, i) => matrix[i][colOrderMap[n]] = n); + return matrix; +}; + +var topologicalSort = function(k, arr) { + var beforeMap = Array(k).fill(0); + var afterMap = Array(k).fill(0).map(() => []); + for (var i = 0; i < arr.length; i++) { + beforeMap[arr[i][1] - 1] += 1; + afterMap[arr[i][0] - 1].push(arr[i][1]); + } + var queue = []; + for (var j = 0; j < k; j++) { + if (beforeMap[j] === 0) { + queue.push(j + 1); + } + } + var res = []; + while (queue.length) { + var num = queue.shift(); + afterMap[num - 1].forEach(n => { + if (--beforeMap[n - 1] === 0) { + queue.push(n); + } + }); + res.push(num); + } + if (res.length === k) { + return res; + } + return null; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(k). +* Space complexity : O(k ^ 2). diff --git a/2401-2500/2441. Largest Positive Integer That Exists With Its Negative.md b/2401-2500/2441. Largest Positive Integer That Exists With Its Negative.md new file mode 100644 index 0000000..d7df653 --- /dev/null +++ b/2401-2500/2441. Largest Positive Integer That Exists With Its Negative.md @@ -0,0 +1,78 @@ +# 2441. Largest Positive Integer That Exists With Its Negative + +- Difficulty: Easy. +- Related Topics: Array, Hash Table, Two Pointers, Sorting. +- Similar Questions: Two Sum. + +## Problem + +Given an integer array `nums` that **does not contain** any zeros, find **the largest positive** integer `k` such that `-k` also exists in the array. + +Return **the positive integer **`k`. If there is no such integer, return `-1`. + +  +Example 1: + +``` +Input: nums = [-1,2,-3,3] +Output: 3 +Explanation: 3 is the only valid k we can find in the array. +``` + +Example 2: + +``` +Input: nums = [-1,10,6,7,-7,1] +Output: 7 +Explanation: Both 1 and 7 have their corresponding negative values in the array. 7 has a larger value. +``` + +Example 3: + +``` +Input: nums = [-10,8,6,7,-2,-3] +Output: -1 +Explanation: There is no a single valid k, we return -1. +``` + +  +**Constraints:** + + + +- `1 <= nums.length <= 1000` + +- `-1000 <= nums[i] <= 1000` + +- `nums[i] != 0` + + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @return {number} + */ +var findMaxK = function(nums) { + var map = {}; + var max = -1; + for (var i = 0; i < nums.length; i++) { + if (map[-nums[i]]) { + max = Math.max(max, Math.abs(nums[i])); + } + map[nums[i]] = true; + } + return max; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/2401-2500/2444. Count Subarrays With Fixed Bounds.md b/2401-2500/2444. Count Subarrays With Fixed Bounds.md new file mode 100644 index 0000000..538c71f --- /dev/null +++ b/2401-2500/2444. Count Subarrays With Fixed Bounds.md @@ -0,0 +1,101 @@ +# 2444. Count Subarrays With Fixed Bounds + +- Difficulty: Hard. +- Related Topics: Array, Queue, Sliding Window, Monotonic Queue. +- Similar Questions: Count Number of Nice Subarrays, Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit. + +## Problem + +You are given an integer array `nums` and two integers `minK` and `maxK`. + +A **fixed-bound subarray** of `nums` is a subarray that satisfies the following conditions: + + + +- The **minimum** value in the subarray is equal to `minK`. + +- The **maximum** value in the subarray is equal to `maxK`. + + +Return **the **number** of fixed-bound subarrays**. + +A **subarray** is a **contiguous** part of an array. + +  +Example 1: + +``` +Input: nums = [1,3,5,2,7,5], minK = 1, maxK = 5 +Output: 2 +Explanation: The fixed-bound subarrays are [1,3,5] and [1,3,5,2]. +``` + +Example 2: + +``` +Input: nums = [1,1,1,1], minK = 1, maxK = 1 +Output: 10 +Explanation: Every subarray of nums is a fixed-bound subarray. There are 10 possible subarrays. +``` + +  +**Constraints:** + + + +- `2 <= nums.length <= 105` + +- `1 <= nums[i], minK, maxK <= 106` + + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @param {number} minK + * @param {number} maxK + * @return {number} + */ +var countSubarrays = function(nums, minK, maxK) { + var maxNum = 0; + var minNum = 0; + var left = 0; + var res = 0; + var start = 0; + for (var right = 0; right < nums.length; right++) { + if (nums[right] > maxK || nums[right] < minK) { + maxNum = 0; + minNum = 0; + left = right + 1; + start = right + 1; + continue; + } + if (nums[right] === minK) minNum += 1; + if (nums[right] === maxK) maxNum += 1; + while (left < right && ( + (nums[left] !== minK && nums[left] !== maxK) || + (nums[left] === minK && minNum > 1) || + (nums[left] === maxK && maxNum > 1) + )) { + if (nums[left] === minK) minNum -= 1; + if (nums[left] === maxK) maxNum -= 1; + left += 1; + } + if (minNum >= 1 && maxNum >= 1) { + res += left - start + 1; + } + } + return res; +}; +``` + +**Explain:** + +Sliding window. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/2401-2500/2487. Remove Nodes From Linked List.md b/2401-2500/2487. Remove Nodes From Linked List.md new file mode 100644 index 0000000..20880e6 --- /dev/null +++ b/2401-2500/2487. Remove Nodes From Linked List.md @@ -0,0 +1,85 @@ +# 2487. Remove Nodes From Linked List + +- Difficulty: Medium. +- Related Topics: Linked List, Stack, Recursion, Monotonic Stack. +- Similar Questions: Reverse Linked List, Delete Node in a Linked List, Next Greater Element I. + +## Problem + +You are given the `head` of a linked list. + +Remove every node which has a node with a greater value anywhere to the right side of it. + +Return **the **`head`** of the modified linked list.** + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2022/10/02/drawio.png) + +``` +Input: head = [5,2,13,3,8] +Output: [13,8] +Explanation: The nodes that should be removed are 5, 2 and 3. +- Node 13 is to the right of node 5. +- Node 13 is to the right of node 2. +- Node 8 is to the right of node 3. +``` + +Example 2: + +``` +Input: head = [1,1,1,1] +Output: [1,1,1,1] +Explanation: Every node has value 1, so no nodes are removed. +``` + +  +**Constraints:** + + + +- The number of the nodes in the given list is in the range `[1, 105]`. + +- `1 <= Node.val <= 105` + + + +## Solution + +```javascript +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ +var removeNodes = function(head) { + var newHead = new ListNode(Number.MAX_SAFE_INTEGER, head); + var stack = [newHead]; + var current = head; + while (current) { + while (current.val > stack[stack.length - 1].val) { + stack.pop(); + } + stack[stack.length - 1].next = current; + stack.push(current); + current = current.next; + } + return newHead.next; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/2601-2700/2678. Number of Senior Citizens.md b/2601-2700/2678. Number of Senior Citizens.md new file mode 100644 index 0000000..671fd1f --- /dev/null +++ b/2601-2700/2678. Number of Senior Citizens.md @@ -0,0 +1,83 @@ +# 2678. Number of Senior Citizens + +- Difficulty: Easy. +- Related Topics: Array, String. +- Similar Questions: . + +## Problem + +You are given a **0-indexed** array of strings `details`. Each element of `details` provides information about a given passenger compressed into a string of length `15`. The system is such that: + + + +- The first ten characters consist of the phone number of passengers. + +- The next character denotes the gender of the person. + +- The following two characters are used to indicate the age of the person. + +- The last two characters determine the seat allotted to that person. + + +Return **the number of passengers who are **strictly ****more than 60 years old**.** + +  +Example 1: + +``` +Input: details = ["7868190130M7522","5303914400F9211","9273338290F4010"] +Output: 2 +Explanation: The passengers at indices 0, 1, and 2 have ages 75, 92, and 40. Thus, there are 2 people who are over 60 years old. +``` + +Example 2: + +``` +Input: details = ["1313579440F2036","2921522980M5644"] +Output: 0 +Explanation: None of the passengers are older than 60. +``` + +  +**Constraints:** + + + +- `1 <= details.length <= 100` + +- `details[i].length == 15` + +- `details[i] consists of digits from '0' to '9'.` + +- `details[i][10] is either 'M' or 'F' or 'O'.` + +- The phone numbers and seat numbers of the passengers are distinct. + + + +## Solution + +```javascript +/** + * @param {string[]} details + * @return {number} + */ +var countSeniors = function(details) { + var count = 0; + for (var i = 0; i < details.length; i++) { + if (details[i][11] > '6' || (details[i][11] === '6' && details[i][12] > '0')) { + count += 1; + } + } + return count; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/2601-2700/2684. Maximum Number of Moves in a Grid.md b/2601-2700/2684. Maximum Number of Moves in a Grid.md new file mode 100644 index 0000000..a6cc478 --- /dev/null +++ b/2601-2700/2684. Maximum Number of Moves in a Grid.md @@ -0,0 +1,103 @@ +# 2684. Maximum Number of Moves in a Grid + +- Difficulty: Medium. +- Related Topics: Array, Dynamic Programming, Matrix. +- Similar Questions: . + +## Problem + +You are given a **0-indexed** `m x n` matrix `grid` consisting of **positive** integers. + +You can start at **any** cell in the first column of the matrix, and traverse the grid in the following way: + + + +- From a cell `(row, col)`, you can move to any of the cells: `(row - 1, col + 1)`, `(row, col + 1)` and `(row + 1, col + 1)` such that the value of the cell you move to, should be **strictly** bigger than the value of the current cell. + + +Return **the **maximum** number of **moves** that you can perform.** + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2023/04/11/yetgriddrawio-10.png) + +``` +Input: grid = [[2,4,3,5],[5,4,9,3],[3,4,2,11],[10,9,13,15]] +Output: 3 +Explanation: We can start at the cell (0, 0) and make the following moves: +- (0, 0) -> (0, 1). +- (0, 1) -> (1, 2). +- (1, 2) -> (2, 3). +It can be shown that it is the maximum number of moves that can be made. +``` + +Example 2: + +``` + +Input: grid = [[3,2,4],[2,1,9],[1,1,7]] +Output: 0 +Explanation: Starting from any cell in the first column we cannot perform any moves. +``` + +  +**Constraints:** + + + +- `m == grid.length` + +- `n == grid[i].length` + +- `2 <= m, n <= 1000` + +- `4 <= m * n <= 105` + +- `1 <= grid[i][j] <= 106` + + + +## Solution + +```javascript +/** + * @param {number[][]} grid + * @return {number} + */ +var maxMoves = function(grid) { + var dp = Array(grid.length).fill(0).map(() => Array(grid[0].length)); + var max = 0; + for (var i = 0; i < grid.length; i++) { + max = Math.max(max, helper(grid, i, 0, dp)); + } + return max; +}; + +var helper = function(grid, i, j, dp) { + if (dp[i][j] !== undefined) return dp[i][j]; + var max = 0; + if (j < grid[0].length - 1) { + if (i > 0 && grid[i - 1][j + 1] > grid[i][j]) { + max = Math.max(max, 1 + helper(grid, i - 1, j + 1, dp)); + } + if (grid[i][j + 1] > grid[i][j]) { + max = Math.max(max, 1 + helper(grid, i, j + 1, dp)); + } + if (i < grid.length - 1 && grid[i + 1][j + 1] > grid[i][j]) { + max = Math.max(max, 1 + helper(grid, i + 1, j + 1, dp)); + } + } + dp[i][j] = max; + return max; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(m * n). +* Space complexity : O(m * n). diff --git a/2701-2800/2751. Robot Collisions.md b/2701-2800/2751. Robot Collisions.md new file mode 100644 index 0000000..eedfbb4 --- /dev/null +++ b/2701-2800/2751. Robot Collisions.md @@ -0,0 +1,124 @@ +# 2751. Robot Collisions + +- Difficulty: Hard. +- Related Topics: Array, Stack, Sorting, Simulation. +- Similar Questions: Asteroid Collision. + +## Problem + +There are `n` **1-indexed** robots, each having a position on a line, health, and movement direction. + +You are given **0-indexed** integer arrays `positions`, `healths`, and a string `directions` (`directions[i]` is either **'L'** for **left** or **'R'** for **right**). All integers in `positions` are **unique**. + +All robots start moving on the line** simultaneously** at the **same speed **in their given directions. If two robots ever share the same position while moving, they will **collide**. + +If two robots collide, the robot with **lower health** is **removed** from the line, and the health of the other robot **decreases** **by one**. The surviving robot continues in the **same** direction it was going. If both robots have the **same** health, they are both** **removed from the line. + +Your task is to determine the **health** of the robots that survive the collisions, in the same **order **that the robots were given,** **i.e. final heath of robot 1 (if survived), final health of robot 2 (if survived), and so on. If there are no survivors, return an empty array. + +Return **an array containing the health of the remaining robots (in the order they were given in the input), after no further collisions can occur.** + +**Note:** The positions may be unsorted. + +  + +  +Example 1: + + +![](https://assets.leetcode.com/uploads/2023/05/15/image-20230516011718-12.png) + + +``` +Input: positions = [5,4,3,2,1], healths = [2,17,9,15,10], directions = "RRRRR" +Output: [2,17,9,15,10] +Explanation: No collision occurs in this example, since all robots are moving in the same direction. So, the health of the robots in order from the first robot is returned, [2, 17, 9, 15, 10]. +``` + +Example 2: + + +![](https://assets.leetcode.com/uploads/2023/05/15/image-20230516004433-7.png) + + +``` +Input: positions = [3,5,2,6], healths = [10,10,15,12], directions = "RLRL" +Output: [14] +Explanation: There are 2 collisions in this example. Firstly, robot 1 and robot 2 will collide, and since both have the same health, they will be removed from the line. Next, robot 3 and robot 4 will collide and since robot 4's health is smaller, it gets removed, and robot 3's health becomes 15 - 1 = 14. Only robot 3 remains, so we return [14]. +``` + +Example 3: + + +![](https://assets.leetcode.com/uploads/2023/05/15/image-20230516005114-9.png) + + +``` +Input: positions = [1,2,5,6], healths = [10,10,11,11], directions = "RLRL" +Output: [] +Explanation: Robot 1 and robot 2 will collide and since both have the same health, they are both removed. Robot 3 and 4 will collide and since both have the same health, they are both removed. So, we return an empty array, []. +``` + +  +**Constraints:** + + + +- `1 <= positions.length == healths.length == directions.length == n <= 105` + +- `1 <= positions[i], healths[i] <= 109` + +- `directions[i] == 'L'` or `directions[i] == 'R'` + +- All values in `positions` are distinct + + + +## Solution + +```javascript +/** + * @param {number[]} positions + * @param {number[]} healths + * @param {string} directions + * @return {number[]} + */ +var survivedRobotsHealths = function(positions, healths, directions) { + var res = []; + var stack = []; + var robots = positions.map((p, i) => [p, healths[i], directions[i], i]).sort((a, b) => a[0] - b[0]); + for (var i = 0; i < robots.length; i++) { + var robot = robots[i]; + if (robot[2] === 'R') { + stack.push(robot); + continue; + } + while (robot[1] > 0 && stack.length) { + if (stack[stack.length - 1][1] < robot[1]) { + stack.pop(); + robot[1] -= 1; + } else if (stack[stack.length - 1][1] === robot[1]) { + stack.pop(); + robot[1] = 0; + } else { + stack[stack.length - 1][1] -= 1; + robot[1] = 0; + } + } + if (robot[1] > 0) { + res.push(robot); + } + } + res.push(...stack); + return res.sort((a, b) => a[3] - b[3]).map(a => a[1]); +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n log(n)). +* Space complexity : O(n). diff --git a/2901-3000/2976. Minimum Cost to Convert String I.md b/2901-3000/2976. Minimum Cost to Convert String I.md new file mode 100644 index 0000000..dae7443 --- /dev/null +++ b/2901-3000/2976. Minimum Cost to Convert String I.md @@ -0,0 +1,176 @@ +# 2976. Minimum Cost to Convert String I + +- Difficulty: Medium. +- Related Topics: Array, String, Graph, Shortest Path. +- Similar Questions: Can Convert String in K Moves, Minimum Moves to Convert String. + +## Problem + +You are given two **0-indexed** strings `source` and `target`, both of length `n` and consisting of **lowercase** English letters. You are also given two **0-indexed** character arrays `original` and `changed`, and an integer array `cost`, where `cost[i]` represents the cost of changing the character `original[i]` to the character `changed[i]`. + +You start with the string `source`. In one operation, you can pick a character `x` from the string and change it to the character `y` at a cost of `z` **if** there exists **any** index `j` such that `cost[j] == z`, `original[j] == x`, and `changed[j] == y`. + +Return **the **minimum** cost to convert the string **`source`** to the string **`target`** using **any** number of operations. If it is impossible to convert** `source` **to** `target`, **return** `-1`. + +**Note** that there may exist indices `i`, `j` such that `original[j] == original[i]` and `changed[j] == changed[i]`. + +  +Example 1: + +``` +Input: source = "abcd", target = "acbe", original = ["a","b","c","c","e","d"], changed = ["b","c","b","e","b","e"], cost = [2,5,5,1,2,20] +Output: 28 +Explanation: To convert the string "abcd" to string "acbe": +- Change value at index 1 from 'b' to 'c' at a cost of 5. +- Change value at index 2 from 'c' to 'e' at a cost of 1. +- Change value at index 2 from 'e' to 'b' at a cost of 2. +- Change value at index 3 from 'd' to 'e' at a cost of 20. +The total cost incurred is 5 + 1 + 2 + 20 = 28. +It can be shown that this is the minimum possible cost. +``` + +Example 2: + +``` +Input: source = "aaaa", target = "bbbb", original = ["a","c"], changed = ["c","b"], cost = [1,2] +Output: 12 +Explanation: To change the character 'a' to 'b' change the character 'a' to 'c' at a cost of 1, followed by changing the character 'c' to 'b' at a cost of 2, for a total cost of 1 + 2 = 3. To change all occurrences of 'a' to 'b', a total cost of 3 * 4 = 12 is incurred. +``` + +Example 3: + +``` +Input: source = "abcd", target = "abce", original = ["a"], changed = ["e"], cost = [10000] +Output: -1 +Explanation: It is impossible to convert source to target because the value at index 3 cannot be changed from 'd' to 'e'. +``` + +  +**Constraints:** + + + +- `1 <= source.length == target.length <= 105` + +- `source`, `target` consist of lowercase English letters. + +- `1 <= cost.length == original.length == changed.length <= 2000` + +- `original[i]`, `changed[i]` are lowercase English letters. + +- `1 <= cost[i] <= 106` + +- `original[i] != changed[i]` + + + +## Solution + +```javascript +/** + * @param {string} source + * @param {string} target + * @param {character[]} original + * @param {character[]} changed + * @param {number[]} cost + * @return {number} + */ +var minimumCost = function(source, target, original, changed, cost) { + var adjacentMap = {}; + for (var i = 0; i < cost.length; i++) { + adjacentMap[original[i]] = adjacentMap[original[i]] || {}; + adjacentMap[original[i]][changed[i]] = Math.min( + adjacentMap[original[i]][changed[i]] || Number.MAX_SAFE_INTEGER, + cost[i], + ); + } + var res = 0; + var minCostMap = {}; + for (var j = 0; j < source.length; j++) { + minCostMap[source[j]] = minCostMap[source[j]] || dijkstra(source[j], adjacentMap); + var costMap = minCostMap[source[j]]; + if (costMap[target[j]] === undefined) return -1; + res += costMap[target[j]]; + } + return res; +}; + +var dijkstra = function(s, adjacentMap) { + var queue = new MinPriorityQueue(); + var minCostMap = {}; + queue.enqueue(s, 0); + while (queue.size()) { + var { element, priority } = queue.dequeue(); + if (minCostMap[element] <= priority) continue; + minCostMap[element] = priority; + var arr = Object.keys(adjacentMap[element] || {}); + for (var i = 0; i < arr.length; i++) { + queue.enqueue(arr[i], priority + adjacentMap[element][arr[i]]); + } + } + return minCostMap; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(m * n). +* Space complexity : O(m). + +## Solution 2 + +```javascript +/** + * @param {string} source + * @param {string} target + * @param {character[]} original + * @param {character[]} changed + * @param {number[]} cost + * @return {number} + */ +var minimumCost = function(source, target, original, changed, cost) { + var minCostMap = Array(26).fill(0).map(() => Array(26).fill(Number.MAX_SAFE_INTEGER)); + var a = 'a'.charCodeAt(0); + for (var i = 0; i < cost.length; i++) { + var o = original[i].charCodeAt(0) - a; + var c = changed[i].charCodeAt(0) - a; + minCostMap[o][c] = Math.min( + minCostMap[o][c], + cost[i], + ); + } + for (var k = 0; k < 26; k++) { + for (var i = 0; i < 26; i++) { + for (var j = 0; j < 26; j++) { + minCostMap[i][j] = Math.min( + minCostMap[i][j], + minCostMap[i][k] + minCostMap[k][j], + ); + } + } + } + var res = 0; + for (var j = 0; j < source.length; j++) { + var s = source[j].charCodeAt(0) - a; + var t = target[j].charCodeAt(0) - a; + if (s === t) continue; + if (minCostMap[s][t] === Number.MAX_SAFE_INTEGER) return -1; + res += minCostMap[s][t]; + } + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(m * n). +* Space complexity : O(1). + diff --git a/3001-3100/3016. Minimum Number of Pushes to Type Word II.md b/3001-3100/3016. Minimum Number of Pushes to Type Word II.md new file mode 100644 index 0000000..8d8813d --- /dev/null +++ b/3001-3100/3016. Minimum Number of Pushes to Type Word II.md @@ -0,0 +1,116 @@ +# 3016. Minimum Number of Pushes to Type Word II + +- Difficulty: Medium. +- Related Topics: Hash Table, String, Greedy, Sorting, Counting. +- Similar Questions: Letter Combinations of a Phone Number. + +## Problem + +You are given a string `word` containing lowercase English letters. + +Telephone keypads have keys mapped with **distinct** collections of lowercase English letters, which can be used to form words by pushing them. For example, the key `2` is mapped with `["a","b","c"]`, we need to push the key one time to type `"a"`, two times to type `"b"`, and three times to type `"c"` **.** + +It is allowed to remap the keys numbered `2` to `9` to **distinct** collections of letters. The keys can be remapped to **any** amount of letters, but each letter **must** be mapped to **exactly** one key. You need to find the **minimum** number of times the keys will be pushed to type the string `word`. + +Return **the **minimum** number of pushes needed to type **`word` **after remapping the keys**. + +An example mapping of letters to keys on a telephone keypad is given below. Note that `1`, `*`, `#`, and `0` do **not** map to any letters. + +![](https://assets.leetcode.com/uploads/2023/12/26/keypaddesc.png) + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2023/12/26/keypadv1e1.png) + +``` +Input: word = "abcde" +Output: 5 +Explanation: The remapped keypad given in the image provides the minimum cost. +"a" -> one push on key 2 +"b" -> one push on key 3 +"c" -> one push on key 4 +"d" -> one push on key 5 +"e" -> one push on key 6 +Total cost is 1 + 1 + 1 + 1 + 1 = 5. +It can be shown that no other mapping can provide a lower cost. +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2023/12/26/keypadv2e2.png) + +``` +Input: word = "xyzxyzxyzxyz" +Output: 12 +Explanation: The remapped keypad given in the image provides the minimum cost. +"x" -> one push on key 2 +"y" -> one push on key 3 +"z" -> one push on key 4 +Total cost is 1 * 4 + 1 * 4 + 1 * 4 = 12 +It can be shown that no other mapping can provide a lower cost. +Note that the key 9 is not mapped to any letter: it is not necessary to map letters to every key, but to map all the letters. +``` + +Example 3: + +![](https://assets.leetcode.com/uploads/2023/12/27/keypadv2.png) + +``` +Input: word = "aabbccddeeffgghhiiiiii" +Output: 24 +Explanation: The remapped keypad given in the image provides the minimum cost. +"a" -> one push on key 2 +"b" -> one push on key 3 +"c" -> one push on key 4 +"d" -> one push on key 5 +"e" -> one push on key 6 +"f" -> one push on key 7 +"g" -> one push on key 8 +"h" -> two pushes on key 9 +"i" -> one push on key 9 +Total cost is 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 2 * 2 + 6 * 1 = 24. +It can be shown that no other mapping can provide a lower cost. +``` + +  +**Constraints:** + + + +- `1 <= word.length <= 105` + +- `word` consists of lowercase English letters. + + + +## Solution + +```javascript +/** + * @param {string} word + * @return {number} + */ +var minimumPushes = function(word) { + var frequencyMap = Array(26).fill(0); + var a = 'a'.charCodeAt(0); + for (var i = 0; i < word.length; i++) { + frequencyMap[word[i].charCodeAt(0) - a] += 1; + } + var arr = frequencyMap.sort((a, b) => b - a); + var res = 0; + for (var i = 0; i < arr.length; i++) { + res += Math.ceil((i + 1) / 8) * arr[i]; + } + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/3001-3100/3043. Find the Length of the Longest Common Prefix.md b/3001-3100/3043. Find the Length of the Longest Common Prefix.md new file mode 100644 index 0000000..35530a0 --- /dev/null +++ b/3001-3100/3043. Find the Length of the Longest Common Prefix.md @@ -0,0 +1,97 @@ +# 3043. Find the Length of the Longest Common Prefix + +- Difficulty: Medium. +- Related Topics: Array, Hash Table, String, Trie. +- Similar Questions: Longest Common Prefix, Longest Common Suffix Queries. + +## Problem + +You are given two arrays with **positive** integers `arr1` and `arr2`. + +A **prefix** of a positive integer is an integer formed by one or more of its digits, starting from its **leftmost** digit. For example, `123` is a prefix of the integer `12345`, while `234` is **not**. + +A **common prefix** of two integers `a` and `b` is an integer `c`, such that `c` is a prefix of both `a` and `b`. For example, `5655359` and `56554` have a common prefix `565` while `1223` and `43456` **do not** have a common prefix. + +You need to find the length of the **longest common prefix** between all pairs of integers `(x, y)` such that `x` belongs to `arr1` and `y` belongs to `arr2`. + +Return **the length of the **longest** common prefix among all pairs**.** If no common prefix exists among them**, **return** `0`. + +  +Example 1: + +``` +Input: arr1 = [1,10,100], arr2 = [1000] +Output: 3 +Explanation: There are 3 pairs (arr1[i], arr2[j]): +- The longest common prefix of (1, 1000) is 1. +- The longest common prefix of (10, 1000) is 10. +- The longest common prefix of (100, 1000) is 100. +The longest common prefix is 100 with a length of 3. +``` + +Example 2: + +``` +Input: arr1 = [1,2,3], arr2 = [4,4,4] +Output: 0 +Explanation: There exists no common prefix for any pair (arr1[i], arr2[j]), hence we return 0. +Note that common prefixes between elements of the same array do not count. +``` + +  +**Constraints:** + + + +- `1 <= arr1.length, arr2.length <= 5 * 104` + +- `1 <= arr1[i], arr2[i] <= 108` + + + +## Solution + +```javascript +/** + * @param {number[]} arr1 + * @param {number[]} arr2 + * @return {number} + */ +var longestCommonPrefix = function(arr1, arr2) { + var trie = {}; + for (var i = 0; i < arr1.length; i++) { + var str = `${arr1[i]}`; + var map = trie; + for (var j = 0; j < str.length; j++) { + if (!map[str[j]]) { + map[str[j]] = {}; + } + map = map[str[j]]; + } + } + var max = 0; + for (var i = 0; i < arr2.length; i++) { + var str = `${arr2[i]}`; + var map = trie; + var len = 0; + for (var j = 0; j < str.length; j++) { + if (!map[str[j]]) { + break; + } + len += 1; + map = map[str[j]]; + } + max = Math.max(max, len); + } + return max; +}; +``` + +**Explain:** + +Trie. + +**Complexity:** + +* Time complexity : O(n * m). +* Space complexity : O(n * m). diff --git a/301-400/310. Minimum Height Trees.md b/301-400/310. Minimum Height Trees.md new file mode 100644 index 0000000..0473dd6 --- /dev/null +++ b/301-400/310. Minimum Height Trees.md @@ -0,0 +1,100 @@ +# 310. Minimum Height Trees + +- Difficulty: Medium. +- Related Topics: Depth-First Search, Breadth-First Search, Graph, Topological Sort. +- Similar Questions: Course Schedule, Course Schedule II, Collect Coins in a Tree, Count Pairs of Connectable Servers in a Weighted Tree Network. + +## Problem + +A tree is an undirected graph in which any two vertices are connected by *exactly* one path. In other words, any connected graph without simple cycles is a tree. + +Given a tree of `n` nodes labelled from `0` to `n - 1`, and an array of `n - 1` `edges` where `edges[i] = [ai, bi]` indicates that there is an undirected edge between the two nodes `ai` and `bi` in the tree, you can choose any node of the tree as the root. When you select a node `x` as the root, the result tree has height `h`. Among all possible rooted trees, those with minimum height (i.e. `min(h)`)  are called **minimum height trees** (MHTs). + +Return **a list of all **MHTs'** root labels**. You can return the answer in **any order**. + +The **height** of a rooted tree is the number of edges on the longest downward path between the root and a leaf. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2020/09/01/e1.jpg) + +``` +Input: n = 4, edges = [[1,0],[1,2],[1,3]] +Output: [1] +Explanation: As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT. +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2020/09/01/e2.jpg) + +``` +Input: n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]] +Output: [3,4] +``` + +  +**Constraints:** + + + +- `1 <= n <= 2 * 104` + +- `edges.length == n - 1` + +- `0 <= ai, bi < n` + +- `ai != bi` + +- All the pairs `(ai, bi)` are distinct. + +- The given input is **guaranteed** to be a tree and there will be **no repeated** edges. + + + +## Solution + +```javascript +/** + * @param {number} n + * @param {number[][]} edges + * @return {number[]} + */ +var findMinHeightTrees = function(n, edges) { + if (!edges.length) return [0]; + var map = Array(n).fill(0).map(() => new Map()); + for (var i = 0; i < edges.length; i++) { + map[edges[i][0]].set(edges[i][1], true); + map[edges[i][1]].set(edges[i][0], true); + } + var arr = []; + for (var i = 0; i < n; i++) { + if (map[i].size === 1) { + arr.push(i); + } + } + while (n > 2) { + n -= arr.length; + var newArr = []; + for (var i = 0; i < arr.length; i++) { + var j = Array.from(map[arr[i]].keys())[0]; + map[j].delete(arr[i]); + if (map[j].size === 1) { + newArr.push(j); + } + } + arr = newArr; + } + return arr; +}; +``` + +**Explain:** + +Delete every leaf untill there is only one or two nodes. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/301-400/350. Intersection of Two Arrays II.md b/301-400/350. Intersection of Two Arrays II.md new file mode 100644 index 0000000..fd9b5b8 --- /dev/null +++ b/301-400/350. Intersection of Two Arrays II.md @@ -0,0 +1,81 @@ +# 350. Intersection of Two Arrays II + +- Difficulty: Easy. +- Related Topics: Array, Hash Table, Two Pointers, Binary Search, Sorting. +- Similar Questions: Intersection of Two Arrays, Find Common Characters, Find the Difference of Two Arrays, Choose Numbers From Two Arrays in Range, Intersection of Multiple Arrays, Minimum Common Value. + +## Problem + +Given two integer arrays `nums1` and `nums2`, return **an array of their intersection**. Each element in the result must appear as many times as it shows in both arrays and you may return the result in **any order**. + +  +Example 1: + +``` +Input: nums1 = [1,2,2,1], nums2 = [2,2] +Output: [2,2] +``` + +Example 2: + +``` +Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] +Output: [4,9] +Explanation: [9,4] is also accepted. +``` + +  +**Constraints:** + + + +- `1 <= nums1.length, nums2.length <= 1000` + +- `0 <= nums1[i], nums2[i] <= 1000` + + +  +**Follow up:** + + + +- What if the given array is already sorted? How would you optimize your algorithm? + +- What if `nums1`'s size is small compared to `nums2`'s size? Which algorithm is better? + +- What if elements of `nums2` are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once? + + + +## Solution + +```javascript +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number[]} + */ +var intersect = function(nums1, nums2) { + var map = {}; + for (var i = 0; i < nums1.length; i++) { + map[nums1[i]] = (map[nums1[i]] || 0) + 1; + } + var res = []; + for (var j = 0; j < nums2.length; j++) { + if (map[nums2[j]]) { + map[nums2[j]]--; + res.push(nums2[j]); + } + } + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n + m). +* Space complexity : O(n + m). diff --git a/301-400/383. Ransom Note.md b/301-400/383. Ransom Note.md new file mode 100644 index 0000000..4527474 --- /dev/null +++ b/301-400/383. Ransom Note.md @@ -0,0 +1,66 @@ +# 383. Ransom Note + +- Difficulty: Easy. +- Related Topics: Hash Table, String, Counting. +- Similar Questions: Stickers to Spell Word. + +## Problem + +Given two strings `ransomNote` and `magazine`, return `true`** if **`ransomNote`** can be constructed by using the letters from **`magazine`** and **`false`** otherwise**. + +Each letter in `magazine` can only be used once in `ransomNote`. + +  +Example 1: +``` +Input: ransomNote = "a", magazine = "b" +Output: false +```Example 2: +``` +Input: ransomNote = "aa", magazine = "ab" +Output: false +```Example 3: +``` +Input: ransomNote = "aa", magazine = "aab" +Output: true +``` +  +**Constraints:** + + + +- `1 <= ransomNote.length, magazine.length <= 105` + +- `ransomNote` and `magazine` consist of lowercase English letters. + + + +## Solution + +```javascript +/** + * @param {string} ransomNote + * @param {string} magazine + * @return {boolean} + */ +var canConstruct = function(ransomNote, magazine) { + var map = {}; + for (var i = 0; i < magazine.length; i++) { + map[magazine[i]] = (map[magazine[i]] || 0) + 1; + } + for (var j = 0; j < ransomNote.length; j++) { + if (!map[ransomNote[j]]) return false; + map[ransomNote[j]] -= 1; + } + return true; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/501-600/514. Freedom Trail.md b/501-600/514. Freedom Trail.md new file mode 100644 index 0000000..75d9dc0 --- /dev/null +++ b/501-600/514. Freedom Trail.md @@ -0,0 +1,103 @@ +# 514. Freedom Trail + +- Difficulty: Hard. +- Related Topics: String, Dynamic Programming, Depth-First Search, Breadth-First Search. +- Similar Questions: . + +## Problem + +In the video game Fallout 4, the quest **"Road to Freedom"** requires players to reach a metal dial called the **"Freedom Trail Ring"** and use the dial to spell a specific keyword to open the door. + +Given a string `ring` that represents the code engraved on the outer ring and another string `key` that represents the keyword that needs to be spelled, return **the minimum number of steps to spell all the characters in the keyword**. + +Initially, the first character of the ring is aligned at the `"12:00"` direction. You should spell all the characters in `key` one by one by rotating `ring` clockwise or anticlockwise to make each character of the string key aligned at the `"12:00"` direction and then by pressing the center button. + +At the stage of rotating the ring to spell the key character `key[i]`: + + + +- You can rotate the ring clockwise or anticlockwise by one place, which counts as **one step**. The final purpose of the rotation is to align one of `ring`'s characters at the `"12:00"` direction, where this character must equal `key[i]`. + +- If the character `key[i]` has been aligned at the `"12:00"` direction, press the center button to spell, which also counts as **one step**. After the pressing, you could begin to spell the next character in the key (next stage). Otherwise, you have finished all the spelling. + + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2018/10/22/ring.jpg) + +``` +Input: ring = "godding", key = "gd" +Output: 4 +Explanation: +For the first key character 'g', since it is already in place, we just need 1 step to spell this character. +For the second key character 'd', we need to rotate the ring "godding" anticlockwise by two steps to make it become "ddinggo". +Also, we need 1 more step for spelling. +So the final output is 4. +``` + +Example 2: + +``` +Input: ring = "godding", key = "godding" +Output: 13 +``` + +  +**Constraints:** + + + +- `1 <= ring.length, key.length <= 100` + +- `ring` and `key` consist of only lower case English letters. + +- It is guaranteed that `key` could always be spelled by rotating `ring`. + + + +## Solution + +```javascript +/** + * @param {string} ring + * @param {string} key + * @return {number} + */ +var findRotateSteps = function(ring, key) { + var next = function(i) { + return i === ring.length - 1 ? 0 : i + 1; + }; + var prev = function(i) { + return i === 0 ? ring.length - 1 : i - 1; + }; + var dp = Array(ring.length).fill(0).map(() => Array(key.length)); + var dfs = function(i, j) { + if (j === key.length) return 0; + if (dp[i][j] !== undefined) return dp[i][j]; + if (ring[i] === key[j]) { + dp[i][j] = 1 + dfs(i, j + 1); + return dp[i][j]; + } + var nextI = next(i); + while (ring[nextI] !== key[j]) nextI = next(nextI); + var prevI = prev(i); + while (ring[prevI] !== key[j]) prevI = prev(prevI); + dp[i][j] = Math.min( + ((nextI - i + ring.length) % ring.length) + dfs(nextI, j), + ((i - prevI + ring.length) % ring.length) + dfs(prevI, j), + ); + return dp[i][j]; + }; + return dfs(0, 0); +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * n * m). +* Space complexity : O(n * m). diff --git a/601-700/641. Design Circular Deque.md b/601-700/641. Design Circular Deque.md new file mode 100644 index 0000000..f6839ce --- /dev/null +++ b/601-700/641. Design Circular Deque.md @@ -0,0 +1,351 @@ +# 641. Design Circular Deque + +- Difficulty: Medium. +- Related Topics: Array, Linked List, Design, Queue. +- Similar Questions: Design Circular Queue, Design Front Middle Back Queue. + +## Problem + +Design your implementation of the circular double-ended queue (deque). + +Implement the `MyCircularDeque` class: + + + +- `MyCircularDeque(int k)` Initializes the deque with a maximum size of `k`. + +- `boolean insertFront()` Adds an item at the front of Deque. Returns `true` if the operation is successful, or `false` otherwise. + +- `boolean insertLast()` Adds an item at the rear of Deque. Returns `true` if the operation is successful, or `false` otherwise. + +- `boolean deleteFront()` Deletes an item from the front of Deque. Returns `true` if the operation is successful, or `false` otherwise. + +- `boolean deleteLast()` Deletes an item from the rear of Deque. Returns `true` if the operation is successful, or `false` otherwise. + +- `int getFront()` Returns the front item from the Deque. Returns `-1` if the deque is empty. + +- `int getRear()` Returns the last item from Deque. Returns `-1` if the deque is empty. + +- `boolean isEmpty()` Returns `true` if the deque is empty, or `false` otherwise. + +- `boolean isFull()` Returns `true` if the deque is full, or `false` otherwise. + + +  +Example 1: + +``` +Input +["MyCircularDeque", "insertLast", "insertLast", "insertFront", "insertFront", "getRear", "isFull", "deleteLast", "insertFront", "getFront"] +[[3], [1], [2], [3], [4], [], [], [], [4], []] +Output +[null, true, true, true, false, 2, true, true, true, 4] + +Explanation +MyCircularDeque myCircularDeque = new MyCircularDeque(3); +myCircularDeque.insertLast(1); // return True +myCircularDeque.insertLast(2); // return True +myCircularDeque.insertFront(3); // return True +myCircularDeque.insertFront(4); // return False, the queue is full. +myCircularDeque.getRear(); // return 2 +myCircularDeque.isFull(); // return True +myCircularDeque.deleteLast(); // return True +myCircularDeque.insertFront(4); // return True +myCircularDeque.getFront(); // return 4 +``` + +  +**Constraints:** + + + +- `1 <= k <= 1000` + +- `0 <= value <= 1000` + +- At most `2000` calls will be made to `insertFront`, `insertLast`, `deleteFront`, `deleteLast`, `getFront`, `getRear`, `isEmpty`, `isFull`. + + + +## Solution 1 + +```javascript +/** + * @param {number} k + */ +var MyCircularDeque = function(k) { + this.limit = k; + this.count = 0; + this.front = null; + this.last = null; +}; + +/** + * @param {number} value + * @return {boolean} + */ +MyCircularDeque.prototype.insertFront = function(value) { + if (this.count === this.limit) return false; + var node = { + value, + prev: null, + next: null, + }; + if (!this.front) { + this.front = node; + this.last = node; + } else { + node.next = this.front; + this.front.prev = node; + this.front = node; + } + this.count += 1; + return true; +}; + +/** + * @param {number} value + * @return {boolean} + */ +MyCircularDeque.prototype.insertLast = function(value) { + if (this.count === this.limit) return false; + var node = { + value, + prev: null, + next: null, + }; + if (!this.last) { + this.front = node; + this.last = node; + } else { + node.prev = this.last; + this.last.next = node; + this.last = node; + } + this.count += 1; + return true; +}; + +/** + * @return {boolean} + */ +MyCircularDeque.prototype.deleteFront = function() { + if (!this.front) return false; + if (this.front === this.last) { + this.front = null; + this.last = null; + } else { + this.front.next.prev = null; + this.front = this.front.next; + } + this.count -= 1; + return true; +}; + +/** + * @return {boolean} + */ +MyCircularDeque.prototype.deleteLast = function() { + if (!this.last) return false; + if (this.front === this.last) { + this.front = null; + this.last = null; + } else { + this.last.prev.next = null; + this.last = this.last.prev; + } + this.count -= 1; + return true; +}; + +/** + * @return {number} + */ +MyCircularDeque.prototype.getFront = function() { + return this.front ? this.front.value : -1; +}; + +/** + * @return {number} + */ +MyCircularDeque.prototype.getRear = function() { + return this.last ? this.last.value : -1; +}; + +/** + * @return {boolean} + */ +MyCircularDeque.prototype.isEmpty = function() { + return this.count === 0; +}; + +/** + * @return {boolean} + */ +MyCircularDeque.prototype.isFull = function() { + return this.count === this.limit; +}; + +/** + * Your MyCircularDeque object will be instantiated and called as such: + * var obj = new MyCircularDeque(k) + * var param_1 = obj.insertFront(value) + * var param_2 = obj.insertLast(value) + * var param_3 = obj.deleteFront() + * var param_4 = obj.deleteLast() + * var param_5 = obj.getFront() + * var param_6 = obj.getRear() + * var param_7 = obj.isEmpty() + * var param_8 = obj.isFull() + */ +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(1). +* Space complexity : O(n). + +## Solution 2 + +```javascript +/** + * @param {number} k + */ +var MyCircularDeque = function(k) { + this.limit = k; + this.count = 0; + this.arr = Array(k); + this.front = -1; + this.last = -1; +}; + +/** + * @param {number} value + * @return {boolean} + */ +MyCircularDeque.prototype.insertFront = function(value) { + if (this.count === this.limit) return false; + if (this.count === 0) { + this.front = 0; + this.last = 0; + } else { + this.front -= 1; + if (this.front < 0) { + this.front += this.arr.length; + } + } + this.arr[this.front] = value; + this.count += 1; + return true; +}; + +/** + * @param {number} value + * @return {boolean} + */ +MyCircularDeque.prototype.insertLast = function(value) { + if (this.count === this.limit) return false; + if (this.count === 0) { + this.front = 0; + this.last = 0; + } else { + this.last += 1; + if (this.last >= this.arr.length) { + this.last -= this.arr.length; + } + } + this.arr[this.last] = value; + this.count += 1; + return true; +}; + +/** + * @return {boolean} + */ +MyCircularDeque.prototype.deleteFront = function() { + if (this.count === 0) return false; + if (this.count === 1) { + this.front = -1; + this.last = -1; + } else { + this.front += 1; + if (this.front >= this.arr.length) { + this.front -= this.arr.length; + } + } + this.count -= 1; + return true; +}; + +/** + * @return {boolean} + */ +MyCircularDeque.prototype.deleteLast = function() { + if (this.count === 0) return false; + if (this.count === 1) { + this.front = -1; + this.last = -1; + } else { + this.last -= 1; + if (this.last < 0) { + this.last += this.arr.length; + } + } + this.count -= 1; + return true; +}; + +/** + * @return {number} + */ +MyCircularDeque.prototype.getFront = function() { + return this.front === -1 ? -1 : this.arr[this.front]; +}; + +/** + * @return {number} + */ +MyCircularDeque.prototype.getRear = function() { + return this.last === -1 ? -1 : this.arr[this.last]; +}; + +/** + * @return {boolean} + */ +MyCircularDeque.prototype.isEmpty = function() { + return this.count === 0; +}; + +/** + * @return {boolean} + */ +MyCircularDeque.prototype.isFull = function() { + return this.count === this.limit; +}; + +/** + * Your MyCircularDeque object will be instantiated and called as such: + * var obj = new MyCircularDeque(k) + * var param_1 = obj.insertFront(value) + * var param_2 = obj.insertLast(value) + * var param_3 = obj.deleteFront() + * var param_4 = obj.deleteLast() + * var param_5 = obj.getFront() + * var param_6 = obj.getRear() + * var param_7 = obj.isEmpty() + * var param_8 = obj.isFull() + */ +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(1). +* Space complexity : O(n). diff --git a/701-800/752. Open the Lock.md b/701-800/752. Open the Lock.md new file mode 100644 index 0000000..a3b412f --- /dev/null +++ b/701-800/752. Open the Lock.md @@ -0,0 +1,116 @@ +# 752. Open the Lock + +- Difficulty: Medium. +- Related Topics: Array, Hash Table, String, Breadth-First Search. +- Similar Questions: Reachable Nodes With Restrictions. + +## Problem + +You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: `'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'`. The wheels can rotate freely and wrap around: for example we can turn `'9'` to be `'0'`, or `'0'` to be `'9'`. Each move consists of turning one wheel one slot. + +The lock initially starts at `'0000'`, a string representing the state of the 4 wheels. + +You are given a list of `deadends` dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it. + +Given a `target` representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible. + +  +Example 1: + +``` +Input: deadends = ["0201","0101","0102","1212","2002"], target = "0202" +Output: 6 +Explanation: +A sequence of valid moves would be "0000" -> "1000" -> "1100" -> "1200" -> "1201" -> "1202" -> "0202". +Note that a sequence like "0000" -> "0001" -> "0002" -> "0102" -> "0202" would be invalid, +because the wheels of the lock become stuck after the display becomes the dead end "0102". +``` + +Example 2: + +``` +Input: deadends = ["8888"], target = "0009" +Output: 1 +Explanation: We can turn the last wheel in reverse to move from "0000" -> "0009". +``` + +Example 3: + +``` +Input: deadends = ["8887","8889","8878","8898","8788","8988","7888","9888"], target = "8888" +Output: -1 +Explanation: We cannot reach the target without getting stuck. +``` + +  +**Constraints:** + + + +- `1 <= deadends.length <= 500` + +- `deadends[i].length == 4` + +- `target.length == 4` + +- target **will not be** in the list `deadends`. + +- `target` and `deadends[i]` consist of digits only. + + + +## Solution + +```javascript +/** + * @param {string[]} deadends + * @param {string} target + * @return {number} + */ +var openLock = function(deadends, target) { + if (target === '0000') return 0; + var arr = ['0000']; + var visited = { '0000': true }; + var deadendsMap = {}; + for (var i = 0; i < deadends.length; i++) { + if (deadends[i] === '0000') return -1; + deadendsMap[deadends[i]] = true; + } + var res = 0; + while (arr.length) { + var newArr = []; + res += 1; + for (var i = 0; i < arr.length; i++) { + var nexts = getNexts(arr[i]); + for (var j = 0; j < nexts.length; j++) { + if (nexts[j] === target) return res; + if (!visited[nexts[j]] && !deadendsMap[nexts[j]]) { + newArr.push(nexts[j]); + visited[nexts[j]] = true; + } + } + } + arr = newArr; + } + return -1; +}; + +var getNexts = function(str) { + var res = []; + for (var i = 0; i < str.length; i++) { + var num = Number(str[i]); + res.push(str.slice(0, i) + (num === 9 ? 0 : num + 1) + str.slice(i + 1)); + res.push(str.slice(0, i) + (num === 0 ? 9 : num - 1) + str.slice(i + 1)); + } + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/701-800/785. Is Graph Bipartite.md b/701-800/785. Is Graph Bipartite.md new file mode 100644 index 0000000..1e6f0af --- /dev/null +++ b/701-800/785. Is Graph Bipartite.md @@ -0,0 +1,100 @@ +# 785. Is Graph Bipartite? + +- Difficulty: Medium. +- Related Topics: Depth-First Search, Breadth-First Search, Union Find, Graph. +- Similar Questions: Divide Nodes Into the Maximum Number of Groups. + +## 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: + +![](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: + +![](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`. + + + +## Solution + +```javascript +/** + * @param {number[][]} graph + * @return {boolean} + */ +var isBipartite = function(graph) { + var map = {}; + for (var i = 0; i < graph.length; i++) { + if (!dfs(graph, map, i)) return false; + } + return true; +}; + +var dfs = function(graph, map, i, group) { + if (map[i]) return !group || group === map[i]; + map[i] = group || 1; + for (var j = 0; j < graph[i].length; j++) { + if (!dfs(graph, map, graph[i][j], map[i] === 1 ? 2 : 1)) return false; + } + return true; +}; +``` + +**Explain:** + +DFS with memorize. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/801-900/881. Boats to Save People.md b/801-900/881. Boats to Save People.md new file mode 100644 index 0000000..edd2598 --- /dev/null +++ b/801-900/881. Boats to Save People.md @@ -0,0 +1,85 @@ +# 881. Boats to Save People + +- Difficulty: Medium. +- Related Topics: Array, Two Pointers, Greedy, Sorting. +- Similar Questions: . + +## Problem + +You are given an array `people` where `people[i]` is the weight of the `ith` person, and an **infinite number of boats** where each boat can carry a maximum weight of `limit`. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most `limit`. + +Return **the minimum number of boats to carry every given person**. + +  +Example 1: + +``` +Input: people = [1,2], limit = 3 +Output: 1 +Explanation: 1 boat (1, 2) +``` + +Example 2: + +``` +Input: people = [3,2,2,1], limit = 3 +Output: 3 +Explanation: 3 boats (1, 2), (2) and (3) +``` + +Example 3: + +``` +Input: people = [3,5,3,4], limit = 5 +Output: 4 +Explanation: 4 boats (3), (3), (4), (5) +``` + +  +**Constraints:** + + + +- `1 <= people.length <= 5 * 104` + +- `1 <= people[i] <= limit <= 3 * 104` + + + +## Solution + +```javascript +/** + * @param {number[]} people + * @param {number} limit + * @return {number} + */ +var numRescueBoats = function(people, limit) { + people.sort((a, b) => a - b); + var left = 0; + var right = people.length - 1; + var res = 0; + while (left <= right) { + res++; + if (left === right) { + break; + } + if (people[left] + people[right] > limit) { + right--; + } else { + right--; + left++; + } + } + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * log(n)). +* Space complexity : O(1). diff --git a/901-1000/950. Reveal Cards In Increasing Order.md b/901-1000/950. Reveal Cards In Increasing Order.md new file mode 100644 index 0000000..e8c5bae --- /dev/null +++ b/901-1000/950. Reveal Cards In Increasing Order.md @@ -0,0 +1,105 @@ +# 950. Reveal Cards In Increasing Order + +- Difficulty: Medium. +- Related Topics: Array, Queue, Sorting, Simulation. +- Similar Questions: . + +## Problem + +You are given an integer array `deck`. There is a deck of cards where every card has a unique integer. The integer on the `ith` card is `deck[i]`. + +You can order the deck in any order you want. Initially, all the cards start face down (unrevealed) in one deck. + +You will do the following steps repeatedly until all cards are revealed: + + + +- Take the top card of the deck, reveal it, and take it out of the deck. + +- If there are still cards in the deck then put the next top card of the deck at the bottom of the deck. + +- If there are still unrevealed cards, go back to step 1. Otherwise, stop. + + +Return **an ordering of the deck that would reveal the cards in increasing order**. + +**Note** that the first entry in the answer is considered to be the top of the deck. + +  +Example 1: + +``` +Input: deck = [17,13,11,2,3,5,7] +Output: [2,13,3,11,5,17,7] +Explanation: +We get the deck in the order [17,13,11,2,3,5,7] (this order does not matter), and reorder it. +After reordering, the deck starts as [2,13,3,11,5,17,7], where 2 is the top of the deck. +We reveal 2, and move 13 to the bottom. The deck is now [3,11,5,17,7,13]. +We reveal 3, and move 11 to the bottom. The deck is now [5,17,7,13,11]. +We reveal 5, and move 17 to the bottom. The deck is now [7,13,11,17]. +We reveal 7, and move 13 to the bottom. The deck is now [11,17,13]. +We reveal 11, and move 17 to the bottom. The deck is now [13,17]. +We reveal 13, and move 17 to the bottom. The deck is now [17]. +We reveal 17. +Since all the cards revealed are in increasing order, the answer is correct. +``` + +Example 2: + +``` +Input: deck = [1,1000] +Output: [1,1000] +``` + +  +**Constraints:** + + + +- `1 <= deck.length <= 1000` + +- `1 <= deck[i] <= 106` + +- All the values of `deck` are **unique**. + + + +## Solution + +```javascript +/** + * @param {number[]} deck + * @return {number[]} + */ +var deckRevealedIncreasing = function(deck) { + deck.sort((a, b) => a - b); + var res = Array(deck.length); + var i = 0; + var j = 0; + var skip = false; + while (i < deck.length) { + // find space for card + if (res[j] === undefined) { + // place card if it's not skip round + if (!skip) { + res[j] = deck[i]; + i++; + } + // revert skip flag + skip = !skip; + } + // try next place + j = (j + 1) % deck.length; + } + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * log(n)). +* Space complexity : O(n). diff --git a/901-1000/959. Regions Cut By Slashes.md b/901-1000/959. Regions Cut By Slashes.md new file mode 100644 index 0000000..555785b --- /dev/null +++ b/901-1000/959. Regions Cut By Slashes.md @@ -0,0 +1,106 @@ +# 959. Regions Cut By Slashes + +- Difficulty: Medium. +- Related Topics: Array, Hash Table, Depth-First Search, Breadth-First Search, Union Find, Matrix. +- Similar Questions: . + +## Problem + +An `n x n` grid is composed of `1 x 1` squares where each `1 x 1` square consists of a `'/'`, `'\'`, or blank space `' '`. These characters divide the square into contiguous regions. + +Given the grid `grid` represented as a string array, return **the number of regions**. + +Note that backslash characters are escaped, so a `'\'` is represented as `'\\'`. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2018/12/15/1.png) + +``` +Input: grid = [" /","/ "] +Output: 2 +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2018/12/15/2.png) + +``` +Input: grid = [" /"," "] +Output: 1 +``` + +Example 3: + +![](https://assets.leetcode.com/uploads/2018/12/15/4.png) + +``` +Input: grid = ["/\\","\\/"] +Output: 5 +Explanation: Recall that because \ characters are escaped, "\\/" refers to \/, and "/\\" refers to /\. +``` + +  +**Constraints:** + + + +- `n == grid.length == grid[i].length` + +- `1 <= n <= 30` + +- `grid[i][j]` is either `'/'`, `'\'`, or `' '`. + + + +## Solution + +```javascript +/** + * @param {string[]} grid + * @return {number} + */ +var regionsBySlashes = function(grid) { + var matrix = Array(3 * grid.length).fill(0).map(() => Array(3 * grid.length).fill(0)); + for (var i = 0; i < grid.length; i++) { + for (var j = 0; j < grid[i].length; j++) { + if (grid[i][j] === '\\') { + matrix[i * 3][j * 3] = 1; + matrix[i * 3 + 1][j * 3 + 1] = 1; + matrix[i * 3 + 2][j * 3 + 2] = 1; + } else if (grid[i][j] === '/') { + matrix[i * 3][j * 3 + 2] = 1; + matrix[i * 3 + 1][j * 3 + 1] = 1; + matrix[i * 3 + 2][j * 3] = 1; + } + } + } + var res = 0; + for (var i = 0; i < matrix.length; i++) { + for (var j = 0; j < matrix[i].length; j++) { + if (matrix[i][j] === 0) { + visitAndMark(matrix, i, j, ++res); + } + } + } + return res; +}; + +var visitAndMark = function(matrix, i, j, num) { + matrix[i][j] = num; + matrix[i][j + 1] === 0 && visitAndMark(matrix, i, j + 1, num); + matrix[i][j - 1] === 0 && visitAndMark(matrix, i, j - 1, num); + matrix[i + 1]?.[j] === 0 && visitAndMark(matrix, i + 1, j, num); + matrix[i - 1]?.[j] === 0 && visitAndMark(matrix, i - 1, j, num); +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n ^ 2). +* Space complexity : O(n ^ 2). diff --git a/create/index.js b/create/index.js index 559c81a..11a431b 100644 --- a/create/index.js +++ b/create/index.js @@ -11,7 +11,7 @@ const create = data => { similarQuestions: JSON.parse(data.similarQuestions).map(q => q.title).join(', '), description: getDescription(data.content), }; - const dir = getPath(pageData.id, pageData.name); + const dir = getPath(pageData.id, pageData.name.replace(/\?/g, '')); if (fs.existsSync(dir)) { console.log(`${chalk.red('file already exists')}: ${chalk.blue(dir)}\n`);