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/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/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/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/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/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/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/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/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/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/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).