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/1001-1100/1047. Remove All Adjacent Duplicates In String.md b/1001-1100/1047. Remove All Adjacent Duplicates In String.md new file mode 100644 index 0000000..4b9b7ef --- /dev/null +++ b/1001-1100/1047. Remove All Adjacent Duplicates In String.md @@ -0,0 +1,70 @@ +# 1047. Remove All Adjacent Duplicates In String + +- Difficulty: Easy. +- Related Topics: String, Stack. +- Similar Questions: Remove All Adjacent Duplicates in String II, Removing Stars From a String, Minimize String Length. + +## Problem + +You are given a string `s` consisting of lowercase English letters. A **duplicate removal** consists of choosing two **adjacent** and **equal** letters and removing them. + +We repeatedly make **duplicate removals** on `s` until we no longer can. + +Return **the final string after all such duplicate removals have been made**. It can be proven that the answer is **unique**. + +  +Example 1: + +``` +Input: s = "abbaca" +Output: "ca" +Explanation: +For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca". +``` + +Example 2: + +``` +Input: s = "azxxzy" +Output: "ay" +``` + +  +**Constraints:** + + + +- `1 <= s.length <= 105` + +- `s` consists of lowercase English letters. + + + +## Solution + +```javascript +/** + * @param {string} s + * @return {string} + */ +var removeDuplicates = function(s) { + var stack = []; + for (var i = 0; i <= s.length; i++) { + if (stack.length >= 2 && stack[stack.length - 1] === stack[stack.length - 2]) { + stack.pop(); + stack.pop(); + } + i !== s.length && stack.push(s[i]); + } + return stack.join(''); +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/1001-1100/1074. Number of Submatrices That Sum to Target.md b/1001-1100/1074. Number of Submatrices That Sum to Target.md new file mode 100644 index 0000000..cdb722a --- /dev/null +++ b/1001-1100/1074. Number of Submatrices That Sum to Target.md @@ -0,0 +1,96 @@ +# 1074. Number of Submatrices That Sum to Target + +- Difficulty: Hard. +- Related Topics: Array, Hash Table, Matrix, Prefix Sum. +- Similar Questions: Disconnect Path in a Binary Matrix by at Most One Flip. + +## Problem + +Given a `matrix` and a `target`, return the number of non-empty submatrices that sum to target. + +A submatrix `x1, y1, x2, y2` is the set of all cells `matrix[x][y]` with `x1 <= x <= x2` and `y1 <= y <= y2`. + +Two submatrices `(x1, y1, x2, y2)` and `(x1', y1', x2', y2')` are different if they have some coordinate that is different: for example, if `x1 != x1'`. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2020/09/02/mate1.jpg) + +``` +Input: matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0 +Output: 4 +Explanation: The four 1x1 submatrices that only contain 0. +``` + +Example 2: + +``` +Input: matrix = [[1,-1],[-1,1]], target = 0 +Output: 5 +Explanation: The two 1x2 submatrices, plus the two 2x1 submatrices, plus the 2x2 submatrix. +``` + +Example 3: + +``` +Input: matrix = [[904]], target = 0 +Output: 0 +``` + +  +**Constraints:** + + + +- `1 <= matrix.length <= 100` + +- `1 <= matrix[0].length <= 100` + +- `-1000 <= matrix[i] <= 1000` + +- `-10^8 <= target <= 10^8` + + + +## Solution + +```javascript +/** + * @param {number[][]} matrix + * @param {number} target + * @return {number} + */ +var numSubmatrixSumTarget = function(matrix, target) { + var m = matrix.length; + var n = matrix[0].length; + for (var i = 0; i < m; i++) { + for (var j = 1; j < n; j++) { + matrix[i][j] += matrix[i][j - 1]; + } + } + var res = 0; + for (var j1 = 0; j1 < n; j1++) { + for (var j2 = j1; j2 < n; j2++) { + var map = {}; + var sum = 0; + map[0] = 1; + for (var i = 0; i < m; i++) { + sum += matrix[i][j2] - (matrix[i][j1 - 1] || 0); + if (map[sum - target]) res += map[sum - target]; + map[sum] = (map[sum] || 0) + 1; + } + } + } + return res; +}; +``` + +**Explain:** + +Prefix sum and hash map. + +**Complexity:** + +* Time complexity : O(n * n * m). +* Space complexity : O(n * m). diff --git a/1001-1100/1092. Shortest Common Supersequence .md b/1001-1100/1092. Shortest Common Supersequence .md new file mode 100644 index 0000000..fd14f66 --- /dev/null +++ b/1001-1100/1092. Shortest Common Supersequence .md @@ -0,0 +1,79 @@ +# 1092. Shortest Common Supersequence + +- Difficulty: Hard. +- Related Topics: String, Dynamic Programming. +- Similar Questions: Longest Common Subsequence, Shortest String That Contains Three Strings. + +## Problem + +Given two strings `str1` and `str2`, return **the shortest string that has both **`str1`** and **`str2`** as **subsequences****. If there are multiple valid strings, return **any** of them. + +A string `s` is a **subsequence** of string `t` if deleting some number of characters from `t` (possibly `0`) results in the string `s`. + +  +Example 1: + +``` +Input: str1 = "abac", str2 = "cab" +Output: "cabac" +Explanation: +str1 = "abac" is a subsequence of "cabac" because we can delete the first "c". +str2 = "cab" is a subsequence of "cabac" because we can delete the last "ac". +The answer provided is the shortest such string that satisfies these properties. +``` + +Example 2: + +``` +Input: str1 = "aaaaaaaa", str2 = "aaaaaaaa" +Output: "aaaaaaaa" +``` + +  +**Constraints:** + + + +- `1 <= str1.length, str2.length <= 1000` + +- `str1` and `str2` consist of lowercase English letters. + + + +## Solution + +```javascript +/** + * @param {string} str1 + * @param {string} str2 + * @return {string} + */ +var shortestCommonSupersequence = function(str1, str2) { + var dp = Array(str1.length).fill(0).map(() => Array(str2.length)); + var helper = function(i, j) { + if (i === str1.length) return str2.slice(j); + if (j === str2.length) return str1.slice(i); + if (dp[i][j] !== undefined) return dp[i][j]; + var res = ''; + if (str1[i] === str2[j]) { + res = str1[i] + helper(i + 1, j + 1); + } else { + var s1 = str1[i] + helper(i + 1, j); + var s2 = str2[j] + helper(i, j + 1); + res = s1.length < s2.length ? s1 : s2; + } + dp[i][j] = res; + return res; + }; + return helper(0, 0); +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * m). +* Space complexity : O(n * m). 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/1101-1200/1143. Longest Common Subsequence.md b/1101-1200/1143. Longest Common Subsequence.md new file mode 100644 index 0000000..08e3aa8 --- /dev/null +++ b/1101-1200/1143. Longest Common Subsequence.md @@ -0,0 +1,92 @@ +# 1143. Longest Common Subsequence + +- Difficulty: Medium. +- Related Topics: String, Dynamic Programming. +- Similar Questions: Longest Palindromic Subsequence, Delete Operation for Two Strings, Shortest Common Supersequence , Maximize Number of Subsequences in a String, Subsequence With the Minimum Score. + +## Problem + +Given two strings `text1` and `text2`, return **the length of their longest **common subsequence**. **If there is no **common subsequence**, return `0`. + +A **subsequence** of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. + + + +- For example, `"ace"` is a subsequence of `"abcde"`. + + +A **common subsequence** of two strings is a subsequence that is common to both strings. + +  +Example 1: + +``` +Input: text1 = "abcde", text2 = "ace" +Output: 3 +Explanation: The longest common subsequence is "ace" and its length is 3. +``` + +Example 2: + +``` +Input: text1 = "abc", text2 = "abc" +Output: 3 +Explanation: The longest common subsequence is "abc" and its length is 3. +``` + +Example 3: + +``` +Input: text1 = "abc", text2 = "def" +Output: 0 +Explanation: There is no such common subsequence, so the result is 0. +``` + +  +**Constraints:** + + + +- `1 <= text1.length, text2.length <= 1000` + +- `text1` and `text2` consist of only lowercase English characters. + + + +## Solution + +```javascript +/** + * @param {string} text1 + * @param {string} text2 + * @return {number} + */ +var longestCommonSubsequence = function(text1, text2) { + var dp = Array(text1.length).fill(0).map(() => Array(text2.length)); + var dfs = function(i, j) { + if (i === text1.length || j === text2.length) return 0; + if (dp[i][j] !== undefined) return dp[i][j]; + if (text1[i] === text2[j]) { + dp[i][j] = 1 + dfs(i + 1, j + 1); + } else { + dp[i][j] = Math.max( + dfs(i + 1, j), + dfs(i, j + 1), + dfs(i + 1, j + 1), + ); + } + return dp[i][j]; + }; + dfs(0, 0, 0); + return dp[0][0]; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * m). +* Space complexity : O(n * m). diff --git a/1101-1200/1155. Number of Dice Rolls With Target Sum.md b/1101-1200/1155. Number of Dice Rolls With Target Sum.md new file mode 100644 index 0000000..abdccca --- /dev/null +++ b/1101-1200/1155. Number of Dice Rolls With Target Sum.md @@ -0,0 +1,88 @@ +# 1155. Number of Dice Rolls With Target Sum + +- Difficulty: Medium. +- Related Topics: Dynamic Programming. +- Similar Questions: Equal Sum Arrays With Minimum Number of Operations, Find Missing Observations. + +## Problem + +You have `n` dice, and each die has `k` faces numbered from `1` to `k`. + +Given three integers `n`, `k`, and `target`, return **the number of possible ways (out of the **`kn`** total ways) ****to roll the dice, so the sum of the face-up numbers equals **`target`. Since the answer may be too large, return it **modulo** `109 + 7`. + +  +Example 1: + +``` +Input: n = 1, k = 6, target = 3 +Output: 1 +Explanation: You throw one die with 6 faces. +There is only one way to get a sum of 3. +``` + +Example 2: + +``` +Input: n = 2, k = 6, target = 7 +Output: 6 +Explanation: You throw two dice, each with 6 faces. +There are 6 ways to get a sum of 7: 1+6, 2+5, 3+4, 4+3, 5+2, 6+1. +``` + +Example 3: + +``` +Input: n = 30, k = 30, target = 500 +Output: 222616187 +Explanation: The answer must be returned modulo 109 + 7. +``` + +  +**Constraints:** + + + +- `1 <= n, k <= 30` + +- `1 <= target <= 1000` + + + +## Solution + +```javascript +/** + * @param {number} n + * @param {number} k + * @param {number} target + * @return {number} + */ +var numRollsToTarget = function(n, k, target) { + var dp = Array(n + 1).fill(0).map(() => ({})); + return helper(n, k, target, dp); +}; + +var helper = function(n, k, target, dp) { + if (dp[n][target] !== undefined) return dp[n][target]; + if (n === 0 && target === 0) return 1; + if (n <= 0 || target <= 0) return 0; + var res = 0; + var mod = Math.pow(10, 9) + 7; + for (var i = 1; i <= k; i++) { + if (target < i) break; + res += helper(n - 1, k, target - i, dp); + res %= mod; + } + dp[n][target] = res; + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * target). +* Space complexity : O(n * target). diff --git a/1201-1300/1207. Unique Number of Occurrences.md b/1201-1300/1207. Unique Number of Occurrences.md new file mode 100644 index 0000000..dabe963 --- /dev/null +++ b/1201-1300/1207. Unique Number of Occurrences.md @@ -0,0 +1,74 @@ +# 1207. Unique Number of Occurrences + +- Difficulty: Easy. +- Related Topics: Array, Hash Table. +- Similar Questions: . + +## Problem + +Given an array of integers `arr`, return `true` **if the number of occurrences of each value in the array is **unique** or **`false`** otherwise**. + +  +Example 1: + +``` +Input: arr = [1,2,2,1,1,3] +Output: true +Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences. +``` + +Example 2: + +``` +Input: arr = [1,2] +Output: false +``` + +Example 3: + +``` +Input: arr = [-3,0,1,-3,1,1,1,-3,10,0] +Output: true +``` + +  +**Constraints:** + + + +- `1 <= arr.length <= 1000` + +- `-1000 <= arr[i] <= 1000` + + + +## Solution + +```javascript +/** + * @param {number[]} arr + * @return {boolean} + */ +var uniqueOccurrences = function(arr) { + var numMap = {}; + for (var i = 0; i < arr.length; i++) { + numMap[arr[i]] = (numMap[arr[i]] || 0) + 1; + } + var occureMap = {}; + var nums = Object.keys(numMap); + for (var j = 0; j < nums.length; j++) { + if (occureMap[numMap[nums[j]]]) return false; + occureMap[numMap[nums[j]]] = true; + } + return true; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/1201-1300/1235. Maximum Profit in Job Scheduling.md b/1201-1300/1235. Maximum Profit in Job Scheduling.md new file mode 100644 index 0000000..cd30f2a --- /dev/null +++ b/1201-1300/1235. Maximum Profit in Job Scheduling.md @@ -0,0 +1,120 @@ +# 1235. Maximum Profit in Job Scheduling + +- Difficulty: Hard. +- Related Topics: Array, Binary Search, Dynamic Programming, Sorting. +- Similar Questions: Maximum Earnings From Taxi, Two Best Non-Overlapping Events. + +## Problem + +We have `n` jobs, where every job is scheduled to be done from `startTime[i]` to `endTime[i]`, obtaining a profit of `profit[i]`. + +You're given the `startTime`, `endTime` and `profit` arrays, return the maximum profit you can take such that there are no two jobs in the subset with overlapping time range. + +If you choose a job that ends at time `X` you will be able to start another job that starts at time `X`. + +  +Example 1: + + +![](https://assets.leetcode.com/uploads/2019/10/10/sample1_1584.png) + + +``` +Input: startTime = [1,2,3,3], endTime = [3,4,5,6], profit = [50,10,40,70] +Output: 120 +Explanation: The subset chosen is the first and fourth job. +Time range [1-3]+[3-6] , we get profit of 120 = 50 + 70. +``` + +Example 2: + + +![](https://assets.leetcode.com/uploads/2019/10/10/sample22_1584.png) + + +``` +Input: startTime = [1,2,3,4,6], endTime = [3,5,10,6,9], profit = [20,20,100,70,60] +Output: 150 +Explanation: The subset chosen is the first, fourth and fifth job. +Profit obtained 150 = 20 + 70 + 60. +``` + +Example 3: + + +![](https://assets.leetcode.com/uploads/2019/10/10/sample3_1584.png) + + +``` +Input: startTime = [1,1,1], endTime = [2,3,4], profit = [5,6,4] +Output: 6 +``` + +  +**Constraints:** + + + +- `1 <= startTime.length == endTime.length == profit.length <= 5 * 104` + +- `1 <= startTime[i] < endTime[i] <= 109` + +- `1 <= profit[i] <= 104` + + + +## Solution + +```javascript +/** + * @param {number[]} startTime + * @param {number[]} endTime + * @param {number[]} profit + * @return {number} + */ +var jobScheduling = function(startTime, endTime, profit) { + var jobs = startTime.map((_, i) => [startTime[i], endTime[i], profit[i]]); + jobs.sort((a, b) => { + return a[0] === b[0] + ? (a[1] === b[1] ? a[2] - b[2] : a[1] - b[1]) + : a[0] - b[0]; + }); + return dfs(jobs, 0, Array(jobs.length)); +}; + +var dfs = function(jobs, i, dp) { + if (i === jobs.length) return 0; + if (dp[i] !== undefined) return dp[i]; + dp[i] = Math.max( + // take job i + jobs[i][2] + dfs(jobs, next(i, jobs), dp), + // do not take job i + dfs(jobs, i + 1, dp), + ); + return dp[i]; +}; + +var next = function(i, jobs) { + // binary search job j which starts after job i ends. + var left = 0; + var right = jobs.length - 1; + while (left < right) { + var mid = left + Math.floor((right - left) / 2); + if (jobs[i][1] > jobs[mid][0]) { + left = mid + 1; + } else { + right = mid; + } + } + return jobs[i][1] <= jobs[left][0] ? left : jobs.length; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * log(n)). +* Space complexity : O(n). diff --git a/1201-1300/1239. Maximum Length of a Concatenated String with Unique Characters.md b/1201-1300/1239. Maximum Length of a Concatenated String with Unique Characters.md new file mode 100644 index 0000000..eed8a83 --- /dev/null +++ b/1201-1300/1239. Maximum Length of a Concatenated String with Unique Characters.md @@ -0,0 +1,103 @@ +# 1239. Maximum Length of a Concatenated String with Unique Characters + +- Difficulty: Medium. +- Related Topics: Array, String, Backtracking, Bit Manipulation. +- Similar Questions: . + +## Problem + +You are given an array of strings `arr`. A string `s` is formed by the **concatenation** of a **subsequence** of `arr` that has **unique characters**. + +Return **the **maximum** possible length** of `s`. + +A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. + +  +Example 1: + +``` +Input: arr = ["un","iq","ue"] +Output: 4 +Explanation: All the valid concatenations are: +- "" +- "un" +- "iq" +- "ue" +- "uniq" ("un" + "iq") +- "ique" ("iq" + "ue") +Maximum length is 4. +``` + +Example 2: + +``` +Input: arr = ["cha","r","act","ers"] +Output: 6 +Explanation: Possible longest valid concatenations are "chaers" ("cha" + "ers") and "acters" ("act" + "ers"). +``` + +Example 3: + +``` +Input: arr = ["abcdefghijklmnopqrstuvwxyz"] +Output: 26 +Explanation: The only string in arr has all 26 characters. +``` + +  +**Constraints:** + + + +- `1 <= arr.length <= 16` + +- `1 <= arr[i].length <= 26` + +- `arr[i]` contains only lowercase English letters. + + + +## Solution + +```javascript +/** + * @param {string[]} arr + * @return {number} + */ +var maxLength = function(arr) { + var maskArr = []; + var newArr = []; + var a = 'a'.charCodeAt(0); + outter: for (var i = 0; i < arr.length; i++) { + var num = 0; + for (var j = 0; j < arr[i].length; j++) { + var bit = (1 << (arr[i].charCodeAt(j) - a)); + if ((bit & num) !== 0) { + continue outter; + } + num |= bit; + } + maskArr.push(num); + newArr.push(arr[i]); + } + return dfs(newArr, maskArr, 0, 0); +}; + +var dfs = function(arr, maskArr, num, i) { + if (i === arr.length) return 0; + var len = dfs(arr, maskArr, num, i + 1); + if ((maskArr[i] & num) === 0) { + len = Math.max(len, arr[i].length + dfs(arr, maskArr, maskArr[i] | num, i + 1)); + } + return len; +}; +``` + +**Explain:** + +Bit mask + DFS. + +**Complexity:** + +* Time complexity : O(2^n). +* Space complexity : O(n). diff --git a/1201-1300/1287. Element Appearing More Than 25% In Sorted Array.md b/1201-1300/1287. Element Appearing More Than 25% In Sorted Array.md new file mode 100644 index 0000000..40a8e18 --- /dev/null +++ b/1201-1300/1287. Element Appearing More Than 25% In Sorted Array.md @@ -0,0 +1,66 @@ +# 1287. Element Appearing More Than 25% In Sorted Array + +- Difficulty: Easy. +- Related Topics: Array. +- Similar Questions: . + +## Problem + +Given an integer array **sorted** in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time, return that integer. + +  +Example 1: + +``` +Input: arr = [1,2,2,6,6,6,6,7,10] +Output: 6 +``` + +Example 2: + +``` +Input: arr = [1,1] +Output: 1 +``` + +  +**Constraints:** + + + +- `1 <= arr.length <= 104` + +- `0 <= arr[i] <= 105` + + + +## Solution + +```javascript +/** + * @param {number[]} arr + * @return {number} + */ +var findSpecialInteger = function(arr) { + var len = 0; + var num = -1; + for (var i = 0; i < arr.length; i++) { + if (arr[i] === num) { + len += 1; + } else { + num = arr[i]; + len = 1; + } + if (len > (arr.length / 4)) return num; + } +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/1201-1300/1289. Minimum Falling Path Sum II.md b/1201-1300/1289. Minimum Falling Path Sum II.md new file mode 100644 index 0000000..55e215a --- /dev/null +++ b/1201-1300/1289. Minimum Falling Path Sum II.md @@ -0,0 +1,88 @@ +# 1289. Minimum Falling Path Sum II + +- Difficulty: Hard. +- Related Topics: Array, Dynamic Programming, Matrix. +- Similar Questions: Minimum Falling Path Sum. + +## Problem + +Given an `n x n` integer matrix `grid`, return **the minimum sum of a **falling path with non-zero shifts****. + +A **falling path with non-zero shifts** is a choice of exactly one element from each row of `grid` such that no two elements chosen in adjacent rows are in the same column. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2021/08/10/falling-grid.jpg) + +``` +Input: grid = [[1,2,3],[4,5,6],[7,8,9]] +Output: 13 +Explanation: +The possible falling paths are: +[1,5,9], [1,5,7], [1,6,7], [1,6,8], +[2,4,8], [2,4,9], [2,6,7], [2,6,8], +[3,4,8], [3,4,9], [3,5,7], [3,5,9] +The falling path with the smallest sum is [1,5,7], so the answer is 13. +``` + +Example 2: + +``` +Input: grid = [[7]] +Output: 7 +``` + +  +**Constraints:** + + + +- `n == grid.length == grid[i].length` + +- `1 <= n <= 200` + +- `-99 <= grid[i][j] <= 99` + + + +## Solution + +```javascript +/** + * @param {number[][]} grid + * @return {number} + */ +var minFallingPathSum = function(grid) { + for (var i = 1; i < grid.length; i++) { + var [minIndex, secondMinIndex] = findMinIndexs(grid[i - 1]); + for (var j = 0; j < grid[i].length; j++) { + grid[i][j] += grid[i - 1][minIndex === j ? secondMinIndex : minIndex]; + } + } + return Math.min(...grid[grid.length - 1]); +}; + +var findMinIndexs = function(arr) { + var minIndex = arr[0] > arr[1] ? 1 : 0; + var secondMinIndex = arr[0] > arr[1] ? 0 : 1; + for (var i = 2; i < arr.length; i++) { + if (arr[i] < arr[minIndex]) { + secondMinIndex = minIndex; + minIndex = i; + } else if (arr[i] < arr[secondMinIndex]) { + secondMinIndex = i; + } + } + return [minIndex, secondMinIndex]; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * m). +* Space complexity : O(1). diff --git a/1201-1300/1291. Sequential Digits.md b/1201-1300/1291. Sequential Digits.md new file mode 100644 index 0000000..eb4b307 --- /dev/null +++ b/1201-1300/1291. Sequential Digits.md @@ -0,0 +1,65 @@ +# 1291. Sequential Digits + +- Difficulty: Medium. +- Related Topics: Enumeration. +- Similar Questions: . + +## Problem + +An integer has **sequential digits** if and only if each digit in the number is one more than the previous digit. + +Return a **sorted** list of all the integers in the range `[low, high]` inclusive that have sequential digits. + +  +Example 1: +``` +Input: low = 100, high = 300 +Output: [123,234] +```Example 2: +``` +Input: low = 1000, high = 13000 +Output: [1234,2345,3456,4567,5678,6789,12345] +``` +  +**Constraints:** + + + +- `10 <= low <= high <= 10^9` + + + +## Solution + +```javascript +/** + * @param {number} low + * @param {number} high + * @return {number[]} + */ +var sequentialDigits = function(low, high) { + var len1 = low.toString().length; + var len2 = high.toString().length; + var res = []; + for (var i = len1; i <= len2; i++) { + for (var j = 1; j <= 9 - i + 1; j++) { + var num = Array(i).fill(0) + .map((_, index) => j + index) + .reduce((sum, n) => sum * 10 + n, 0); + if (num >= low && num <= high) { + res.push(num); + } + } + } + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(log(n)). +* Space complexity : O(log(n)). 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/1301-1400/1335. Minimum Difficulty of a Job Schedule.md b/1301-1400/1335. Minimum Difficulty of a Job Schedule.md new file mode 100644 index 0000000..1bbf16d --- /dev/null +++ b/1301-1400/1335. Minimum Difficulty of a Job Schedule.md @@ -0,0 +1,95 @@ +# 1335. Minimum Difficulty of a Job Schedule + +- Difficulty: Hard. +- Related Topics: Array, Dynamic Programming. +- Similar Questions: . + +## Problem + +You want to schedule a list of jobs in `d` days. Jobs are dependent (i.e To work on the `ith` job, you have to finish all the jobs `j` where `0 <= j < i`). + +You have to finish **at least** one task every day. The difficulty of a job schedule is the sum of difficulties of each day of the `d` days. The difficulty of a day is the maximum difficulty of a job done on that day. + +You are given an integer array `jobDifficulty` and an integer `d`. The difficulty of the `ith` job is `jobDifficulty[i]`. + +Return **the minimum difficulty of a job schedule**. If you cannot find a schedule for the jobs return `-1`. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2020/01/16/untitled.png) + +``` +Input: jobDifficulty = [6,5,4,3,2,1], d = 2 +Output: 7 +Explanation: First day you can finish the first 5 jobs, total difficulty = 6. +Second day you can finish the last job, total difficulty = 1. +The difficulty of the schedule = 6 + 1 = 7 +``` + +Example 2: + +``` +Input: jobDifficulty = [9,9,9], d = 4 +Output: -1 +Explanation: If you finish a job per day you will still have a free day. you cannot find a schedule for the given jobs. +``` + +Example 3: + +``` +Input: jobDifficulty = [1,1,1], d = 3 +Output: 3 +Explanation: The schedule is one job per day. total difficulty will be 3. +``` + +  +**Constraints:** + + + +- `1 <= jobDifficulty.length <= 300` + +- `0 <= jobDifficulty[i] <= 1000` + +- `1 <= d <= 10` + + + +## Solution + +```javascript +/** + * @param {number[]} jobDifficulty + * @param {number} d + * @return {number} + */ +var minDifficulty = function(jobDifficulty, d) { + var dp = Array(jobDifficulty.length).fill(0).map(() => Array(d)); + return helper(jobDifficulty, d, 0, dp); +}; + +var helper = function(jobs, d, index, dp) { + if (jobs.length < d) return -1; + if (d === 0 && index === jobs.length) return 0; + if (d === 0) return Number.MAX_SAFE_INTEGER; + if (dp[index][d] !== undefined) return dp[index][d]; + var min = Number.MAX_SAFE_INTEGER; + var maxDifficulty = Number.MIN_SAFE_INTEGER; + for (var i = index; i <= jobs.length - d; i++) { + maxDifficulty = Math.max(maxDifficulty, jobs[i]); + min = Math.min(min, maxDifficulty + helper(jobs, d - 1, i + 1, dp)); + } + dp[index][d] = min; + return min; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * m). +* Space complexity : O(n * m). diff --git a/1301-1400/1347. Minimum Number of Steps to Make Two Strings Anagram.md b/1301-1400/1347. Minimum Number of Steps to Make Two Strings Anagram.md new file mode 100644 index 0000000..c01da89 --- /dev/null +++ b/1301-1400/1347. Minimum Number of Steps to Make Two Strings Anagram.md @@ -0,0 +1,85 @@ +# 1347. Minimum Number of Steps to Make Two Strings Anagram + +- Difficulty: Medium. +- Related Topics: Hash Table, String, Counting. +- Similar Questions: Determine if Two Strings Are Close, Minimum Number of Steps to Make Two Strings Anagram II. + +## Problem + +You are given two strings of the same length `s` and `t`. In one step you can choose **any character** of `t` and replace it with **another character**. + +Return **the minimum number of steps** to make `t` an anagram of `s`. + +An **Anagram** of a string is a string that contains the same characters with a different (or the same) ordering. + +  +Example 1: + +``` +Input: s = "bab", t = "aba" +Output: 1 +Explanation: Replace the first 'a' in t with b, t = "bba" which is anagram of s. +``` + +Example 2: + +``` +Input: s = "leetcode", t = "practice" +Output: 5 +Explanation: Replace 'p', 'r', 'a', 'i' and 'c' from t with proper characters to make t anagram of s. +``` + +Example 3: + +``` +Input: s = "anagram", t = "mangaar" +Output: 0 +Explanation: "anagram" and "mangaar" are anagrams. +``` + +  +**Constraints:** + + + +- `1 <= s.length <= 5 * 104` + +- `s.length == t.length` + +- `s` and `t` consist of lowercase English letters only. + + + +## Solution + +```javascript +/** + * @param {string} s + * @param {string} t + * @return {number} + */ +var minSteps = function(s, t) { + var map = Array(26).fill(0); + var a = 'a'.charCodeAt(0); + for (var i = 0; i < t.length; i++) { + map[t.charCodeAt(i) - a]++; + } + for (var j = 0; j < s.length; j++) { + map[s.charCodeAt(j) - a]--; + } + var res = 0; + for (var k = 0; k < 26; k++) { + res += Math.abs(map[k]); + } + return res / 2; +} +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/1401-1500/1422. Maximum Score After Splitting a String.md b/1401-1500/1422. Maximum Score After Splitting a String.md new file mode 100644 index 0000000..02d03b1 --- /dev/null +++ b/1401-1500/1422. Maximum Score After Splitting a String.md @@ -0,0 +1,84 @@ +# 1422. Maximum Score After Splitting a String + +- Difficulty: Easy. +- Related Topics: String. +- Similar Questions: . + +## Problem + +Given a string `s` of zeros and ones, **return the maximum score after splitting the string into two **non-empty** substrings** (i.e. **left** substring and **right** substring). + +The score after splitting a string is the number of **zeros** in the **left** substring plus the number of **ones** in the **right** substring. + +  +Example 1: + +``` +Input: s = "011101" +Output: 5 +Explanation: +All possible ways of splitting s into two non-empty substrings are: +left = "0" and right = "11101", score = 1 + 4 = 5 +left = "01" and right = "1101", score = 1 + 3 = 4 +left = "011" and right = "101", score = 1 + 2 = 3 +left = "0111" and right = "01", score = 1 + 1 = 2 +left = "01110" and right = "1", score = 2 + 1 = 3 +``` + +Example 2: + +``` +Input: s = "00111" +Output: 5 +Explanation: When left = "00" and right = "111", we get the maximum score = 2 + 3 = 5 +``` + +Example 3: + +``` +Input: s = "1111" +Output: 3 +``` + +  +**Constraints:** + + + +- `2 <= s.length <= 500` + +- The string `s` consists of characters `'0'` and `'1'` only. + + + +## Solution + +```javascript +/** + * @param {string} s + * @return {number} + */ +var maxScore = function(s) { + var numOfOnes = 0; + var numOfZeros = 0; + var max = 0; + for (var i = 0; i < s.length; i++) { + s[i] === '1' && numOfOnes++; + } + for (var j = 0; j < s.length - 1; j++) { + s[j] === '0' && numOfZeros++; + s[j] === '1' && numOfOnes--; + max = Math.max(numOfOnes + numOfZeros, max); + } + return max; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(0). diff --git a/1401-1500/1436. Destination City.md b/1401-1500/1436. Destination City.md new file mode 100644 index 0000000..e8a4379 --- /dev/null +++ b/1401-1500/1436. Destination City.md @@ -0,0 +1,87 @@ +# 1436. Destination City + +- Difficulty: Easy. +- Related Topics: Hash Table, String. +- Similar Questions: . + +## Problem + +You are given the array `paths`, where `paths[i] = [cityAi, cityBi]` means there exists a direct path going from `cityAi` to `cityBi`. **Return the destination city, that is, the city without any path outgoing to another city.** + +It is guaranteed that the graph of paths forms a line without any loop, therefore, there will be exactly one destination city. + +  +Example 1: + +``` +Input: paths = [["London","New York"],["New York","Lima"],["Lima","Sao Paulo"]] +Output: "Sao Paulo" +Explanation: Starting at "London" city you will reach "Sao Paulo" city which is the destination city. Your trip consist of: "London" -> "New York" -> "Lima" -> "Sao Paulo". +``` + +Example 2: + +``` +Input: paths = [["B","C"],["D","B"],["C","A"]] +Output: "A" +Explanation: All possible trips are:  +"D" -> "B" -> "C" -> "A".  +"B" -> "C" -> "A".  +"C" -> "A".  +"A".  +Clearly the destination city is "A". +``` + +Example 3: + +``` +Input: paths = [["A","Z"]] +Output: "Z" +``` + +  +**Constraints:** + + + +- `1 <= paths.length <= 100` + +- `paths[i].length == 2` + +- `1 <= cityAi.length, cityBi.length <= 10` + +- `cityAi != cityBi` + +- All strings consist of lowercase and uppercase English letters and the space character. + + + +## Solution + +```javascript +/** + * @param {string[][]} paths + * @return {string} + */ +var destCity = function(paths) { + var map = {}; + for (var i = 0; i < paths.length; i++) { + map[paths[i][0]] = map[paths[i][0]] || 0; + map[paths[i][1]] = map[paths[i][1]] || 0; + map[paths[i][0]] += 1; + } + var cities = Object.keys(map); + for (var j = 0; j < cities.length; j++) { + if (map[cities[j]] === 0) return cities[j]; + } +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/1401-1500/1457. Pseudo-Palindromic Paths in a Binary Tree.md b/1401-1500/1457. Pseudo-Palindromic Paths in a Binary Tree.md new file mode 100644 index 0000000..82df309 --- /dev/null +++ b/1401-1500/1457. Pseudo-Palindromic Paths in a Binary Tree.md @@ -0,0 +1,100 @@ +# 1457. Pseudo-Palindromic Paths in a Binary Tree + +- Difficulty: Medium. +- Related Topics: Bit Manipulation, Tree, Depth-First Search, Breadth-First Search, Binary Tree. +- Similar Questions: . + +## Problem + +Given a binary tree where node values are digits from 1 to 9. A path in the binary tree is said to be **pseudo-palindromic** if at least one permutation of the node values in the path is a palindrome. + +**Return the number of **pseudo-palindromic** paths going from the root node to leaf nodes.** + +  +Example 1: + + +![](https://assets.leetcode.com/uploads/2020/05/06/palindromic_paths_1.png) + + +``` +Input: root = [2,3,1,3,1,null,1] +Output: 2 +Explanation: The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the red path [2,3,3], the green path [2,1,1], and the path [2,3,1]. Among these paths only red path and green path are pseudo-palindromic paths since the red path [2,3,3] can be rearranged in [3,2,3] (palindrome) and the green path [2,1,1] can be rearranged in [1,2,1] (palindrome). +``` + +Example 2: + + +![](https://assets.leetcode.com/uploads/2020/05/07/palindromic_paths_2.png) + + +``` +Input: root = [2,1,1,1,3,null,null,null,null,null,1] +Output: 1 +Explanation: The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the green path [2,1,1], the path [2,1,3,1], and the path [2,1]. Among these paths only the green path is pseudo-palindromic since [2,1,1] can be rearranged in [1,2,1] (palindrome). +``` + +Example 3: + +``` +Input: root = [9] +Output: 1 +``` + +  +**Constraints:** + + + +- The number of nodes in the tree is in the range `[1, 105]`. + +- `1 <= Node.val <= 9` + + + +## 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 + * @return {number} + */ +var pseudoPalindromicPaths = function(root) { + return dfs(root, Array(10).fill(0), 0); +}; + +var dfs = function(node, map, numOfOdd) { + if (!node) return 0; + if (map[node.val] % 2) { + numOfOdd -= 1; + } else { + numOfOdd += 1; + } + if (!node.left && !node.right) { + return numOfOdd <= 1 ? 1 : 0; + } + map[node.val] += 1; + var res = dfs(node.left, map, numOfOdd) + + dfs(node.right, map, numOfOdd); + map[node.val] -= 1; + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/1401-1500/1464. Maximum Product of Two Elements in an Array.md b/1401-1500/1464. Maximum Product of Two Elements in an Array.md new file mode 100644 index 0000000..fb92014 --- /dev/null +++ b/1401-1500/1464. Maximum Product of Two Elements in an Array.md @@ -0,0 +1,88 @@ +# 1464. Maximum Product of Two Elements in an Array + +- Difficulty: Easy. +- Related Topics: Array, Sorting, Heap (Priority Queue). +- Similar Questions: . + +## Problem + +Given the array of integers `nums`, you will choose two different indices `i` and `j` of that array. **Return the maximum value of** `(nums[i]-1)*(nums[j]-1)`. +  +Example 1: + +``` +Input: nums = [3,4,5,2] +Output: 12 +Explanation: If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12. +``` + +Example 2: + +``` +Input: nums = [1,5,4,5] +Output: 16 +Explanation: Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)*(5-1) = 16. +``` + +Example 3: + +``` +Input: nums = [3,7] +Output: 12 +``` + +  +**Constraints:** + + + +- `2 <= nums.length <= 500` + +- `1 <= nums[i] <= 10^3` + + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @return {number} + */ +var maxProduct = function(nums) { + if (nums.length === 2) { + return (nums[0] - 1) * (nums[1] - 1); + } + var minNegativeNum = 0; + var secondMinNegativeNum = 0; + var maxPositiveNum = 0; + var secondMaxPositiveNum = 0; + for (var i = 0; i < nums.length; i++) { + var num = nums[i] - 1; + if (num < minNegativeNum) { + secondMinNegativeNum = minNegativeNum; + minNegativeNum = num; + } else if (num < secondMinNegativeNum) { + secondMinNegativeNum = num; + } else if (num > maxPositiveNum) { + secondMaxPositiveNum = maxPositiveNum; + maxPositiveNum = num; + } else if (num > secondMaxPositiveNum) { + secondMaxPositiveNum = num; + } + } + return Math.max( + minNegativeNum * secondMinNegativeNum, + maxPositiveNum * secondMaxPositiveNum, + ); +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/1401-1500/1481. Least Number of Unique Integers after K Removals.md b/1401-1500/1481. Least Number of Unique Integers after K Removals.md new file mode 100644 index 0000000..9c739ce --- /dev/null +++ b/1401-1500/1481. Least Number of Unique Integers after K Removals.md @@ -0,0 +1,114 @@ +# 1481. Least Number of Unique Integers after K Removals + +- Difficulty: Medium. +- Related Topics: Array, Hash Table, Greedy, Sorting, Counting. +- Similar Questions: . + +## Problem + +Given an array of integers `arr` and an integer `k`. Find the **least number of unique integers** after removing **exactly** `k` elements**.** + + + + +  +Example 1: + +``` +Input: arr = [5,5,4], k = 1 +Output: 1 +Explanation: Remove the single 4, only 5 is left. +``` +Example 2: + +``` +Input: arr = [4,3,1,1,3,3,2], k = 3 +Output: 2 +Explanation: Remove 4, 2 and either one of the two 1s or three 3s. 1 and 3 will be left. +``` + +  +**Constraints:** + + + +- `1 <= arr.length <= 10^5` + +- `1 <= arr[i] <= 10^9` + +- `0 <= k <= arr.length` + + +## Solution 1 + +```javascript +/** + * @param {number[]} arr + * @param {number} k + * @return {number} + */ +var findLeastNumOfUniqueInts = function(arr, k) { + var map = {}; + for (var i = 0; i < arr.length; i++) { + map[arr[i]] = (map[arr[i]] || 0) + 1; + } + var nums = Array.from(Object.values(map)); + nums.sort((a, b) => a - b); + while (k > 0 && nums.length && k >= nums[0]) { + k -= nums.shift(); + } + return nums.length; +}; +``` + +**Explain:** + +Sort. + +**Complexity:** + +* Time complexity : O(n * log(n)). +* Space complexity : O(n). + +## Solution 2 + +```javascript +/** + * @param {number[]} arr + * @param {number} k + * @return {number} + */ +var findLeastNumOfUniqueInts = function(arr, k) { + var map = {}; + var nums = Array(arr.length + 1).fill(0); + for (var i = 0; i < arr.length; i++) { + if (map[arr[i]] === undefined) { + map[arr[i]] = 1; + } else { + nums[map[arr[i]]] -= 1; + map[arr[i]] += 1; + } + nums[map[arr[i]]] += 1; + } + var num = 0; + for (var j = 0; j < nums.length; j++) { + if (k > 0) { + var tmp = nums[j]; + nums[j] = Math.max(0, nums[j] - Math.floor(k / j)); + k -= tmp * j; + } + num += nums[j]; + } + return num; +}; +``` + +**Explain:** + +Counting sort. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). + diff --git a/1401-1500/1496. Path Crossing.md b/1401-1500/1496. Path Crossing.md new file mode 100644 index 0000000..f625067 --- /dev/null +++ b/1401-1500/1496. Path Crossing.md @@ -0,0 +1,77 @@ +# 1496. Path Crossing + +- Difficulty: Easy. +- Related Topics: Hash Table, String. +- Similar Questions: . + +## Problem + +Given a string `path`, where `path[i] = 'N'`, `'S'`, `'E'` or `'W'`, each representing moving one unit north, south, east, or west, respectively. You start at the origin `(0, 0)` on a 2D plane and walk on the path specified by `path`. + +Return `true` **if the path crosses itself at any point, that is, if at any time you are on a location you have previously visited**. Return `false` otherwise. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2020/06/10/screen-shot-2020-06-10-at-123929-pm.png) + +``` +Input: path = "NES" +Output: false +Explanation: Notice that the path doesn't cross any point more than once. +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2020/06/10/screen-shot-2020-06-10-at-123843-pm.png) + +``` +Input: path = "NESWW" +Output: true +Explanation: Notice that the path visits the origin twice. +``` + +  +**Constraints:** + + + +- `1 <= path.length <= 104` + +- `path[i]` is either `'N'`, `'S'`, `'E'`, or `'W'`. + + + +## Solution + +```javascript +/** + * @param {string} path + * @return {boolean} + */ +var isPathCrossing = function(path) { + var num = 0; + var map = { + N: 1, + S: -1, + E: 10000, + W: -10000, + }; + var visited = { '0': true }; + for (var i = 0; i < path.length; i++) { + num += map[path[i]]; + if (visited[num]) return true; + visited[num] = true; + } + return false; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). 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/1531. String Compression II.md b/1501-1600/1531. String Compression II.md new file mode 100644 index 0000000..66f8d52 --- /dev/null +++ b/1501-1600/1531. String Compression II.md @@ -0,0 +1,99 @@ +# 1531. String Compression II + +- Difficulty: Hard. +- Related Topics: String, Dynamic Programming. +- Similar Questions: . + +## Problem + +Run-length encoding is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string `"aabccc"` we replace `"aa"` by `"a2"` and replace `"ccc"` by `"c3"`. Thus the compressed string becomes `"a2bc3"`. + +Notice that in this problem, we are not adding `'1'` after single characters. + +Given a string `s` and an integer `k`. You need to delete **at most** `k` characters from `s` such that the run-length encoded version of `s` has minimum length. + +Find the **minimum length of the run-length encoded version of **`s`** after deleting at most **`k`** characters**. + +  +Example 1: + +``` +Input: s = "aaabcccd", k = 2 +Output: 4 +Explanation: Compressing s without deleting anything will give us "a3bc3d" of length 6. Deleting any of the characters 'a' or 'c' would at most decrease the length of the compressed string to 5, for instance delete 2 'a' then we will have s = "abcccd" which compressed is abc3d. Therefore, the optimal way is to delete 'b' and 'd', then the compressed version of s will be "a3c3" of length 4. +``` + +Example 2: + +``` +Input: s = "aabbaa", k = 2 +Output: 2 +Explanation: If we delete both 'b' characters, the resulting compressed string would be "a4" of length 2. +``` + +Example 3: + +``` +Input: s = "aaaaaaaaaaa", k = 0 +Output: 3 +Explanation: Since k is zero, we cannot delete anything. The compressed string is "a11" of length 3. +``` + +  +**Constraints:** + + + +- `1 <= s.length <= 100` + +- `0 <= k <= s.length` + +- `s` contains only lowercase English letters. + + + +## Solution + +```javascript +/** + * @param {string} s + * @param {number} k + * @return {number} + */ +var getLengthOfOptimalCompression = function(s, k) { + var cache = {}; + var helper = function(i, k, prev, prevCount) { + if (k < 0) return Number.MAX_SAFE_INTEGER; + if (i === s.length - k) return 0; + + var cacheKey = `${i}-${k}-${prev}-${prevCount}`; + if (cache[cacheKey] !== undefined) return cache[cacheKey]; + + var res = 0; + if (s[i] === prev) { + // keep + var diff = [1, 9, 99].includes(prevCount) ? 1 : 0; + res = diff + helper(i + 1, k, prev, prevCount + 1); + } else { + res = Math.min( + // delete + helper(i + 1, k - 1, prev, prevCount), + // keep + 1 + helper(i + 1, k, s[i], 1), + ); + } + cache[cacheKey] = res; + return res; + }; + return helper(0, k, '', 0); +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * k * n). +* Space complexity : O(n * k * n). 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/1501-1600/1578. Minimum Time to Make Rope Colorful.md b/1501-1600/1578. Minimum Time to Make Rope Colorful.md new file mode 100644 index 0000000..d4a225c --- /dev/null +++ b/1501-1600/1578. Minimum Time to Make Rope Colorful.md @@ -0,0 +1,100 @@ +# 1578. Minimum Time to Make Rope Colorful + +- Difficulty: Medium. +- Related Topics: Array, String, Dynamic Programming, Greedy. +- Similar Questions: . + +## Problem + +Alice has `n` balloons arranged on a rope. You are given a **0-indexed** string `colors` where `colors[i]` is the color of the `ith` balloon. + +Alice wants the rope to be **colorful**. She does not want **two consecutive balloons** to be of the same color, so she asks Bob for help. Bob can remove some balloons from the rope to make it **colorful**. You are given a **0-indexed** integer array `neededTime` where `neededTime[i]` is the time (in seconds) that Bob needs to remove the `ith` balloon from the rope. + +Return **the **minimum time** Bob needs to make the rope **colorful****. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2021/12/13/ballon1.jpg) + +``` +Input: colors = "abaac", neededTime = [1,2,3,4,5] +Output: 3 +Explanation: In the above image, 'a' is blue, 'b' is red, and 'c' is green. +Bob can remove the blue balloon at index 2. This takes 3 seconds. +There are no longer two consecutive balloons of the same color. Total time = 3. +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2021/12/13/balloon2.jpg) + +``` +Input: colors = "abc", neededTime = [1,2,3] +Output: 0 +Explanation: The rope is already colorful. Bob does not need to remove any balloons from the rope. +``` + +Example 3: + +![](https://assets.leetcode.com/uploads/2021/12/13/balloon3.jpg) + +``` +Input: colors = "aabaa", neededTime = [1,2,3,4,1] +Output: 2 +Explanation: Bob will remove the ballons at indices 0 and 4. Each ballon takes 1 second to remove. +There are no longer two consecutive balloons of the same color. Total time = 1 + 1 = 2. +``` + +  +**Constraints:** + + + +- `n == colors.length == neededTime.length` + +- `1 <= n <= 105` + +- `1 <= neededTime[i] <= 104` + +- `colors` contains only lowercase English letters. + + + +## Solution + +```javascript +/** + * @param {string} colors + * @param {number[]} neededTime + * @return {number} + */ +var minCost = function(colors, neededTime) { + var cost = 0; + var sum = 0; + var max = 0; + var color = ''; + for (var i = 0; i < colors.length; i++) { + if (color === colors[i]) { + sum += neededTime[i]; + max = Math.max(max, neededTime[i]); + } else { + color = colors[i]; + cost += (sum - max); + sum = neededTime[i]; + max = neededTime[i]; + } + } + cost += (sum - max); + return cost; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/1501-1600/1582. Special Positions in a Binary Matrix.md b/1501-1600/1582. Special Positions in a Binary Matrix.md new file mode 100644 index 0000000..de5e124 --- /dev/null +++ b/1501-1600/1582. Special Positions in a Binary Matrix.md @@ -0,0 +1,92 @@ +# 1582. Special Positions in a Binary Matrix + +- Difficulty: Easy. +- Related Topics: Array, Matrix. +- Similar Questions: Difference Between Ones and Zeros in Row and Column. + +## Problem + +Given an `m x n` binary matrix `mat`, return **the number of special positions in **`mat`**.** + +A position `(i, j)` is called **special** if `mat[i][j] == 1` and all other elements in row `i` and column `j` are `0` (rows and columns are **0-indexed**). + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2021/12/23/special1.jpg) + +``` +Input: mat = [[1,0,0],[0,0,1],[1,0,0]] +Output: 1 +Explanation: (1, 2) is a special position because mat[1][2] == 1 and all other elements in row 1 and column 2 are 0. +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2021/12/24/special-grid.jpg) + +``` +Input: mat = [[1,0,0],[0,1,0],[0,0,1]] +Output: 3 +Explanation: (0, 0), (1, 1) and (2, 2) are special positions. +``` + +  +**Constraints:** + + + +- `m == mat.length` + +- `n == mat[i].length` + +- `1 <= m, n <= 100` + +- `mat[i][j]` is either `0` or `1`. + + + +## Solution + +```javascript +/** + * @param {number[][]} mat + * @return {number} + */ +var numSpecial = function(mat) { + var res = 0; + for (var i = 0; i < mat.length; i++) { + var specialCol = -1; + var hasOnlyOne = false; + for (var j = 0; j < mat[i].length; j++) { + if (mat[i][j] === 1) { + if (specialCol === -1) { + specialCol = j; + hasOnlyOne = true; + } else { + hasOnlyOne = false; + } + } + } + if (!hasOnlyOne) continue; + var isValid = true; + for (var k = 0; k < mat.length; k++) { + if (mat[k][specialCol] === 1 && k !== i) { + isValid = false; + break; + } + } + if (isValid) res += 1; + } + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * m). +* Space complexity : O(1). diff --git a/1501-1600/1583. Count Unhappy Friends.md b/1501-1600/1583. Count Unhappy Friends.md new file mode 100644 index 0000000..89b4e75 --- /dev/null +++ b/1501-1600/1583. Count Unhappy Friends.md @@ -0,0 +1,135 @@ +# 1583. Count Unhappy Friends + +- Difficulty: Medium. +- Related Topics: Array, Simulation. +- Similar Questions: . + +## Problem + +You are given a list of `preferences` for `n` friends, where `n` is always **even**. + +For each person `i`, `preferences[i]` contains a list of friends **sorted** in the **order of preference**. In other words, a friend earlier in the list is more preferred than a friend later in the list. Friends in each list are denoted by integers from `0` to `n-1`. + +All the friends are divided into pairs. The pairings are given in a list `pairs`, where `pairs[i] = [xi, yi]` denotes `xi` is paired with `yi` and `yi` is paired with `xi`. + +However, this pairing may cause some of the friends to be unhappy. A friend `x` is unhappy if `x` is paired with `y` and there exists a friend `u` who is paired with `v` but: + + + +- `x` prefers `u` over `y`, and + +- `u` prefers `x` over `v`. + + +Return **the number of unhappy friends**. + +  +Example 1: + +``` +Input: n = 4, preferences = [[1, 2, 3], [3, 2, 0], [3, 1, 0], [1, 2, 0]], pairs = [[0, 1], [2, 3]] +Output: 2 +Explanation: +Friend 1 is unhappy because: +- 1 is paired with 0 but prefers 3 over 0, and +- 3 prefers 1 over 2. +Friend 3 is unhappy because: +- 3 is paired with 2 but prefers 1 over 2, and +- 1 prefers 3 over 0. +Friends 0 and 2 are happy. +``` + +Example 2: + +``` +Input: n = 2, preferences = [[1], [0]], pairs = [[1, 0]] +Output: 0 +Explanation: Both friends 0 and 1 are happy. +``` + +Example 3: + +``` +Input: n = 4, preferences = [[1, 3, 2], [2, 3, 0], [1, 3, 0], [0, 2, 1]], pairs = [[1, 3], [0, 2]] +Output: 4 +``` + +  +**Constraints:** + + + +- `2 <= n <= 500` + +- `n` is even. + +- `preferences.length == n` + +- `preferences[i].length == n - 1` + +- `0 <= preferences[i][j] <= n - 1` + +- `preferences[i]` does not contain `i`. + +- All values in `preferences[i]` are unique. + +- `pairs.length == n/2` + +- `pairs[i].length == 2` + +- `xi != yi` + +- `0 <= xi, yi <= n - 1` + +- Each person is contained in **exactly one** pair. + + + +## Solution + +```javascript +/** + * @param {number} n + * @param {number[][]} preferences + * @param {number[][]} pairs + * @return {number} + */ +var unhappyFriends = function(n, preferences, pairs) { + var preferenceMap = Array(n).fill(0).map(() => Array(n)); + for (var i = 0; i < preferences.length; i++) { + for (var j = 0; j < preferences[i].length; j++) { + preferenceMap[i][preferences[i][j]] = j; + } + } + var pairMap = Array(n); + for (var m = 0; m < pairs.length; m++) { + pairMap[pairs[m][0]] = pairs[m][1]; + pairMap[pairs[m][1]] = pairs[m][0]; + } + var res = 0; + for (var k = 0; k < n; k++) { + judge(preferenceMap, pairMap, k, n) && res++; + } + return res; +}; + +var judge = function(preferenceMap, pairMap, i, n) { + for (var k = 0; k < n; k++) { + if (k === i || k === pairMap[i]) continue; + if (preferenceMap[i][pairMap[i]] > preferenceMap[i][k] + && preferenceMap[k][pairMap[k]] > preferenceMap[k][i]) { + return true; + } + } + return false; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * n). +* Space complexity : O(n * 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/1609. Even Odd Tree.md b/1601-1700/1609. Even Odd Tree.md new file mode 100644 index 0000000..89c6240 --- /dev/null +++ b/1601-1700/1609. Even Odd Tree.md @@ -0,0 +1,118 @@ +# 1609. Even Odd Tree + +- Difficulty: Medium. +- Related Topics: Tree, Breadth-First Search, Binary Tree. +- Similar Questions: . + +## Problem + +A binary tree is named **Even-Odd** if it meets the following conditions: + + + +- The root of the binary tree is at level index `0`, its children are at level index `1`, their children are at level index `2`, etc. + +- For every **even-indexed** level, all nodes at the level have **odd** integer values in **strictly increasing** order (from left to right). + +- For every **odd-indexed** level, all nodes at the level have **even** integer values in **strictly decreasing** order (from left to right). + + +Given the `root` of a binary tree, **return **`true`** if the binary tree is **Even-Odd**, otherwise return **`false`**.** + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2020/09/15/sample_1_1966.png) + +``` +Input: root = [1,10,4,3,null,7,9,12,8,6,null,null,2] +Output: true +Explanation: The node values on each level are: +Level 0: [1] +Level 1: [10,4] +Level 2: [3,7,9] +Level 3: [12,8,6,2] +Since levels 0 and 2 are all odd and increasing and levels 1 and 3 are all even and decreasing, the tree is Even-Odd. +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2020/09/15/sample_2_1966.png) + +``` +Input: root = [5,4,2,3,3,7] +Output: false +Explanation: The node values on each level are: +Level 0: [5] +Level 1: [4,2] +Level 2: [3,3,7] +Node values in level 2 must be in strictly increasing order, so the tree is not Even-Odd. +``` + +Example 3: + +![](https://assets.leetcode.com/uploads/2020/09/22/sample_1_333_1966.png) + +``` +Input: root = [5,9,1,3,5,7] +Output: false +Explanation: Node values in the level 1 should be even integers. +``` + +  +**Constraints:** + + + +- The number of nodes in the tree is in the range `[1, 105]`. + +- `1 <= Node.val <= 106` + + + +## 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 + * @return {boolean} + */ +var isEvenOddTree = function(root) { + var nodesOfLevel = [root]; + var level = 0; + while (nodesOfLevel.length) { + var newNodesOfLevel = []; + for (var i = 0; i < nodesOfLevel.length; i++) { + if (level % 2) { + if (nodesOfLevel[i].val % 2) return false; + if (i > 0 && nodesOfLevel[i].val >= nodesOfLevel[i - 1].val) return false; + } else { + if (nodesOfLevel[i].val % 2 === 0) return false; + if (i > 0 && nodesOfLevel[i].val <= nodesOfLevel[i - 1].val) return false; + } + nodesOfLevel[i].left && newNodesOfLevel.push(nodesOfLevel[i].left); + nodesOfLevel[i].right && newNodesOfLevel.push(nodesOfLevel[i].right); + } + nodesOfLevel = newNodesOfLevel; + level += 1; + } + return true; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/1601-1700/1624. Largest Substring Between Two Equal Characters.md b/1601-1700/1624. Largest Substring Between Two Equal Characters.md new file mode 100644 index 0000000..390f508 --- /dev/null +++ b/1601-1700/1624. Largest Substring Between Two Equal Characters.md @@ -0,0 +1,82 @@ +# 1624. Largest Substring Between Two Equal Characters + +- Difficulty: Easy. +- Related Topics: Hash Table, String. +- Similar Questions: . + +## Problem + +Given a string `s`, return **the length of the longest substring between two equal characters, excluding the two characters.** If there is no such substring return `-1`. + +A **substring** is a contiguous sequence of characters within a string. + +  +Example 1: + +``` +Input: s = "aa" +Output: 0 +Explanation: The optimal substring here is an empty substring between the two 'a's. +``` + +Example 2: + +``` +Input: s = "abca" +Output: 2 +Explanation: The optimal substring here is "bc". +``` + +Example 3: + +``` +Input: s = "cbzxy" +Output: -1 +Explanation: There are no characters that appear twice in s. +``` + +  +**Constraints:** + + + +- `1 <= s.length <= 300` + +- `s` contains only lowercase English letters. + + + +## Solution + +```javascript +/** + * @param {string} s + * @return {number} + */ +var maxLengthBetweenEqualCharacters = function(s) { + var leftPosMap = Array(26); + var rightPosMap = Array(26); + var a = 'a'.charCodeAt(0); + for (var i = 0; i < s.length; i++) { + var j = s[i].charCodeAt(0) - a; + if (leftPosMap[j] === undefined) leftPosMap[j] = i; + rightPosMap[j] = i; + } + var max = -1; + for (var m = 0; m < 26; m++) { + if (leftPosMap[m] !== rightPosMap[m]) { + max = Math.max(max, rightPosMap[m] - leftPosMap[m] - 1); + } + } + return max; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/1601-1700/1637. Widest Vertical Area Between Two Points Containing No Points.md b/1601-1700/1637. Widest Vertical Area Between Two Points Containing No Points.md new file mode 100644 index 0000000..70f282a --- /dev/null +++ b/1601-1700/1637. Widest Vertical Area Between Two Points Containing No Points.md @@ -0,0 +1,72 @@ +# 1637. Widest Vertical Area Between Two Points Containing No Points + +- Difficulty: Medium. +- Related Topics: Array, Sorting. +- Similar Questions: . + +## Problem + +Given `n` `points` on a 2D plane where `points[i] = [xi, yi]`, Return** the **widest vertical area** between two points such that no points are inside the area.** + +A **vertical area** is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The **widest vertical area** is the one with the maximum width. + +Note that points **on the edge** of a vertical area **are not** considered included in the area. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2020/09/19/points3.png) +​ +``` +Input: points = [[8,7],[9,9],[7,4],[9,7]] +Output: 1 +Explanation: Both the red and the blue area are optimal. +``` + +Example 2: + +``` +Input: points = [[3,1],[9,0],[1,0],[1,4],[5,3],[8,8]] +Output: 3 +``` + +  +**Constraints:** + + + +- `n == points.length` + +- `2 <= n <= 105` + +- `points[i].length == 2` + +- `0 <= xi, yi <= 109` + + + +## Solution + +```javascript +/** + * @param {number[][]} points + * @return {number} + */ +var maxWidthOfVerticalArea = function(points) { + var maxGap = 0; + points.sort((a, b) => a[0] - b[0]); + for (var i = 1; i < points.length; i++) { + maxGap = Math.max(maxGap, points[i][0] - points[i - 1][0]); + } + return maxGap; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/1601-1700/1642. Furthest Building You Can Reach.md b/1601-1700/1642. Furthest Building You Can Reach.md new file mode 100644 index 0000000..e4303c2 --- /dev/null +++ b/1601-1700/1642. Furthest Building You Can Reach.md @@ -0,0 +1,100 @@ +# 1642. Furthest Building You Can Reach + +- Difficulty: Medium. +- Related Topics: Array, Greedy, Heap (Priority Queue). +- Similar Questions: Make the Prefix Sum Non-negative, Find Building Where Alice and Bob Can Meet. + +## Problem + +You are given an integer array `heights` representing the heights of buildings, some `bricks`, and some `ladders`. + +You start your journey from building `0` and move to the next building by possibly using bricks or ladders. + +While moving from building `i` to building `i+1` (**0-indexed**), + + + +- If the current building's height is **greater than or equal** to the next building's height, you do **not** need a ladder or bricks. + +- If the current building's height is **less than** the next building's height, you can either use **one ladder** or `(h[i+1] - h[i])` **bricks**. + + +**Return the furthest building index (0-indexed) you can reach if you use the given ladders and bricks optimally.** + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2020/10/27/q4.gif) + +``` +Input: heights = [4,2,7,6,9,14,12], bricks = 5, ladders = 1 +Output: 4 +Explanation: Starting at building 0, you can follow these steps: +- Go to building 1 without using ladders nor bricks since 4 >= 2. +- Go to building 2 using 5 bricks. You must use either bricks or ladders because 2 < 7. +- Go to building 3 without using ladders nor bricks since 7 >= 6. +- Go to building 4 using your only ladder. You must use either bricks or ladders because 6 < 9. +It is impossible to go beyond building 4 because you do not have any more bricks or ladders. +``` + +Example 2: + +``` +Input: heights = [4,12,2,7,3,18,20,3,19], bricks = 10, ladders = 2 +Output: 7 +``` + +Example 3: + +``` +Input: heights = [14,3,19,3], bricks = 17, ladders = 0 +Output: 3 +``` + +  +**Constraints:** + + + +- `1 <= heights.length <= 105` + +- `1 <= heights[i] <= 106` + +- `0 <= bricks <= 109` + +- `0 <= ladders <= heights.length` + + + +## Solution + +```javascript +/** + * @param {number[]} heights + * @param {number} bricks + * @param {number} ladders + * @return {number} + */ +var furthestBuilding = function(heights, bricks, ladders) { + var queue = new MinPriorityQueue(); + for (var i = 0; i < heights.length - 1; i++) { + if (heights[i + 1] <= heights[i]) continue; + queue.enqueue(heights[i + 1] - heights[i], heights[i + 1] - heights[i]); + if (queue.size() > ladders) { + var height = queue.dequeue().element; + if (bricks < height) return i; + bricks -= height; + } + } + return heights.length - 1; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * log(n)). +* Space complexity : O(n). 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/1704. Determine if String Halves Are Alike.md b/1701-1800/1704. Determine if String Halves Are Alike.md new file mode 100644 index 0000000..362ca73 --- /dev/null +++ b/1701-1800/1704. Determine if String Halves Are Alike.md @@ -0,0 +1,83 @@ +# 1704. Determine if String Halves Are Alike + +- Difficulty: Easy. +- Related Topics: String, Counting. +- Similar Questions: . + +## Problem + +You are given a string `s` of even length. Split this string into two halves of equal lengths, and let `a` be the first half and `b` be the second half. + +Two strings are **alike** if they have the same number of vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`, `'A'`, `'E'`, `'I'`, `'O'`, `'U'`). Notice that `s` contains uppercase and lowercase letters. + +Return `true`** if **`a`** and **`b`** are **alike****. Otherwise, return `false`. + +  +Example 1: + +``` +Input: s = "book" +Output: true +Explanation: a = "bo" and b = "ok". a has 1 vowel and b has 1 vowel. Therefore, they are alike. +``` + +Example 2: + +``` +Input: s = "textbook" +Output: false +Explanation: a = "text" and b = "book". a has 1 vowel whereas b has 2. Therefore, they are not alike. +Notice that the vowel o is counted twice. +``` + +  +**Constraints:** + + + +- `2 <= s.length <= 1000` + +- `s.length` is even. + +- `s` consists of **uppercase and lowercase** letters. + + + +## Solution + +```javascript +/** + * @param {string} s + * @return {boolean} + */ +var halvesAreAlike = function(s) { + var map = { + a: true, + e: true, + i: true, + o: true, + u: true, + A: true, + E: true, + I: true, + O: true, + U: true, + }; + var half = s.length / 2; + var count = 0; + for (var i = 0; i < half; i++) { + if (map[s[i]]) count++; + if (map[s[i + half]]) count--; + } + return count === 0; +}; +``` + +**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/1750. Minimum Length of String After Deleting Similar Ends.md b/1701-1800/1750. Minimum Length of String After Deleting Similar Ends.md new file mode 100644 index 0000000..113feb7 --- /dev/null +++ b/1701-1800/1750. Minimum Length of String After Deleting Similar Ends.md @@ -0,0 +1,95 @@ +# 1750. Minimum Length of String After Deleting Similar Ends + +- Difficulty: Medium. +- Related Topics: Two Pointers, String. +- Similar Questions: . + +## Problem + +Given a string `s` consisting only of characters `'a'`, `'b'`, and `'c'`. You are asked to apply the following algorithm on the string any number of times: + + + +- Pick a **non-empty** prefix from the string `s` where all the characters in the prefix are equal. + +- Pick a **non-empty** suffix from the string `s` where all the characters in this suffix are equal. + +- The prefix and the suffix should not intersect at any index. + +- The characters from the prefix and suffix must be the same. + +- Delete both the prefix and the suffix. + + +Return **the **minimum length** of **`s` **after performing the above operation any number of times (possibly zero times)**. + +  +Example 1: + +``` +Input: s = "ca" +Output: 2 +Explanation: You can't remove any characters, so the string stays as is. +``` + +Example 2: + +``` +Input: s = "cabaabac" +Output: 0 +Explanation: An optimal sequence of operations is: +- Take prefix = "c" and suffix = "c" and remove them, s = "abaaba". +- Take prefix = "a" and suffix = "a" and remove them, s = "baab". +- Take prefix = "b" and suffix = "b" and remove them, s = "aa". +- Take prefix = "a" and suffix = "a" and remove them, s = "". +``` + +Example 3: + +``` +Input: s = "aabccabba" +Output: 3 +Explanation: An optimal sequence of operations is: +- Take prefix = "aa" and suffix = "a" and remove them, s = "bccabb". +- Take prefix = "b" and suffix = "bb" and remove them, s = "cca". +``` + +  +**Constraints:** + + + +- `1 <= s.length <= 105` + +- `s` only consists of characters `'a'`, `'b'`, and `'c'`. + + + +## Solution + +```javascript +/** + * @param {string} s + * @return {number} + */ +var minimumLength = function(s) { + var left = 0; + var right = s.length - 1; + while (left < right && s[left] === s[right]) { + while (s[left] === s[left + 1] && left + 1 < right) left++; + while (s[right] === s[right - 1] && right - 1 > left) right--; + left++; + right--; + } + return right - left + 1; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(0). 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/1801-1900/1879. Minimum XOR Sum of Two Arrays.md b/1801-1900/1879. Minimum XOR Sum of Two Arrays.md new file mode 100644 index 0000000..ace6f5c --- /dev/null +++ b/1801-1900/1879. Minimum XOR Sum of Two Arrays.md @@ -0,0 +1,90 @@ +# 1879. Minimum XOR Sum of Two Arrays + +- Difficulty: Hard. +- Related Topics: Array, Dynamic Programming, Bit Manipulation, Bitmask. +- Similar Questions: Fair Distribution of Cookies, Choose Numbers From Two Arrays in Range, Maximum AND Sum of Array. + +## Problem + +You are given two integer arrays `nums1` and `nums2` of length `n`. + +The **XOR sum** of the two integer arrays is `(nums1[0] XOR nums2[0]) + (nums1[1] XOR nums2[1]) + ... + (nums1[n - 1] XOR nums2[n - 1])` (**0-indexed**). + + + +- For example, the **XOR sum** of `[1,2,3]` and `[3,2,1]` is equal to `(1 XOR 3) + (2 XOR 2) + (3 XOR 1) = 2 + 0 + 2 = 4`. + + +Rearrange the elements of `nums2` such that the resulting **XOR sum** is **minimized**. + +Return **the **XOR sum** after the rearrangement**. + +  +Example 1: + +``` +Input: nums1 = [1,2], nums2 = [2,3] +Output: 2 +Explanation: Rearrange nums2 so that it becomes [3,2]. +The XOR sum is (1 XOR 3) + (2 XOR 2) = 2 + 0 = 2. +``` + +Example 2: + +``` +Input: nums1 = [1,0,3], nums2 = [5,3,4] +Output: 8 +Explanation: Rearrange nums2 so that it becomes [5,4,3]. +The XOR sum is (1 XOR 5) + (0 XOR 4) + (3 XOR 3) = 4 + 4 + 0 = 8. +``` + +  +**Constraints:** + + + +- `n == nums1.length` + +- `n == nums2.length` + +- `1 <= n <= 14` + +- `0 <= nums1[i], nums2[i] <= 107` + + + +## Solution + +```javascript +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number} + */ +var minimumXORSum = function(nums1, nums2) { + return helper(nums1, nums2, 0, 0, {}); +}; + +var helper = function(nums1, nums2, i, bitmask, dp) { + if (i === nums1.length) return 0; + var key = `${i}-${bitmask}`; + if (dp[key] !== undefined) return dp[key]; + var min = Number.MAX_SAFE_INTEGER; + for (var j = 0; j < nums2.length; j++) { + var mask = 1 << j; + if (bitmask & mask) continue; + min = Math.min(min, (nums1[i] ^ nums2[j]) + helper(nums1, nums2, i + 1, bitmask | mask, dp)); + } + dp[key] = min; + return min; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * 2^n). +* Space complexity : O(n * 2^n). diff --git a/1801-1900/1884. Egg Drop With 2 Eggs and N Floors.md b/1801-1900/1884. Egg Drop With 2 Eggs and N Floors.md new file mode 100644 index 0000000..44a7f5f --- /dev/null +++ b/1801-1900/1884. Egg Drop With 2 Eggs and N Floors.md @@ -0,0 +1,72 @@ +# 1884. Egg Drop With 2 Eggs and N Floors + +- Difficulty: Medium. +- Related Topics: Math, Dynamic Programming. +- Similar Questions: Super Egg Drop. + +## Problem + +You are given **two identical** eggs and you have access to a building with `n` floors labeled from `1` to `n`. + +You know that there exists a floor `f` where `0 <= f <= n` such that any egg dropped at a floor **higher** than `f` will **break**, and any egg dropped **at or below** floor `f` will **not break**. + +In each move, you may take an **unbroken** egg and drop it from any floor `x` (where `1 <= x <= n`). If the egg breaks, you can no longer use it. However, if the egg does not break, you may **reuse** it in future moves. + +Return **the **minimum number of moves** that you need to determine **with certainty** what the value of **`f` is. + +  +Example 1: + +``` +Input: n = 2 +Output: 2 +Explanation: We can drop the first egg from floor 1 and the second egg from floor 2. +If the first egg breaks, we know that f = 0. +If the second egg breaks but the first egg didn't, we know that f = 1. +Otherwise, if both eggs survive, we know that f = 2. +``` + +Example 2: + +``` +Input: n = 100 +Output: 14 +Explanation: One optimal strategy is: +- Drop the 1st egg at floor 9. If it breaks, we know f is between 0 and 8. Drop the 2nd egg starting from floor 1 and going up one at a time to find f within 8 more drops. Total drops is 1 + 8 = 9. +- If the 1st egg does not break, drop the 1st egg again at floor 22. If it breaks, we know f is between 9 and 21. Drop the 2nd egg starting from floor 10 and going up one at a time to find f within 12 more drops. Total drops is 2 + 12 = 14. +- If the 1st egg does not break again, follow a similar process dropping the 1st egg from floors 34, 45, 55, 64, 72, 79, 85, 90, 94, 97, 99, and 100. +Regardless of the outcome, it takes at most 14 drops to determine f. +``` + +  +**Constraints:** + + + +- `1 <= n <= 1000` + + + +## Solution + +```javascript +/** + * @param {number} n + * @return {number} + */ +var twoEggDrop = function(n) { + // x + (x - 1) + (x - 2) + ... + 1 >= n + var num = Math.ceil(Math.sqrt(2 * n)); + while (num * (num - 1) / 2 >= n) num--; + return num; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(1). +* Space complexity : O(1). diff --git a/1801-1900/1897. Redistribute Characters to Make All Strings Equal.md b/1801-1900/1897. Redistribute Characters to Make All Strings Equal.md new file mode 100644 index 0000000..7813ee4 --- /dev/null +++ b/1801-1900/1897. Redistribute Characters to Make All Strings Equal.md @@ -0,0 +1,73 @@ +# 1897. Redistribute Characters to Make All Strings Equal + +- Difficulty: Easy. +- Related Topics: Hash Table, String, Counting. +- Similar Questions: . + +## Problem + +You are given an array of strings `words` (**0-indexed**). + +In one operation, pick two **distinct** indices `i` and `j`, where `words[i]` is a non-empty string, and move **any** character from `words[i]` to **any** position in `words[j]`. + +Return `true` **if you can make** every** string in **`words`** **equal **using **any** number of operations**,** and **`false` **otherwise**. + +  +Example 1: + +``` +Input: words = ["abc","aabc","bc"] +Output: true +Explanation: Move the first 'a' in words[1] to the front of words[2], +to make words[1] = "abc" and words[2] = "abc". +All the strings are now equal to "abc", so return true. +``` + +Example 2: + +``` +Input: words = ["ab","a"] +Output: false +Explanation: It is impossible to make all the strings equal using the operation. +``` + +  +**Constraints:** + + + +- `1 <= words.length <= 100` + +- `1 <= words[i].length <= 100` + +- `words[i]` consists of lowercase English letters. + + + +## Solution + +```javascript +/** + * @param {string[]} words + * @return {boolean} + */ +var makeEqual = function(words) { + var map = Array(26).fill(0); + var a = 'a'.charCodeAt(0); + for (var i = 0; i < words.length; i++) { + for (var j = 0; j < words[i].length; j++) { + map[words[i][j].charCodeAt(0) - a]++; + } + } + return map.every(item => item % words.length === 0); +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * m). +* Space complexity : O(1). diff --git a/1901-2000/1903. Largest Odd Number in String.md b/1901-2000/1903. Largest Odd Number in String.md new file mode 100644 index 0000000..e98aaae --- /dev/null +++ b/1901-2000/1903. Largest Odd Number in String.md @@ -0,0 +1,80 @@ +# 1903. Largest Odd Number in String + +- Difficulty: Easy. +- Related Topics: Math, String, Greedy. +- Similar Questions: Largest 3-Same-Digit Number in String. + +## Problem + +You are given a string `num`, representing a large integer. Return **the **largest-valued odd** integer (as a string) that is a **non-empty substring** of **`num`**, or an empty string **`""`** if no odd integer exists**. + +A **substring** is a contiguous sequence of characters within a string. + +  +Example 1: + +``` +Input: num = "52" +Output: "5" +Explanation: The only non-empty substrings are "5", "2", and "52". "5" is the only odd number. +``` + +Example 2: + +``` +Input: num = "4206" +Output: "" +Explanation: There are no odd numbers in "4206". +``` + +Example 3: + +``` +Input: num = "35427" +Output: "35427" +Explanation: "35427" is already an odd number. +``` + +  +**Constraints:** + + + +- `1 <= num.length <= 105` + +- `num` only consists of digits and does not contain any leading zeros. + + + +## Solution + +```javascript +/** + * @param {string} num + * @return {string} + */ +var largestOddNumber = function(num) { + var lastNonZeroNumIndex = -1; + var firstOddNumIndex = -1; + for (var i = num.length - 1; i >= 0; i--) { + if (firstOddNumIndex === -1 && (Number(num[i]) % 2)) { + firstOddNumIndex = i; + } + if (num[i] !== '0') { + lastNonZeroNumIndex = i; + } + } + return firstOddNumIndex === -1 + ? '' : + num.slice(lastNonZeroNumIndex, firstOddNumIndex + 1) +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/1901-2000/1913. Maximum Product Difference Between Two Pairs.md b/1901-2000/1913. Maximum Product Difference Between Two Pairs.md new file mode 100644 index 0000000..656599d --- /dev/null +++ b/1901-2000/1913. Maximum Product Difference Between Two Pairs.md @@ -0,0 +1,87 @@ +# 1913. Maximum Product Difference Between Two Pairs + +- Difficulty: Easy. +- Related Topics: Array, Sorting. +- Similar Questions: . + +## Problem + +The **product difference** between two pairs `(a, b)` and `(c, d)` is defined as `(a * b) - (c * d)`. + + + +- For example, the product difference between `(5, 6)` and `(2, 7)` is `(5 * 6) - (2 * 7) = 16`. + + +Given an integer array `nums`, choose four **distinct** indices `w`, `x`, `y`, and `z` such that the **product difference** between pairs `(nums[w], nums[x])` and `(nums[y], nums[z])` is **maximized**. + +Return **the **maximum** such product difference**. + +  +Example 1: + +``` +Input: nums = [5,6,2,7,4] +Output: 34 +Explanation: We can choose indices 1 and 3 for the first pair (6, 7) and indices 2 and 4 for the second pair (2, 4). +The product difference is (6 * 7) - (2 * 4) = 34. +``` + +Example 2: + +``` +Input: nums = [4,2,5,9,7,4,8] +Output: 64 +Explanation: We can choose indices 3 and 6 for the first pair (9, 8) and indices 1 and 5 for the second pair (2, 4). +The product difference is (9 * 8) - (2 * 4) = 64. +``` + +  +**Constraints:** + + + +- `4 <= nums.length <= 104` + +- `1 <= nums[i] <= 104` + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @return {number} + */ +var maxProductDifference = function(nums) { + var maxIndex = -1; + var secondMaxIndex = -1; + var minIndex = -1; + var secondMinIndex = -1; + for (var i = 0; i < nums.length; i++) { + if (minIndex === -1 || nums[i] < nums[minIndex]) { + secondMinIndex = minIndex; + minIndex = i; + } else if (secondMinIndex === -1 || nums[i] < nums[secondMinIndex]) { + secondMinIndex = i; + } + if (maxIndex === -1 || nums[i] > nums[maxIndex]) { + secondMaxIndex = maxIndex; + maxIndex = i; + } else if (secondMaxIndex == -1 || nums[i] > nums[secondMaxIndex]) { + secondMaxIndex = i; + } + } + return nums[maxIndex] * nums[secondMaxIndex] + - nums[minIndex] * nums[secondMinIndex]; +}; +``` + +**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/1901-2000/1964. Find the Longest Valid Obstacle Course at Each Position.md b/1901-2000/1964. Find the Longest Valid Obstacle Course at Each Position.md new file mode 100644 index 0000000..5bfadc3 --- /dev/null +++ b/1901-2000/1964. Find the Longest Valid Obstacle Course at Each Position.md @@ -0,0 +1,123 @@ +# 1964. Find the Longest Valid Obstacle Course at Each Position + +- Difficulty: Hard. +- Related Topics: Array, Binary Search, Binary Indexed Tree. +- Similar Questions: Longest Increasing Subsequence. + +## Problem + +You want to build some obstacle courses. You are given a **0-indexed** integer array `obstacles` of length `n`, where `obstacles[i]` describes the height of the `ith` obstacle. + +For every index `i` between `0` and `n - 1` (**inclusive**), find the length of the **longest obstacle course** in `obstacles` such that: + + + +- You choose any number of obstacles between `0` and `i` **inclusive**. + +- You must include the `ith` obstacle in the course. + +- You must put the chosen obstacles in the **same order** as they appear in `obstacles`. + +- Every obstacle (except the first) is **taller** than or the **same height** as the obstacle immediately before it. + + +Return **an array** `ans` **of length** `n`, **where** `ans[i]` **is the length of the **longest obstacle course** for index** `i`** as described above**. + +  +Example 1: + +``` +Input: obstacles = [1,2,3,2] +Output: [1,2,3,3] +Explanation: The longest valid obstacle course at each position is: +- i = 0: [1], [1] has length 1. +- i = 1: [1,2], [1,2] has length 2. +- i = 2: [1,2,3], [1,2,3] has length 3. +- i = 3: [1,2,3,2], [1,2,2] has length 3. +``` + +Example 2: + +``` +Input: obstacles = [2,2,1] +Output: [1,2,1] +Explanation: The longest valid obstacle course at each position is: +- i = 0: [2], [2] has length 1. +- i = 1: [2,2], [2,2] has length 2. +- i = 2: [2,2,1], [1] has length 1. +``` + +Example 3: + +``` +Input: obstacles = [3,1,5,6,4,2] +Output: [1,1,2,3,2,2] +Explanation: The longest valid obstacle course at each position is: +- i = 0: [3], [3] has length 1. +- i = 1: [3,1], [1] has length 1. +- i = 2: [3,1,5], [3,5] has length 2. [1,5] is also valid. +- i = 3: [3,1,5,6], [3,5,6] has length 3. [1,5,6] is also valid. +- i = 4: [3,1,5,6,4], [3,4] has length 2. [1,4] is also valid. +- i = 5: [3,1,5,6,4,2], [1,2] has length 2. +``` + +  +**Constraints:** + + + +- `n == obstacles.length` + +- `1 <= n <= 105` + +- `1 <= obstacles[i] <= 107` + + + +## Solution + +```javascript +/** + * @param {number[]} obstacles + * @return {number[]} + */ +var longestObstacleCourseAtEachPosition = function(obstacles) { + var res = Array(obstacles.length).fill(1); + var stack = []; + for (var i = 0; i < obstacles.length; i++) { + if (!stack.length || obstacles[i] >= stack[stack.length - 1]) { + res[i] = (stack.length || 0) + 1; + stack.push(obstacles[i]); + } else { + var index = binarySearch(stack, obstacles[i]); + res[i] = index + 1; + stack[index] = obstacles[i]; + } + } + return res; +}; + +var binarySearch = function(arr, num) { + var left = 0; + var right = arr.length - 1; + while (left < right) { + var mid = left + Math.floor((right - left) / 2); + if (arr[mid] <= num) { + left = mid + 1; + } else { + right = mid; + } + } + return left; +}; + +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * log(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/2092. Find All People With Secret.md b/2001-2100/2092. Find All People With Secret.md new file mode 100644 index 0000000..c79529a --- /dev/null +++ b/2001-2100/2092. Find All People With Secret.md @@ -0,0 +1,135 @@ +# 2092. Find All People With Secret + +- Difficulty: Hard. +- Related Topics: Depth-First Search, Breadth-First Search, Union Find, Graph, Sorting. +- Similar Questions: Reachable Nodes In Subdivided Graph. + +## Problem + +You are given an integer `n` indicating there are `n` people numbered from `0` to `n - 1`. You are also given a **0-indexed** 2D integer array `meetings` where `meetings[i] = [xi, yi, timei]` indicates that person `xi` and person `yi` have a meeting at `timei`. A person may attend **multiple meetings** at the same time. Finally, you are given an integer `firstPerson`. + +Person `0` has a **secret** and initially shares the secret with a person `firstPerson` at time `0`. This secret is then shared every time a meeting takes place with a person that has the secret. More formally, for every meeting, if a person `xi` has the secret at `timei`, then they will share the secret with person `yi`, and vice versa. + +The secrets are shared **instantaneously**. That is, a person may receive the secret and share it with people in other meetings within the same time frame. + +Return **a list of all the people that have the secret after all the meetings have taken place. **You may return the answer in **any order**. + +  +Example 1: + +``` +Input: n = 6, meetings = [[1,2,5],[2,3,8],[1,5,10]], firstPerson = 1 +Output: [0,1,2,3,5] +Explanation: +At time 0, person 0 shares the secret with person 1. +At time 5, person 1 shares the secret with person 2. +At time 8, person 2 shares the secret with person 3. +At time 10, person 1 shares the secret with person 5.​​​​ +Thus, people 0, 1, 2, 3, and 5 know the secret after all the meetings. +``` + +Example 2: + +``` +Input: n = 4, meetings = [[3,1,3],[1,2,2],[0,3,3]], firstPerson = 3 +Output: [0,1,3] +Explanation: +At time 0, person 0 shares the secret with person 3. +At time 2, neither person 1 nor person 2 know the secret. +At time 3, person 3 shares the secret with person 0 and person 1. +Thus, people 0, 1, and 3 know the secret after all the meetings. +``` + +Example 3: + +``` +Input: n = 5, meetings = [[3,4,2],[1,2,1],[2,3,1]], firstPerson = 1 +Output: [0,1,2,3,4] +Explanation: +At time 0, person 0 shares the secret with person 1. +At time 1, person 1 shares the secret with person 2, and person 2 shares the secret with person 3. +Note that person 2 can share the secret at the same time as receiving it. +At time 2, person 3 shares the secret with person 4. +Thus, people 0, 1, 2, 3, and 4 know the secret after all the meetings. +``` + +  +**Constraints:** + + + +- `2 <= n <= 105` + +- `1 <= meetings.length <= 105` + +- `meetings[i].length == 3` + +- `0 <= xi, yi <= n - 1` + +- `xi != yi` + +- `1 <= timei <= 105` + +- `1 <= firstPerson <= n - 1` + + + +## Solution + +```javascript +/** + * @param {number} n + * @param {number[][]} meetings + * @param {number} firstPerson + * @return {number[]} + */ +var findAllPeople = function(n, meetings, firstPerson) { + var map = Array(n).fill(0).map(() => []); + var queue = new MinPriorityQueue(); + var hasSecretMap = Array(n); + var handledMap = Array(meetings.length); + hasSecretMap[0] = true; + hasSecretMap[firstPerson] = true; + for (var i = 0; i < meetings.length; i++) { + map[meetings[i][0]].push([meetings[i][1], meetings[i][2], i]); + map[meetings[i][1]].push([meetings[i][0], meetings[i][2], i]); + queue.enqueue( + [...meetings[i], i], + (hasSecretMap[meetings[i][0]] || hasSecretMap[meetings[i][1]]) + ? meetings[i][2] - 0.1 + : meetings[i][2] + ); + } + while (queue.size() !== 0) { + var item = queue.dequeue().element; + if (handledMap[item[3]]) continue; + handledMap[item[3]] = true; + if (!hasSecretMap[item[0]] && !hasSecretMap[item[1]]) continue; + if (hasSecretMap[item[0]] && hasSecretMap[item[1]]) continue; + var num = hasSecretMap[item[0]] ? item[1] : item[0]; + for (var i = 0; i < map[num].length; i++) { + var data = map[num][i]; + if (handledMap[data[2]]) continue; + if (hasSecretMap[data[0]]) continue; + queue.enqueue( + [num, data[0], data[1] - 0.1, data[2]], + data[1] - 0.1 + ); + } + hasSecretMap[num] = true; + } + return hasSecretMap.reduce((res, item, i) => { + if (item) res.push(i); + return res; + }, []); +}; +``` + +**Explain:** + +Priority queue with dynamicly changes priority. + +**Complexity:** + +* Time complexity : O(n * log(n) + m). +* Space complexity : O(n + m). 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/201. Bitwise AND of Numbers Range.md b/201-300/201. Bitwise AND of Numbers Range.md new file mode 100644 index 0000000..5966450 --- /dev/null +++ b/201-300/201. Bitwise AND of Numbers Range.md @@ -0,0 +1,68 @@ +# 201. Bitwise AND of Numbers Range + +- Difficulty: Medium. +- Related Topics: Bit Manipulation. +- Similar Questions: Longest Nice Subarray. + +## Problem + +Given two integers `left` and `right` that represent the range `[left, right]`, return **the bitwise AND of all numbers in this range, inclusive**. + +  +Example 1: + +``` +Input: left = 5, right = 7 +Output: 4 +``` + +Example 2: + +``` +Input: left = 0, right = 0 +Output: 0 +``` + +Example 3: + +``` +Input: left = 1, right = 2147483647 +Output: 0 +``` + +  +**Constraints:** + + + +- `0 <= left <= right <= 231 - 1` + + + +## Solution + +```javascript +/** + * @param {number} left + * @param {number} right + * @return {number} + */ +var rangeBitwiseAnd = function(left, right) { + var count = 0; + while (left !== right) { + left >>= 1; + right >>= 1; + count += 1; + } + return left << count; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(1). +* Space complexity : O(1). 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/224. Basic Calculator.md b/201-300/224. Basic Calculator.md new file mode 100644 index 0000000..82cc3c5 --- /dev/null +++ b/201-300/224. Basic Calculator.md @@ -0,0 +1,117 @@ +# 224. Basic Calculator + +- Difficulty: Hard. +- Related Topics: Math, String, Stack, Recursion. +- Similar Questions: Evaluate Reverse Polish Notation, Basic Calculator II, Different Ways to Add Parentheses, Expression Add Operators, Basic Calculator III, The Score of Students Solving Math Expression, Minimize Result by Adding Parentheses to Expression. + +## Problem + +Given a string `s` representing a valid expression, implement a basic calculator to evaluate it, and return **the result of the evaluation**. + +**Note:** You are **not** allowed to use any built-in function which evaluates strings as mathematical expressions, such as `eval()`. + +  +Example 1: + +``` +Input: s = "1 + 1" +Output: 2 +``` + +Example 2: + +``` +Input: s = " 2-1 + 2 " +Output: 3 +``` + +Example 3: + +``` +Input: s = "(1+(4+5+2)-3)+(6+8)" +Output: 23 +``` + +  +**Constraints:** + + + +- `1 <= s.length <= 3 * 105` + +- `s` consists of digits, `'+'`, `'-'`, `'('`, `')'`, and `' '`. + +- `s` represents a valid expression. + +- `'+'` is **not** used as a unary operation (i.e., `"+1"` and `"+(2 + 3)"` is invalid). + +- `'-'` could be used as a unary operation (i.e., `"-1"` and `"-(2 + 3)"` is valid). + +- There will be no two consecutive operators in the input. + +- Every number and running calculation will fit in a signed 32-bit integer. + + + +## Solution + +```javascript +/** + * @param {string} s + * @return {number} + */ +var calculate = function(s) { + var res = 0; + var i = 0; + var isPlus = true; + while (i < s.length) { + switch (s[i]) { + case ' ': + i++; + break; + case '+': + isPlus = true; + i++; + break; + case '-': + isPlus = false; + i++; + break; + case '(': + i++; + var num = 0; + var from = i; + while (!(num === 0 && s[i] === ')')) { + if (s[i] === '(') num++; + if (s[i] === ')') num--; + i++; + } + isPlus + ? (res += calculate(s.slice(from, i))) + : (res -= calculate(s.slice(from, i))) + i++; + break; + default: + var num = Number(s[i]); + while (s[i + 1] >= '0' && s[i + 1] <= '9') { + i++; + num *= 10; + num += Number(s[i]); + } + isPlus ? (res += num) : (res -= num); + i++; + break; + } + } + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). 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/231. Power of Two.md b/201-300/231. Power of Two.md new file mode 100644 index 0000000..711a78e --- /dev/null +++ b/201-300/231. Power of Two.md @@ -0,0 +1,70 @@ +# 231. Power of Two + +- Difficulty: Easy. +- Related Topics: Math, Bit Manipulation, Recursion. +- Similar Questions: Number of 1 Bits, Power of Three, Power of Four. + +## Problem + +Given an integer `n`, return **`true` if it is a power of two. Otherwise, return `false`**. + +An integer `n` is a power of two, if there exists an integer `x` such that `n == 2x`. + +  +Example 1: + +``` +Input: n = 1 +Output: true +Explanation: 20 = 1 +``` + +Example 2: + +``` +Input: n = 16 +Output: true +Explanation: 24 = 16 +``` + +Example 3: + +``` +Input: n = 3 +Output: false +``` + +  +**Constraints:** + + + +- `-231 <= n <= 231 - 1` + + +  +**Follow up:** Could you solve it without loops/recursion? + +## Solution + +```javascript +/** + * @param {number} n + * @return {boolean} + */ +var isPowerOfTwo = function(n) { + if (n <= 0) return false; + if (n === 1) return true; + if (n % 2) return false; + return isPowerOfTwo(n / 2); +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(log(n)). +* Space complexity : O(1). diff --git a/201-300/232. Implement Queue using Stacks.md b/201-300/232. Implement Queue using Stacks.md new file mode 100644 index 0000000..62bf1db --- /dev/null +++ b/201-300/232. Implement Queue using Stacks.md @@ -0,0 +1,129 @@ +# 232. Implement Queue using Stacks + +- Difficulty: Easy. +- Related Topics: Stack, Design, Queue. +- Similar Questions: Implement Stack using Queues. + +## Problem + +Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (`push`, `peek`, `pop`, and `empty`). + +Implement the `MyQueue` class: + + + +- `void push(int x)` Pushes element x to the back of the queue. + +- `int pop()` Removes the element from the front of the queue and returns it. + +- `int peek()` Returns the element at the front of the queue. + +- `boolean empty()` Returns `true` if the queue is empty, `false` otherwise. + + +**Notes:** + + + +- You must use **only** standard operations of a stack, which means only `push to top`, `peek/pop from top`, `size`, and `is empty` operations are valid. + +- Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations. + + +  +Example 1: + +``` +Input +["MyQueue", "push", "push", "peek", "pop", "empty"] +[[], [1], [2], [], [], []] +Output +[null, null, null, 1, 1, false] + +Explanation +MyQueue myQueue = new MyQueue(); +myQueue.push(1); // queue is: [1] +myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue) +myQueue.peek(); // return 1 +myQueue.pop(); // return 1, queue is [2] +myQueue.empty(); // return false +``` + +  +**Constraints:** + + + +- `1 <= x <= 9` + +- At most `100` calls will be made to `push`, `pop`, `peek`, and `empty`. + +- All the calls to `pop` and `peek` are valid. + + +  +**Follow-up:** Can you implement the queue such that each operation is **amortized** `O(1)` time complexity? In other words, performing `n` operations will take overall `O(n)` time even if one of those operations may take longer. + + +## Solution + +```javascript + +var MyQueue = function() { + this.stack1 = []; + this.stack2 = []; +}; + +/** + * @param {number} x + * @return {void} + */ +MyQueue.prototype.push = function(x) { + this.stack1.push(x); +}; + +/** + * @return {number} + */ +MyQueue.prototype.pop = function() { + if (this.stack2.length === 0) { + while (this.stack1.length) this.stack2.push(this.stack1.pop()); + } + return this.stack2.pop(); +}; + +/** + * @return {number} + */ +MyQueue.prototype.peek = function() { + if (this.stack2.length === 0) { + while (this.stack1.length) this.stack2.push(this.stack1.pop()); + } + return this.stack2[this.stack2.length - 1]; +}; + +/** + * @return {boolean} + */ +MyQueue.prototype.empty = function() { + return this.stack1.length === 0 && this.stack2.length === 0; +}; + +/** + * Your MyQueue object will be instantiated and called as such: + * var obj = new MyQueue() + * obj.push(x) + * var param_2 = obj.pop() + * var param_3 = obj.peek() + * var param_4 = obj.empty() + */ +``` + +**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/268. Missing Number.md b/201-300/268. Missing Number.md new file mode 100644 index 0000000..0198035 --- /dev/null +++ b/201-300/268. Missing Number.md @@ -0,0 +1,74 @@ +# 268. Missing Number + +- Difficulty: Easy. +- Related Topics: Array, Hash Table, Math, Binary Search, Bit Manipulation, Sorting. +- Similar Questions: First Missing Positive, Single Number, Find the Duplicate Number, Couples Holding Hands, Find Unique Binary String. + +## Problem + +Given an array `nums` containing `n` distinct numbers in the range `[0, n]`, return **the only number in the range that is missing from the array.** + +  +Example 1: + +``` +Input: nums = [3,0,1] +Output: 2 +Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums. +``` + +Example 2: + +``` +Input: nums = [0,1] +Output: 2 +Explanation: n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the range since it does not appear in nums. +``` + +Example 3: + +``` +Input: nums = [9,6,4,2,3,5,7,0,1] +Output: 8 +Explanation: n = 9 since there are 9 numbers, so all numbers are in the range [0,9]. 8 is the missing number in the range since it does not appear in nums. +``` + +  +**Constraints:** + + + +- `n == nums.length` + +- `1 <= n <= 104` + +- `0 <= nums[i] <= n` + +- All the numbers of `nums` are **unique**. + + +  +**Follow up:** Could you implement a solution using only `O(1)` extra space complexity and `O(n)` runtime complexity? + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @return {number} + */ +var missingNumber = function(nums) { + var sum = nums.reduce((s, i) => s + i, 0); + return nums.length * (nums.length + 1) / 2 - sum; +}; +``` + +**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/201-300/300. Longest Increasing Subsequence.md b/201-300/300. Longest Increasing Subsequence.md new file mode 100644 index 0000000..f3a8ecd --- /dev/null +++ b/201-300/300. Longest Increasing Subsequence.md @@ -0,0 +1,92 @@ +# 300. Longest Increasing Subsequence + +- Difficulty: Medium. +- Related Topics: Array, Binary Search, Dynamic Programming. +- Similar Questions: Increasing Triplet Subsequence, Russian Doll Envelopes, Maximum Length of Pair Chain, Number of Longest Increasing Subsequence, Minimum ASCII Delete Sum for Two Strings, Minimum Number of Removals to Make Mountain Array, Find the Longest Valid Obstacle Course at Each Position, Minimum Operations to Make the Array K-Increasing, Longest Ideal Subsequence, Maximum Number of Books You Can Take, Longest Increasing Subsequence II. + +## Problem + +Given an integer array `nums`, return **the length of the longest **strictly increasing ********subsequence****. + +  +Example 1: + +``` +Input: nums = [10,9,2,5,3,7,101,18] +Output: 4 +Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. +``` + +Example 2: + +``` +Input: nums = [0,1,0,3,2,3] +Output: 4 +``` + +Example 3: + +``` +Input: nums = [7,7,7,7,7,7,7] +Output: 1 +``` + +  +**Constraints:** + + + +- `1 <= nums.length <= 2500` + +- `-104 <= nums[i] <= 104` + + +  +**Follow up:** Can you come up with an algorithm that runs in `O(n log(n))` time complexity? + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @return {number} + */ +var lengthOfLIS = function(nums) { + var arr = [nums[0]]; + for (var i = 1; i < nums.length; i++) { + if (nums[i] > arr[arr.length - 1]) { + arr.push(nums[i]); + } else { + var index = binarySearch(arr, nums[i]); + arr[index] = nums[i]; + } + } + return arr.length; +}; + +var binarySearch = function(arr, num) { + var left = 0; + var right = arr.length - 1; + while (left < right) { + var mid = left + Math.floor((right - left) / 2); + if (arr[mid] > num) { + right = mid; + } else if (arr[mid] === num) { + return mid; + } else { + left = mid + 1; + } + } + return left; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * log(n)). +* Space complexity : O(n). diff --git a/2101-2200/2125. Number of Laser Beams in a Bank.md b/2101-2200/2125. Number of Laser Beams in a Bank.md new file mode 100644 index 0000000..073a879 --- /dev/null +++ b/2101-2200/2125. Number of Laser Beams in a Bank.md @@ -0,0 +1,100 @@ +# 2125. Number of Laser Beams in a Bank + +- Difficulty: Medium. +- Related Topics: Array, Math, String, Matrix. +- Similar Questions: Set Matrix Zeroes. + +## Problem + +Anti-theft security devices are activated inside a bank. You are given a **0-indexed** binary string array `bank` representing the floor plan of the bank, which is an `m x n` 2D matrix. `bank[i]` represents the `ith` row, consisting of `'0'`s and `'1'`s. `'0'` means the cell is empty, while`'1'` means the cell has a security device. + +There is **one** laser beam between any **two** security devices **if both** conditions are met: + + + +- The two devices are located on two **different rows**: `r1` and `r2`, where `r1 < r2`. + +- For **each** row `i` where `r1 < i < r2`, there are **no security devices** in the `ith` row. + + +Laser beams are independent, i.e., one beam does not interfere nor join with another. + +Return **the total number of laser beams in the bank**. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2021/12/24/laser1.jpg) + +``` +Input: bank = ["011001","000000","010100","001000"] +Output: 8 +Explanation: Between each of the following device pairs, there is one beam. In total, there are 8 beams: + * bank[0][1] -- bank[2][1] + * bank[0][1] -- bank[2][3] + * bank[0][2] -- bank[2][1] + * bank[0][2] -- bank[2][3] + * bank[0][5] -- bank[2][1] + * bank[0][5] -- bank[2][3] + * bank[2][1] -- bank[3][2] + * bank[2][3] -- bank[3][2] +Note that there is no beam between any device on the 0th row with any on the 3rd row. +This is because the 2nd row contains security devices, which breaks the second condition. +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2021/12/24/laser2.jpg) + +``` +Input: bank = ["000","111","000"] +Output: 0 +Explanation: There does not exist two devices located on two different rows. +``` + +  +**Constraints:** + + + +- `m == bank.length` + +- `n == bank[i].length` + +- `1 <= m, n <= 500` + +- `bank[i][j]` is either `'0'` or `'1'`. + + + +## Solution + +```javascript +/** + * @param {string[]} bank + * @return {number} + */ +var numberOfBeams = function(bank) { + var res = 0; + var lastRowDeviceNum = 0; + for (var i = 0; i < bank.length; i++) { + var deviceNum = 0; + for (var j = 0; j < bank[i].length; j++) { + if (bank[i][j] === '1') deviceNum++; + } + if (deviceNum === 0) continue; + res += lastRowDeviceNum * deviceNum; + lastRowDeviceNum = deviceNum; + } + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * m). +* Space complexity : O(1). 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/2353. Design a Food Rating System.md b/2301-2400/2353. Design a Food Rating System.md new file mode 100644 index 0000000..988bba5 --- /dev/null +++ b/2301-2400/2353. Design a Food Rating System.md @@ -0,0 +1,159 @@ +# 2353. Design a Food Rating System + +- Difficulty: Medium. +- Related Topics: Hash Table, Design, Heap (Priority Queue), Ordered Set. +- Similar Questions: Design a Number Container System, Most Popular Video Creator. + +## Problem + +Design a food rating system that can do the following: + + + +- **Modify** the rating of a food item listed in the system. + +- Return the highest-rated food item for a type of cuisine in the system. + + +Implement the `FoodRatings` class: + + + `FoodRatings(String[] foods, String[] cuisines, int[] ratings)` Initializes the system. The food items are described by `foods`, `cuisines` and `ratings`, all of which have a length of `n`. + + + +- `foods[i]` is the name of the `ith` food, + +- `cuisines[i]` is the type of cuisine of the `ith` food, and + +- `ratings[i]` is the initial rating of the `ith` food. + + + +- `void changeRating(String food, int newRating)` Changes the rating of the food item with the name `food`. + +- `String highestRated(String cuisine)` Returns the name of the food item that has the highest rating for the given type of `cuisine`. If there is a tie, return the item with the **lexicographically smaller** name. + + +Note that a string `x` is lexicographically smaller than string `y` if `x` comes before `y` in dictionary order, that is, either `x` is a prefix of `y`, or if `i` is the first position such that `x[i] != y[i]`, then `x[i]` comes before `y[i]` in alphabetic order. + +  +Example 1: + +``` +Input +["FoodRatings", "highestRated", "highestRated", "changeRating", "highestRated", "changeRating", "highestRated"] +[[["kimchi", "miso", "sushi", "moussaka", "ramen", "bulgogi"], ["korean", "japanese", "japanese", "greek", "japanese", "korean"], [9, 12, 8, 15, 14, 7]], ["korean"], ["japanese"], ["sushi", 16], ["japanese"], ["ramen", 16], ["japanese"]] +Output +[null, "kimchi", "ramen", null, "sushi", null, "ramen"] + +Explanation +FoodRatings foodRatings = new FoodRatings(["kimchi", "miso", "sushi", "moussaka", "ramen", "bulgogi"], ["korean", "japanese", "japanese", "greek", "japanese", "korean"], [9, 12, 8, 15, 14, 7]); +foodRatings.highestRated("korean"); // return "kimchi" + // "kimchi" is the highest rated korean food with a rating of 9. +foodRatings.highestRated("japanese"); // return "ramen" + // "ramen" is the highest rated japanese food with a rating of 14. +foodRatings.changeRating("sushi", 16); // "sushi" now has a rating of 16. +foodRatings.highestRated("japanese"); // return "sushi" + // "sushi" is the highest rated japanese food with a rating of 16. +foodRatings.changeRating("ramen", 16); // "ramen" now has a rating of 16. +foodRatings.highestRated("japanese"); // return "ramen" + // Both "sushi" and "ramen" have a rating of 16. + // However, "ramen" is lexicographically smaller than "sushi". +``` + +  +**Constraints:** + + + +- `1 <= n <= 2 * 104` + +- `n == foods.length == cuisines.length == ratings.length` + +- `1 <= foods[i].length, cuisines[i].length <= 10` + +- `foods[i]`, `cuisines[i]` consist of lowercase English letters. + +- `1 <= ratings[i] <= 108` + +- All the strings in `foods` are **distinct**. + +- `food` will be the name of a food item in the system across all calls to `changeRating`. + +- `cuisine` will be a type of cuisine of **at least one** food item in the system across all calls to `highestRated`. + +- At most `2 * 104` calls **in total** will be made to `changeRating` and `highestRated`. + + + +## Solution + +```javascript +/** + * @param {string[]} foods + * @param {string[]} cuisines + * @param {number[]} ratings + */ +var FoodRatings = function(foods, cuisines, ratings) { + this.foodsMap = {}; + this.cuisinesMap = {}; + this.getRatingWithName = function(food, rating) { + var z = 'z'.charCodeAt(0); + var foodNameRating = food.split('') + .map(char => z - char.charCodeAt(0)) + .map(num => num < 10 ? `0${num}` : `${num}`) + .join(''); + var rate = Number(`${rating}.${foodNameRating}`); + return rate; + }; + for (var i = 0; i < foods.length; i++) { + var rate = this.getRatingWithName(foods[i], ratings[i]); + this.foodsMap[foods[i]] = [cuisines[i], rate]; + if (!this.cuisinesMap[cuisines[i]]) { + this.cuisinesMap[cuisines[i]] = new MaxPriorityQueue(); + } + this.cuisinesMap[cuisines[i]].enqueue(foods[i], rate); + } +}; + +/** + * @param {string} food + * @param {number} newRating + * @return {void} + */ +FoodRatings.prototype.changeRating = function(food, newRating) { + var rate = this.getRatingWithName(food, newRating); + this.foodsMap[food][1] = rate; + this.cuisinesMap[this.foodsMap[food][0]].enqueue(food, rate); +}; + +/** + * @param {string} cuisine + * @return {string} + */ +FoodRatings.prototype.highestRated = function(cuisine) { + var item = this.cuisinesMap[cuisine].front(); + while (this.foodsMap[item.element][1] !== item.priority) { + this.cuisinesMap[cuisine].dequeue(); + item = this.cuisinesMap[cuisine].front(); + } + return item.element; +}; + +/** + * Your FoodRatings object will be instantiated and called as such: + * var obj = new FoodRatings(foods, cuisines, ratings) + * obj.changeRating(food,newRating) + * var param_2 = obj.highestRated(cuisine) + */ +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * log(n) + m * log(n)). +* Space complexity : O(n). diff --git a/2301-2400/2374. Node With Highest Edge Score.md b/2301-2400/2374. Node With Highest Edge Score.md new file mode 100644 index 0000000..3bdbe25 --- /dev/null +++ b/2301-2400/2374. Node With Highest Edge Score.md @@ -0,0 +1,89 @@ +# 2374. Node With Highest Edge Score + +- Difficulty: Medium. +- Related Topics: Hash Table, Graph. +- Similar Questions: Two Sum, Sort Characters By Frequency, Sort Array by Increasing Frequency. + +## Problem + +You are given a directed graph with `n` nodes labeled from `0` to `n - 1`, where each node has **exactly one** outgoing edge. + +The graph is represented by a given **0-indexed** integer array `edges` of length `n`, where `edges[i]` indicates that there is a **directed** edge from node `i` to node `edges[i]`. + +The **edge score** of a node `i` is defined as the sum of the **labels** of all the nodes that have an edge pointing to `i`. + +Return **the node with the highest **edge score****. If multiple nodes have the same **edge score**, return the node with the **smallest** index. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2022/06/20/image-20220620195403-1.png) + +``` +Input: edges = [1,0,0,0,0,7,7,5] +Output: 7 +Explanation: +- The nodes 1, 2, 3 and 4 have an edge pointing to node 0. The edge score of node 0 is 1 + 2 + 3 + 4 = 10. +- The node 0 has an edge pointing to node 1. The edge score of node 1 is 0. +- The node 7 has an edge pointing to node 5. The edge score of node 5 is 7. +- The nodes 5 and 6 have an edge pointing to node 7. The edge score of node 7 is 5 + 6 = 11. +Node 7 has the highest edge score so return 7. +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2022/06/20/image-20220620200212-3.png) + +``` +Input: edges = [2,0,0,2] +Output: 0 +Explanation: +- The nodes 1 and 2 have an edge pointing to node 0. The edge score of node 0 is 1 + 2 = 3. +- The nodes 0 and 3 have an edge pointing to node 2. The edge score of node 2 is 0 + 3 = 3. +Nodes 0 and 2 both have an edge score of 3. Since node 0 has a smaller index, we return 0. +``` + +  +**Constraints:** + + + +- `n == edges.length` + +- `2 <= n <= 105` + +- `0 <= edges[i] < n` + +- `edges[i] != i` + + + +## Solution + +```javascript +/** + * @param {number[]} edges + * @return {number} + */ +var edgeScore = function(edges) { + var sumMap = Array(edges.length).fill(0); + var maxSumNode = 0; + for (var i = 0; i < edges.length; i++) { + sumMap[edges[i]] += i; + if (sumMap[edges[i]] > sumMap[maxSumNode] + || (sumMap[edges[i]] === sumMap[maxSumNode] && maxSumNode > edges[i])) { + maxSumNode = edges[i]; + } + } + return maxSumNode; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/2301-2400/2385. Amount of Time for Binary Tree to Be Infected.md b/2301-2400/2385. Amount of Time for Binary Tree to Be Infected.md new file mode 100644 index 0000000..440212a --- /dev/null +++ b/2301-2400/2385. Amount of Time for Binary Tree to Be Infected.md @@ -0,0 +1,117 @@ +# 2385. Amount of Time for Binary Tree to Be Infected + +- Difficulty: Medium. +- Related Topics: Tree, Depth-First Search, Breadth-First Search, Binary Tree. +- Similar Questions: Maximum Depth of Binary Tree, Shortest Path to Get Food, All Nodes Distance K in Binary Tree, Count the Number of Infection Sequences. + +## Problem + +You are given the `root` of a binary tree with **unique** values, and an integer `start`. At minute `0`, an **infection** starts from the node with value `start`. + +Each minute, a node becomes infected if: + + + +- The node is currently uninfected. + +- The node is adjacent to an infected node. + + +Return **the number of minutes needed for the entire tree to be infected.** + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2022/06/25/image-20220625231744-1.png) + +``` +Input: root = [1,5,3,null,4,10,6,9,2], start = 3 +Output: 4 +Explanation: The following nodes are infected during: +- Minute 0: Node 3 +- Minute 1: Nodes 1, 10 and 6 +- Minute 2: Node 5 +- Minute 3: Node 4 +- Minute 4: Nodes 9 and 2 +It takes 4 minutes for the whole tree to be infected so we return 4. +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2022/06/25/image-20220625231812-2.png) + +``` +Input: root = [1], start = 1 +Output: 0 +Explanation: At minute 0, the only node in the tree is infected so we return 0. +``` + +  +**Constraints:** + + + +- The number of nodes in the tree is in the range `[1, 105]`. + +- `1 <= Node.val <= 105` + +- Each node has a **unique** value. + +- A node with a value of `start` exists in the tree. + + + +## 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} start + * @return {number} + */ +var amountOfTime = function(root, start) { + const startNode = findStartNode(root, start, null); + return findLongestPath(root, startNode, 0, {}); +}; + +var findStartNode = function(node, start, parent) { + if (!node) return null; + const startNode = (node.val === start ? node : null) + || findStartNode(node.left, start, node) + || findStartNode(node.right, start, node); + if (startNode) { + node.parent = parent; + return startNode; + } + return null; +}; + +var findLongestPath = function(root, node, depth, visited) { + if (!node || visited[node.val]) return 0; + visited[node.val] = true; + if (!node.left && !node.right && !node.parent) return depth; + return Math.max( + node === root ? depth : 0, + findLongestPath(root, node.left, depth + 1, visited), + findLongestPath(root, node.right, depth + 1, visited), + findLongestPath(root, node.parent, depth + 1, visited), + ); +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/2301-2400/2390. Removing Stars From a String.md b/2301-2400/2390. Removing Stars From a String.md new file mode 100644 index 0000000..d1887a3 --- /dev/null +++ b/2301-2400/2390. Removing Stars From a String.md @@ -0,0 +1,92 @@ +# 2390. Removing Stars From a String + +- Difficulty: Medium. +- Related Topics: String, Stack, Simulation. +- Similar Questions: Backspace String Compare, Remove All Adjacent Duplicates In String. + +## Problem + +You are given a string `s`, which contains stars `*`. + +In one operation, you can: + + + +- Choose a star in `s`. + +- Remove the closest **non-star** character to its **left**, as well as remove the star itself. + + +Return **the string after **all** stars have been removed**. + +**Note:** + + + +- The input will be generated such that the operation is always possible. + +- It can be shown that the resulting string will always be unique. + + +  +Example 1: + +``` +Input: s = "leet**cod*e" +Output: "lecoe" +Explanation: Performing the removals from left to right: +- The closest character to the 1st star is 't' in "leet**cod*e". s becomes "lee*cod*e". +- The closest character to the 2nd star is 'e' in "lee*cod*e". s becomes "lecod*e". +- The closest character to the 3rd star is 'd' in "lecod*e". s becomes "lecoe". +There are no more stars, so we return "lecoe". +``` + +Example 2: + +``` +Input: s = "erase*****" +Output: "" +Explanation: The entire string is removed, so we return an empty string. +``` + +  +**Constraints:** + + + +- `1 <= s.length <= 105` + +- `s` consists of lowercase English letters and stars `*`. + +- The operation above can be performed on `s`. + + + +## Solution + +```javascript +/** + * @param {string} s + * @return {string} + */ +var removeStars = function(s) { + var stack = []; + for (var i = 0; i < s.length; i++) { + if (s[i] === '*') { + stack.pop(); + } else { + stack.push(s[i]); + } + } + return stack.join(''); +}; +``` + +**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/2461. Maximum Sum of Distinct Subarrays With Length K.md b/2401-2500/2461. Maximum Sum of Distinct Subarrays With Length K.md new file mode 100644 index 0000000..f0b2637 --- /dev/null +++ b/2401-2500/2461. Maximum Sum of Distinct Subarrays With Length K.md @@ -0,0 +1,106 @@ +# 2461. Maximum Sum of Distinct Subarrays With Length K + +- Difficulty: Medium. +- Related Topics: Array, Hash Table, Sliding Window. +- Similar Questions: Max Consecutive Ones III, Longest Nice Subarray, Optimal Partition of String, Count the Number of Good Subarrays. + +## Problem + +You are given an integer array `nums` and an integer `k`. Find the maximum subarray sum of all the subarrays of `nums` that meet the following conditions: + + + +- The length of the subarray is `k`, and + +- All the elements of the subarray are **distinct**. + + +Return **the maximum subarray sum of all the subarrays that meet the conditions****.** If no subarray meets the conditions, return `0`. + +**A **subarray** is a contiguous non-empty sequence of elements within an array.** + +  +Example 1: + +``` +Input: nums = [1,5,4,2,9,9,9], k = 3 +Output: 15 +Explanation: The subarrays of nums with length 3 are: +- [1,5,4] which meets the requirements and has a sum of 10. +- [5,4,2] which meets the requirements and has a sum of 11. +- [4,2,9] which meets the requirements and has a sum of 15. +- [2,9,9] which does not meet the requirements because the element 9 is repeated. +- [9,9,9] which does not meet the requirements because the element 9 is repeated. +We return 15 because it is the maximum subarray sum of all the subarrays that meet the conditions +``` + +Example 2: + +``` +Input: nums = [4,4,4], k = 3 +Output: 0 +Explanation: The subarrays of nums with length 3 are: +- [4,4,4] which does not meet the requirements because the element 4 is repeated. +We return 0 because no subarrays meet the conditions. +``` + +  +**Constraints:** + + + +- `1 <= k <= nums.length <= 105` + +- `1 <= nums[i] <= 105` + + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var maximumSubarraySum = function(nums, k) { + var map = {}; + var duplicateNums = 0; + var sum = 0; + for (var j = 0; j < k; j++) { + map[nums[j]] = (map[nums[j]] || 0) + 1; + sum += nums[j]; + if (map[nums[j]] === 2) { + duplicateNums++; + } + } + var maxSum = duplicateNums === 0 ? sum : 0; + for (var i = k; i < nums.length; i++) { + var num = map[nums[i]] || 0; + var before = map[nums[i - k]]; + map[nums[i]] = num + 1; + map[nums[i - k]]--; + sum += nums[i]; + sum -= nums[i - k]; + if (num === 1 && map[nums[i]] === 2) { + duplicateNums++; + } + if (before === 2 && map[nums[i - k]] === 1) { + duplicateNums--; + } + if (duplicateNums === 0) { + maxSum = Math.max(maxSum, sum); + } + } + return maxSum; +}; +``` + +**Explain:** + +Sliding window and hash map. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/2401-2500/2482. Difference Between Ones and Zeros in Row and Column.md b/2401-2500/2482. Difference Between Ones and Zeros in Row and Column.md new file mode 100644 index 0000000..a8e79a8 --- /dev/null +++ b/2401-2500/2482. Difference Between Ones and Zeros in Row and Column.md @@ -0,0 +1,124 @@ +# 2482. Difference Between Ones and Zeros in Row and Column + +- Difficulty: Medium. +- Related Topics: Array, Matrix, Simulation. +- Similar Questions: 01 Matrix, Special Positions in a Binary Matrix, Remove All Ones With Row and Column Flips, First Completely Painted Row or Column. + +## Problem + +You are given a **0-indexed** `m x n` binary matrix `grid`. + +A **0-indexed** `m x n` difference matrix `diff` is created with the following procedure: + + + +- Let the number of ones in the `ith` row be `onesRowi`. + +- Let the number of ones in the `jth` column be `onesColj`. + +- Let the number of zeros in the `ith` row be `zerosRowi`. + +- Let the number of zeros in the `jth` column be `zerosColj`. + +- `diff[i][j] = onesRowi + onesColj - zerosRowi - zerosColj` + + +Return **the difference matrix **`diff`. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2022/11/06/image-20221106171729-5.png) + +``` +Input: grid = [[0,1,1],[1,0,1],[0,0,1]] +Output: [[0,0,4],[0,0,4],[-2,-2,2]] +Explanation: +- diff[0][0] = onesRow0 + onesCol0 - zerosRow0 - zerosCol0 = 2 + 1 - 1 - 2 = 0 +- diff[0][1] = onesRow0 + onesCol1 - zerosRow0 - zerosCol1 = 2 + 1 - 1 - 2 = 0 +- diff[0][2] = onesRow0 + onesCol2 - zerosRow0 - zerosCol2 = 2 + 3 - 1 - 0 = 4 +- diff[1][0] = onesRow1 + onesCol0 - zerosRow1 - zerosCol0 = 2 + 1 - 1 - 2 = 0 +- diff[1][1] = onesRow1 + onesCol1 - zerosRow1 - zerosCol1 = 2 + 1 - 1 - 2 = 0 +- diff[1][2] = onesRow1 + onesCol2 - zerosRow1 - zerosCol2 = 2 + 3 - 1 - 0 = 4 +- diff[2][0] = onesRow2 + onesCol0 - zerosRow2 - zerosCol0 = 1 + 1 - 2 - 2 = -2 +- diff[2][1] = onesRow2 + onesCol1 - zerosRow2 - zerosCol1 = 1 + 1 - 2 - 2 = -2 +- diff[2][2] = onesRow2 + onesCol2 - zerosRow2 - zerosCol2 = 1 + 3 - 2 - 0 = 2 +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2022/11/06/image-20221106171747-6.png) + +``` +Input: grid = [[1,1,1],[1,1,1]] +Output: [[5,5,5],[5,5,5]] +Explanation: +- diff[0][0] = onesRow0 + onesCol0 - zerosRow0 - zerosCol0 = 3 + 2 - 0 - 0 = 5 +- diff[0][1] = onesRow0 + onesCol1 - zerosRow0 - zerosCol1 = 3 + 2 - 0 - 0 = 5 +- diff[0][2] = onesRow0 + onesCol2 - zerosRow0 - zerosCol2 = 3 + 2 - 0 - 0 = 5 +- diff[1][0] = onesRow1 + onesCol0 - zerosRow1 - zerosCol0 = 3 + 2 - 0 - 0 = 5 +- diff[1][1] = onesRow1 + onesCol1 - zerosRow1 - zerosCol1 = 3 + 2 - 0 - 0 = 5 +- diff[1][2] = onesRow1 + onesCol2 - zerosRow1 - zerosCol2 = 3 + 2 - 0 - 0 = 5 +``` + +  +**Constraints:** + + + +- `m == grid.length` + +- `n == grid[i].length` + +- `1 <= m, n <= 105` + +- `1 <= m * n <= 105` + +- `grid[i][j]` is either `0` or `1`. + + + +## Solution + +```javascript +/** + * @param {number[][]} grid + * @return {number[][]} + */ +var onesMinusZeros = function(grid) { + var m = grid.length; + var n = grid[0].length; + var colOnes = Array(n).fill(0); + var colZeros = Array(n).fill(0); + var rowOnes = Array(m).fill(0); + var rowZeros = Array(m).fill(0); + for (var i = 0; i < m; i++) { + for (var j = 0; j < n; j++) { + if (grid[i][j] === 1) { + rowOnes[i]++; + colOnes[j]++; + } + if (grid[i][j] === 0) { + rowZeros[i]++; + colZeros[j]++; + } + } + } + var diff = Array(m).fill(0).map(() => Array(n).fill(0)); + for (var i = 0; i < m; i++) { + for (var j = 0; j < n; j++) { + diff[i][j] = rowOnes[i] + colOnes[j] - rowZeros[i] - colZeros[j]; + } + } + return diff; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * m). +* Space complexity : O(n * m). 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/2610. Convert an Array Into a 2D Array With Conditions.md b/2601-2700/2610. Convert an Array Into a 2D Array With Conditions.md new file mode 100644 index 0000000..3e58918 --- /dev/null +++ b/2601-2700/2610. Convert an Array Into a 2D Array With Conditions.md @@ -0,0 +1,87 @@ +# 2610. Convert an Array Into a 2D Array With Conditions + +- Difficulty: Medium. +- Related Topics: Array, Hash Table. +- Similar Questions: . + +## Problem + +You are given an integer array `nums`. You need to create a 2D array from `nums` satisfying the following conditions: + + + +- The 2D array should contain **only** the elements of the array `nums`. + +- Each row in the 2D array contains **distinct** integers. + +- The number of rows in the 2D array should be **minimal**. + + +Return **the resulting array**. If there are multiple answers, return any of them. + +**Note** that the 2D array can have a different number of elements on each row. + +  +Example 1: + +``` +Input: nums = [1,3,4,1,2,3,1] +Output: [[1,3,4,2],[1,3],[1]] +Explanation: We can create a 2D array that contains the following rows: +- 1,3,4,2 +- 1,3 +- 1 +All elements of nums were used, and each row of the 2D array contains distinct integers, so it is a valid answer. +It can be shown that we cannot have less than 3 rows in a valid array. +``` + +Example 2: + +``` +Input: nums = [1,2,3,4] +Output: [[4,3,2,1]] +Explanation: All elements of the array are distinct, so we can keep all of them in the first row of the 2D array. +``` + +  +**Constraints:** + + + +- `1 <= nums.length <= 200` + +- `1 <= nums[i] <= nums.length` + + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @return {number[][]} + */ +var findMatrix = function(nums) { + var numMap = Array(nums.length + 1).fill(0); + var res = []; + for (var i = 0; i < nums.length; i++) { + var num = nums[i]; + var row = numMap[nums[i]]; + if (!res[row]) { + res.push([]); + } + res[row].push(num); + numMap[num]++; + } + return res; +}; +``` + +**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/2706. Buy Two Chocolates.md b/2701-2800/2706. Buy Two Chocolates.md new file mode 100644 index 0000000..040523d --- /dev/null +++ b/2701-2800/2706. Buy Two Chocolates.md @@ -0,0 +1,77 @@ +# 2706. Buy Two Chocolates + +- Difficulty: Easy. +- Related Topics: Array, Sorting. +- Similar Questions: . + +## Problem + +You are given an integer array `prices` representing the prices of various chocolates in a store. You are also given a single integer `money`, which represents your initial amount of money. + +You must buy **exactly** two chocolates in such a way that you still have some **non-negative** leftover money. You would like to minimize the sum of the prices of the two chocolates you buy. + +Return **the amount of money you will have leftover after buying the two chocolates**. If there is no way for you to buy two chocolates without ending up in debt, return `money`. Note that the leftover must be non-negative. + +  +Example 1: + +``` +Input: prices = [1,2,2], money = 3 +Output: 0 +Explanation: Purchase the chocolates priced at 1 and 2 units respectively. You will have 3 - 3 = 0 units of money afterwards. Thus, we return 0. +``` + +Example 2: + +``` +Input: prices = [3,2,3], money = 3 +Output: 3 +Explanation: You cannot buy 2 chocolates without going in debt, so we return 3. +``` + +  +**Constraints:** + + + +- `2 <= prices.length <= 50` + +- `1 <= prices[i] <= 100` + +- `1 <= money <= 100` + + + +## Solution + +```javascript +/** + * @param {number[]} prices + * @param {number} money + * @return {number} + */ +var buyChoco = function(prices, money) { + var minPrice = 0; + var secondMinPrice = 0; + for (var i = 0; i < prices.length; i++) { + if (minPrice === 0 || prices[i] < minPrice) { + secondMinPrice = minPrice; + minPrice = prices[i]; + } else if (secondMinPrice === 0 || prices[i] < secondMinPrice) { + secondMinPrice = prices[i]; + } + } + return (minPrice !== 0 && secondMinPrice !== 0 && secondMinPrice + minPrice <= money) + ? money - (secondMinPrice + minPrice) + : money; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). 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/2801-2900/2864. Maximum Odd Binary Number.md b/2801-2900/2864. Maximum Odd Binary Number.md new file mode 100644 index 0000000..2e28009 --- /dev/null +++ b/2801-2900/2864. Maximum Odd Binary Number.md @@ -0,0 +1,67 @@ +# 2864. Maximum Odd Binary Number + +- Difficulty: Easy. +- Related Topics: Math, String, Greedy. +- Similar Questions: . + +## Problem + +You are given a **binary** string `s` that contains at least one `'1'`. + +You have to **rearrange** the bits in such a way that the resulting binary number is the **maximum odd binary number** that can be created from this combination. + +Return **a string representing the maximum odd binary number that can be created from the given combination.** + +**Note **that the resulting string **can** have leading zeros. + +  +Example 1: + +``` +Input: s = "010" +Output: "001" +Explanation: Because there is just one '1', it must be in the last position. So the answer is "001". +``` + +Example 2: + +``` +Input: s = "0101" +Output: "1001" +Explanation: One of the '1's must be in the last position. The maximum number that can be made with the remaining digits is "100". So the answer is "1001". +``` + +  +**Constraints:** + + + +- `1 <= s.length <= 100` + +- `s` consists only of `'0'` and `'1'`. + +- `s` contains at least one `'1'`. + + + +## Solution + +```javascript +/** + * @param {string} s + * @return {string} + */ +var maximumOddBinaryNumber = function(s) { + var numOfOnes = s.split('').reduce((sum, num) => sum + Number(num), 0); + return '1'.repeat(numOfOnes - 1) + '0'.repeat(s.length - numOfOnes) + '1'; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/2901-3000/2966. Divide Array Into Arrays With Max Difference.md b/2901-3000/2966. Divide Array Into Arrays With Max Difference.md new file mode 100644 index 0000000..35e64d6 --- /dev/null +++ b/2901-3000/2966. Divide Array Into Arrays With Max Difference.md @@ -0,0 +1,87 @@ +# 2966. Divide Array Into Arrays With Max Difference + +- Difficulty: Medium. +- Related Topics: Array, Greedy, Sorting. +- Similar Questions: . + +## Problem + +You are given an integer array `nums` of size `n` and a positive integer `k`. + +Divide the array into one or more arrays of size `3` satisfying the following conditions: + + + +- **Each** element of `nums` should be in **exactly** one array. + +- The difference between **any** two elements in one array is less than or equal to `k`. + + +Return **a ****2D**** array containing all the arrays. If it is impossible to satisfy the conditions, return an empty array. And if there are multiple answers, return **any** of them.** + +  +Example 1: + +``` +Input: nums = [1,3,4,8,7,9,3,5,1], k = 2 +Output: [[1,1,3],[3,4,5],[7,8,9]] +Explanation: We can divide the array into the following arrays: [1,1,3], [3,4,5] and [7,8,9]. +The difference between any two elements in each array is less than or equal to 2. +Note that the order of elements is not important. +``` + +Example 2: + +``` +Input: nums = [1,3,3,2,7,3], k = 3 +Output: [] +Explanation: It is not possible to divide the array satisfying all the conditions. +``` + +  +**Constraints:** + + + +- `n == nums.length` + +- `1 <= n <= 105` + +- `n` is a multiple of `3`. + +- `1 <= nums[i] <= 105` + +- `1 <= k <= 105` + + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @param {number} k + * @return {number[][]} + */ +var divideArray = function(nums, k) { + nums.sort((a, b) => a - b); + var res = []; + for (var i = 0; i < nums.length; i += 3) { + if (nums[i + 2] - nums[i] <= k) { + res.push([nums[i], nums[i + 1], nums[i + 2]]); + } else { + return []; + } + } + return res; +}; +``` + +**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/301-400/387. First Unique Character in a String.md b/301-400/387. First Unique Character in a String.md new file mode 100644 index 0000000..0b65925 --- /dev/null +++ b/301-400/387. First Unique Character in a String.md @@ -0,0 +1,62 @@ +# 387. First Unique Character in a String + +- Difficulty: Easy. +- Related Topics: Hash Table, String, Queue, Counting. +- Similar Questions: Sort Characters By Frequency, First Letter to Appear Twice. + +## Problem + +Given a string `s`, **find the first non-repeating character in it and return its index**. If it does not exist, return `-1`. + +  +Example 1: +``` +Input: s = "leetcode" +Output: 0 +```Example 2: +``` +Input: s = "loveleetcode" +Output: 2 +```Example 3: +``` +Input: s = "aabb" +Output: -1 +``` +  +**Constraints:** + + + +- `1 <= s.length <= 105` + +- `s` consists of only lowercase English letters. + + + +## Solution + +```javascript +/** + * @param {string} s + * @return {number} + */ +var firstUniqChar = function(s) { + var map = {}; + for (var i = 0; i < s.length; i++) { + map[s[i]] = (map[s[i]] || 0) + 1; + } + for (var i = 0; i < s.length; i++) { + if (map[s[i]] === 1) return i; + } + return -1; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/401-500/455. Assign Cookies.md b/401-500/455. Assign Cookies.md new file mode 100644 index 0000000..d3848c9 --- /dev/null +++ b/401-500/455. Assign Cookies.md @@ -0,0 +1,75 @@ +# 455. Assign Cookies + +- Difficulty: Easy. +- Related Topics: Array, Two Pointers, Greedy, Sorting. +- Similar Questions: . + +## Problem + +Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. + +Each child `i` has a greed factor `g[i]`, which is the minimum size of a cookie that the child will be content with; and each cookie `j` has a size `s[j]`. If `s[j] >= g[i]`, we can assign the cookie `j` to the child `i`, and the child `i` will be content. Your goal is to maximize the number of your content children and output the maximum number. + +  +Example 1: + +``` +Input: g = [1,2,3], s = [1,1] +Output: 1 +Explanation: You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. +And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content. +You need to output 1. +``` + +Example 2: + +``` +Input: g = [1,2], s = [1,2,3] +Output: 2 +Explanation: You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. +You have 3 cookies and their sizes are big enough to gratify all of the children, +You need to output 2. +``` + +  +**Constraints:** + + + +- `1 <= g.length <= 3 * 104` + +- `0 <= s.length <= 3 * 104` + +- `1 <= g[i], s[j] <= 231 - 1` + + + +## Solution + +```javascript +/** + * @param {number[]} g + * @param {number[]} s + * @return {number} + */ +var findContentChildren = function(g, s) { + g.sort((a, b) => a - b); + s.sort((a, b) => a - b); + var j = 0; + for (var i = 0; i < g.length; i++) { + while (s[j] < g[i] && j < s.length) j++; + if (j === s.length) return i; + j++; + } + return g.length; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * log(n)). +* Space complexity : O(1). diff --git a/401-500/478. Generate Random Point in a Circle.md b/401-500/478. Generate Random Point in a Circle.md new file mode 100644 index 0000000..fbe35f1 --- /dev/null +++ b/401-500/478. Generate Random Point in a Circle.md @@ -0,0 +1,93 @@ +# 478. Generate Random Point in a Circle + +- Difficulty: Medium. +- Related Topics: Math, Geometry, Rejection Sampling, Randomized. +- Similar Questions: Random Point in Non-overlapping Rectangles. + +## Problem + +Given the radius and the position of the center of a circle, implement the function `randPoint` which generates a uniform random point inside the circle. + +Implement the `Solution` class: + + + +- `Solution(double radius, double x_center, double y_center)` initializes the object with the radius of the circle `radius` and the position of the center `(x_center, y_center)`. + +- `randPoint()` returns a random point inside the circle. A point on the circumference of the circle is considered to be in the circle. The answer is returned as an array `[x, y]`. + + +  +Example 1: + +``` +Input +["Solution", "randPoint", "randPoint", "randPoint"] +[[1.0, 0.0, 0.0], [], [], []] +Output +[null, [-0.02493, -0.38077], [0.82314, 0.38945], [0.36572, 0.17248]] + +Explanation +Solution solution = new Solution(1.0, 0.0, 0.0); +solution.randPoint(); // return [-0.02493, -0.38077] +solution.randPoint(); // return [0.82314, 0.38945] +solution.randPoint(); // return [0.36572, 0.17248] +``` + +  +**Constraints:** + + + +- `0 < radius <= 108` + +- `-107 <= x_center, y_center <= 107` + +- At most `3 * 104` calls will be made to `randPoint`. + + + +## Solution + +```javascript +/** + * @param {number} radius + * @param {number} x_center + * @param {number} y_center + */ +var Solution = function(radius, x_center, y_center) { + this.radius = radius; + this.centerX = x_center; + this.centerY = y_center; +}; + +/** + * @return {number[]} + */ +Solution.prototype.randPoint = function() { + var radius = Math.sqrt(Math.random()) * this.radius; + var rand = Math.random(); + var degree = Math.PI / 2 * (rand === 1 ? 0 : rand); + var x = Math.cos(degree) * radius; + var y = Math.sin(degree) * radius; + return [ + this.centerX + (Math.random() > 0.5 ? 1 : -1) * x, + this.centerY + (Math.random() > 0.5 ? 1 : -1) * y, + ]; +}; + +/** + * Your Solution object will be instantiated and called as such: + * var obj = new Solution(radius, x_center, y_center) + * var param_1 = obj.randPoint() + */ +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/501-600/513. Find Bottom Left Tree Value.md b/501-600/513. Find Bottom Left Tree Value.md new file mode 100644 index 0000000..27bd8bb --- /dev/null +++ b/501-600/513. Find Bottom Left Tree Value.md @@ -0,0 +1,74 @@ +# 513. Find Bottom Left Tree Value + +- Difficulty: Medium. +- Related Topics: Tree, Depth-First Search, Breadth-First Search, Binary Tree. +- Similar Questions: . + +## Problem + +Given the `root` of a binary tree, return the leftmost value in the last row of the tree. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2020/12/14/tree1.jpg) + +``` +Input: root = [2,1,3] +Output: 1 +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2020/12/14/tree2.jpg) + +``` +Input: root = [1,2,3,4,null,5,6,null,null,7] +Output: 7 +``` + +  +**Constraints:** + + + +- The number of nodes in the tree is in the range `[1, 104]`. + +- `-231 <= Node.val <= 231 - 1` + + + +## 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 + * @return {number} + */ +var findBottomLeftValue = function(root) { + return dfs(root, 0)[0]; +}; + +var dfs = function(node, depth) { + var left = node.left ? dfs(node.left, depth + 1) : [node.val, depth]; + var right = node.right ? dfs(node.right, depth + 1) : [node.val, depth]; + return right[1] > left[1] ? right : left; +}; +``` + +**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/501-600/516. Longest Palindromic Subsequence.md b/501-600/516. Longest Palindromic Subsequence.md new file mode 100644 index 0000000..6a24da1 --- /dev/null +++ b/501-600/516. Longest Palindromic Subsequence.md @@ -0,0 +1,75 @@ +# 516. Longest Palindromic Subsequence + +- Difficulty: Medium. +- Related Topics: String, Dynamic Programming. +- Similar Questions: Longest Palindromic Substring, Palindromic Substrings, Count Different Palindromic Subsequences, Longest Common Subsequence, Longest Palindromic Subsequence II, Maximize Palindrome Length From Subsequences, Maximum Product of the Length of Two Palindromic Subsequences. + +## Problem + +Given a string `s`, find **the longest palindromic **subsequence**'s length in** `s`. + +A **subsequence** is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. + +  +Example 1: + +``` +Input: s = "bbbab" +Output: 4 +Explanation: One possible longest palindromic subsequence is "bbbb". +``` + +Example 2: + +``` +Input: s = "cbbd" +Output: 2 +Explanation: One possible longest palindromic subsequence is "bb". +``` + +  +**Constraints:** + + + +- `1 <= s.length <= 1000` + +- `s` consists only of lowercase English letters. + + + +## Solution + +```javascript +/** + * @param {string} s + * @return {number} + */ +var longestPalindromeSubseq = function(s) { + var dp = Array(s.length).fill(0).map(() => Array(s.length)); + var helper = function(i, j) { + if (j < i) return 0; + if (dp[i][j] !== undefined) return dp[i][j]; + if (s[i] === s[j]) { + dp[i][j] = (i === j ? 1 : 2) + helper(i + 1, j - 1); + } else { + dp[i][j] = Math.max( + helper(i + 1, j), + helper(i, j - 1), + helper(i + 1, j - 1), + ); + } + return dp[i][j]; + }; + return helper(0, s.length - 1); +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * m). +* Space complexity : O(n * m). diff --git a/501-600/518. Coin Change II.md b/501-600/518. Coin Change II.md new file mode 100644 index 0000000..e8c9b0d --- /dev/null +++ b/501-600/518. Coin Change II.md @@ -0,0 +1,96 @@ +# 518. Coin Change II + +- Difficulty: Medium. +- Related Topics: Array, Dynamic Programming. +- Similar Questions: Maximum Value of K Coins From Piles, Number of Ways to Earn Points, Count of Sub-Multisets With Bounded Sum, Length of the Longest Subsequence That Sums to Target. + +## Problem + +You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money. + +Return **the number of combinations that make up that amount**. If that amount of money cannot be made up by any combination of the coins, return `0`. + +You may assume that you have an infinite number of each kind of coin. + +The answer is **guaranteed** to fit into a signed **32-bit** integer. + +  +Example 1: + +``` +Input: amount = 5, coins = [1,2,5] +Output: 4 +Explanation: there are four ways to make up the amount: +5=5 +5=2+2+1 +5=2+1+1+1 +5=1+1+1+1+1 +``` + +Example 2: + +``` +Input: amount = 3, coins = [2] +Output: 0 +Explanation: the amount of 3 cannot be made up just with coins of 2. +``` + +Example 3: + +``` +Input: amount = 10, coins = [10] +Output: 1 +``` + +  +**Constraints:** + + + +- `1 <= coins.length <= 300` + +- `1 <= coins[i] <= 5000` + +- All the values of `coins` are **unique**. + +- `0 <= amount <= 5000` + + + +## Solution + +```javascript +/** + * @param {number} amount + * @param {number[]} coins + * @return {number} + */ +var change = function(amount, coins) { + coins.sort((a, b) => b - a); + return helper(amount, coins, Array(coins.length + 1).fill(0).map(() => [])); +}; + +var helper = function(amount, coins, dp) { + if (amount === 0) return 1; + if (dp[coins.length][amount] !== undefined) return dp[coins.length][amount]; + var res = 0; + for (var i = 0; i < coins.length; i++) { + if (amount >= coins[i]) { + res += helper(amount - coins[i], coins.slice(i), dp); + } + } + dp[coins.length][amount] = res; + return res; +}; +``` +**Explain:** + +1. sort `coins` array, to avoid duplicate answer +2. `f(5, [5,2,1]) = f(0, [5,2,1]) + f(3, [2,1]) + f(4, [1])` +3. `f(0, []) = 1` +4. cache every compute so that we only compute same case once + +**Complexity:** + +* Time complexity : O(n * m). +* Space complexity : O(n * m). diff --git a/501-600/525. Contiguous Array.md b/501-600/525. Contiguous Array.md new file mode 100644 index 0000000..ee920e0 --- /dev/null +++ b/501-600/525. Contiguous Array.md @@ -0,0 +1,70 @@ +# 525. Contiguous Array + +- Difficulty: Medium. +- Related Topics: Array, Hash Table, Prefix Sum. +- Similar Questions: Maximum Size Subarray Sum Equals k. + +## Problem + +Given a binary array `nums`, return **the maximum length of a contiguous subarray with an equal number of **`0`** and **`1`. + +  +Example 1: + +``` +Input: nums = [0,1] +Output: 2 +Explanation: [0, 1] is the longest contiguous subarray with an equal number of 0 and 1. +``` + +Example 2: + +``` +Input: nums = [0,1,0] +Output: 2 +Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1. +``` + +  +**Constraints:** + + + +- `1 <= nums.length <= 105` + +- `nums[i]` is either `0` or `1`. + + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @return {number} + */ +var findMaxLength = function(nums) { + var map = {}; + var count = 0; + var max = 0; + map[0] = -1; + for (var i = 0; i < nums.length; i++) { + count += (nums[i] === 1 ? 1 : -1); + if (map[count] !== undefined) { + max = Math.max(max, i - map[count]) + } else { + map[count] = i; + } + } + return max; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/501-600/543. Diameter of Binary Tree.md b/501-600/543. Diameter of Binary Tree.md new file mode 100644 index 0000000..1cb9c91 --- /dev/null +++ b/501-600/543. Diameter of Binary Tree.md @@ -0,0 +1,91 @@ +# 543. Diameter of Binary Tree + +- Difficulty: Easy. +- Related Topics: Tree, Depth-First Search, Binary Tree. +- Similar Questions: Diameter of N-Ary Tree, Longest Path With Different Adjacent Characters. + +## Problem + +Given the `root` of a binary tree, return **the length of the **diameter** of the tree**. + +The **diameter** of a binary tree is the **length** of the longest path between any two nodes in a tree. This path may or may not pass through the `root`. + +The **length** of a path between two nodes is represented by the number of edges between them. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2021/03/06/diamtree.jpg) + +``` +Input: root = [1,2,3,4,5] +Output: 3 +Explanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3]. +``` + +Example 2: + +``` +Input: root = [1,2] +Output: 1 +``` + +  +**Constraints:** + + + +- The number of nodes in the tree is in the range `[1, 104]`. + +- `-100 <= Node.val <= 100` + + + +## 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 + * @return {number} + */ +var diameterOfBinaryTree = function(root) { + return dfs(root)[0]; +}; + +var dfs = function(node) { + if (!node) return [0, 0]; + var left = dfs(node.left); + var right = dfs(node.right); + var child = Math.max( + node.left ? left[1] + 1 : 0, + node.right ? right[1] + 1 : 0, + ); + var branch = (node.left ? left[1] + 1 : 0) + + (node.right ? right[1] + 1 : 0); + return [ + Math.max( + left[0], + right[0], + branch, + ), + child, + ]; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/501-600/576. Out of Boundary Paths.md b/501-600/576. Out of Boundary Paths.md new file mode 100644 index 0000000..f642567 --- /dev/null +++ b/501-600/576. Out of Boundary Paths.md @@ -0,0 +1,93 @@ +# 576. Out of Boundary Paths + +- Difficulty: Medium. +- Related Topics: Dynamic Programming. +- Similar Questions: Knight Probability in Chessboard, Execution of All Suffix Instructions Staying in a Grid. + +## Problem + +There is an `m x n` grid with a ball. The ball is initially at the position `[startRow, startColumn]`. You are allowed to move the ball to one of the four adjacent cells in the grid (possibly out of the grid crossing the grid boundary). You can apply **at most** `maxMove` moves to the ball. + +Given the five integers `m`, `n`, `maxMove`, `startRow`, `startColumn`, return the number of paths to move the ball out of the grid boundary. Since the answer can be very large, return it **modulo** `109 + 7`. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2021/04/28/out_of_boundary_paths_1.png) + +``` +Input: m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0 +Output: 6 +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2021/04/28/out_of_boundary_paths_2.png) + +``` +Input: m = 1, n = 3, maxMove = 3, startRow = 0, startColumn = 1 +Output: 12 +``` + +  +**Constraints:** + + + +- `1 <= m, n <= 50` + +- `0 <= maxMove <= 50` + +- `0 <= startRow < m` + +- `0 <= startColumn < n` + + + +## Solution + +```javascript +/** + * @param {number} m + * @param {number} n + * @param {number} maxMove + * @param {number} startRow + * @param {number} startColumn + * @return {number} + */ +var findPaths = function(m, n, maxMove, startRow, startColumn) { + var matrix = Array(m).fill(0).map(() => Array(n).fill(0)); + matrix[startRow][startColumn] = 1; + var res = 0; + var mod = Math.pow(10, 9) + 7; + for (var k = 0; k < maxMove; k++) { + var newMatrix = Array(m).fill(0).map(() => Array(n).fill(0)); + for (var i = 0; i < m; i++) { + for (var j = 0; j < n; j++) { + newMatrix[i][j] = ( + (matrix[i - 1] ? matrix[i - 1][j] : 0) + + (matrix[i][j - 1] || 0) + + (matrix[i + 1] ? matrix[i + 1][j] : 0) + + (matrix[i][j + 1] || 0) + ) % mod; + if (i === 0) res += matrix[i][j]; + if (i === m - 1) res += matrix[i][j]; + if (j === 0) res += matrix[i][j]; + if (j === n - 1) res += matrix[i][j]; + res %= mod; + } + } + matrix = newMatrix; + } + return res; +}; +``` + +**Explain:** + +Dynamic programming. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/601-700/606. Construct String from Binary Tree.md b/601-700/606. Construct String from Binary Tree.md new file mode 100644 index 0000000..b1874fc --- /dev/null +++ b/601-700/606. Construct String from Binary Tree.md @@ -0,0 +1,76 @@ +# 606. Construct String from Binary Tree + +- Difficulty: Easy. +- Related Topics: String, Tree, Depth-First Search, Binary Tree. +- Similar Questions: Construct Binary Tree from String, Find Duplicate Subtrees. + +## Problem + +Given the `root` of a binary tree, construct a string consisting of parenthesis and integers from a binary tree with the preorder traversal way, and return it. + +Omit all the empty parenthesis pairs that do not affect the one-to-one mapping relationship between the string and the original binary tree. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2021/05/03/cons1-tree.jpg) + +``` +Input: root = [1,2,3,4] +Output: "1(2(4))(3)" +Explanation: Originally, it needs to be "1(2(4)())(3()())", but you need to omit all the unnecessary empty parenthesis pairs. And it will be "1(2(4))(3)" +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2021/05/03/cons2-tree.jpg) + +``` +Input: root = [1,2,3,null,4] +Output: "1(2()(4))(3)" +Explanation: Almost the same as the first example, except we cannot omit the first parenthesis pair to break the one-to-one mapping relationship between the input and the output. +``` + +  +**Constraints:** + + + +- The number of nodes in the tree is in the range `[1, 104]`. + +- `-1000 <= Node.val <= 1000` + + + +## 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 + * @return {string} + */ +var tree2str = function(root) { + if (!root) return ''; + var res = `${root.val}`; + if (root.left || root.right) res += `(${tree2str(root.left)})`; + if (root.right) res += `(${tree2str(root.right)})`; + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). 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/601-700/645. Set Mismatch.md b/601-700/645. Set Mismatch.md new file mode 100644 index 0000000..423ce9b --- /dev/null +++ b/601-700/645. Set Mismatch.md @@ -0,0 +1,69 @@ +# 645. Set Mismatch + +- Difficulty: Easy. +- Related Topics: Array, Hash Table, Bit Manipulation, Sorting. +- Similar Questions: Find the Duplicate Number. + +## Problem + +You have a set of integers `s`, which originally contains all the numbers from `1` to `n`. Unfortunately, due to some error, one of the numbers in `s` got duplicated to another number in the set, which results in **repetition of one** number and **loss of another** number. + +You are given an integer array `nums` representing the data status of this set after the error. + +Find the number that occurs twice and the number that is missing and return **them in the form of an array**. + +  +Example 1: +``` +Input: nums = [1,2,2,4] +Output: [2,3] +```Example 2: +``` +Input: nums = [1,1] +Output: [1,2] +``` +  +**Constraints:** + + + +- `2 <= nums.length <= 104` + +- `1 <= nums[i] <= 104` + + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @return {number[]} + */ +var findErrorNums = function(nums) { + var missing = 0; + var duplicated = 0; + for (var i = 0; i < nums.length; i++) { + if (nums[Math.abs(nums[i]) - 1] < 0) { + duplicated = Math.abs(nums[i]); + } else { + nums[Math.abs(nums[i]) - 1] *= -1; + } + } + for (var i = 0; i < nums.length; i++) { + if (nums[i] > 0) { + missing = i + 1; + } + } + return [duplicated, missing]; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/601-700/661. Image Smoother.md b/601-700/661. Image Smoother.md new file mode 100644 index 0000000..2382861 --- /dev/null +++ b/601-700/661. Image Smoother.md @@ -0,0 +1,116 @@ +# 661. Image Smoother + +- Difficulty: Easy. +- Related Topics: Array, Matrix. +- Similar Questions: . + +## Problem + +An **image smoother** is a filter of the size `3 x 3` that can be applied to each cell of an image by rounding down the average of the cell and the eight surrounding cells (i.e., the average of the nine cells in the blue smoother). If one or more of the surrounding cells of a cell is not present, we do not consider it in the average (i.e., the average of the four cells in the red smoother). + +![](https://assets.leetcode.com/uploads/2021/05/03/smoother-grid.jpg) + +Given an `m x n` integer matrix `img` representing the grayscale of an image, return **the image after applying the smoother on each cell of it**. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2021/05/03/smooth-grid.jpg) + +``` +Input: img = [[1,1,1],[1,0,1],[1,1,1]] +Output: [[0,0,0],[0,0,0],[0,0,0]] +Explanation: +For the points (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0 +For the points (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0 +For the point (1,1): floor(8/9) = floor(0.88888889) = 0 +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2021/05/03/smooth2-grid.jpg) + +``` +Input: img = [[100,200,100],[200,50,200],[100,200,100]] +Output: [[137,141,137],[141,138,141],[137,141,137]] +Explanation: +For the points (0,0), (0,2), (2,0), (2,2): floor((100+200+200+50)/4) = floor(137.5) = 137 +For the points (0,1), (1,0), (1,2), (2,1): floor((200+200+50+200+100+100)/6) = floor(141.666667) = 141 +For the point (1,1): floor((50+200+200+200+200+100+100+100+100)/9) = floor(138.888889) = 138 +``` + +  +**Constraints:** + + + +- `m == img.length` + +- `n == img[i].length` + +- `1 <= m, n <= 200` + +- `0 <= img[i][j] <= 255` + + + +## Solution + +```javascript +/** + * @param {number[][]} img + * @return {number[][]} + */ +var imageSmoother = function(img) { + var res = Array(img.length).fill(0).map(() => Array(img[0].length)); + for (var i = 0; i < img.length; i++) { + for (var j = 0; j < img[i].length; j++) { + var count = 1; + var num = img[i][j]; + if (img[i - 1]) { + if (img[i - 1][j - 1] !== undefined) { + count += 1; + num += img[i - 1][j - 1]; + } + count += 1; + num += img[i - 1][j]; + if (img[i - 1][j + 1] !== undefined) { + count += 1; + num += img[i - 1][j + 1]; + } + } + if (img[i][j - 1] !== undefined) { + count += 1; + num += img[i][j - 1]; + } + if (img[i][j + 1] !== undefined) { + count += 1; + num += img[i][j + 1]; + } + if (img[i + 1]) { + if (img[i + 1][j - 1] !== undefined) { + count += 1; + num += img[i + 1][j - 1]; + } + count += 1; + num += img[i + 1][j]; + if (img[i + 1][j + 1] !== undefined) { + count += 1; + num += img[i + 1][j + 1]; + } + } + res[i][j] = Math.floor(num / count); + } + } + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/701-800/725. Split Linked List in Parts.md b/701-800/725. Split Linked List in Parts.md new file mode 100644 index 0000000..adafa34 --- /dev/null +++ b/701-800/725. Split Linked List in Parts.md @@ -0,0 +1,119 @@ +# 725. Split Linked List in Parts + +- Difficulty: Medium. +- Related Topics: Linked List. +- Similar Questions: Rotate List, Odd Even Linked List, Split a Circular Linked List. + +## Problem + +Given the `head` of a singly linked list and an integer `k`, split the linked list into `k` consecutive linked list parts. + +The length of each part should be as equal as possible: no two parts should have a size differing by more than one. This may lead to some parts being null. + +The parts should be in the order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal to parts occurring later. + +Return **an array of the **`k`** parts**. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2021/06/13/split1-lc.jpg) + +``` +Input: head = [1,2,3], k = 5 +Output: [[1],[2],[3],[],[]] +Explanation: +The first element output[0] has output[0].val = 1, output[0].next = null. +The last element output[4] is null, but its string representation as a ListNode is []. +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2021/06/13/split2-lc.jpg) + +``` +Input: head = [1,2,3,4,5,6,7,8,9,10], k = 3 +Output: [[1,2,3,4],[5,6,7],[8,9,10]] +Explanation: +The input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts. +``` + +  +**Constraints:** + + + +- The number of nodes in the list is in the range `[0, 1000]`. + +- `0 <= Node.val <= 1000` + +- `1 <= k <= 50` + + + +## 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 + * @param {number} k + * @return {ListNode[]} + */ +var splitListToParts = function(head, k) { + var count = getListCount(head); + var maxCountPerPart = Math.ceil(count / k); + var res = []; + var node = head; + for (var i = 0; i < k; i++) { + var partCount = count > (maxCountPerPart - 1) * (k - i) + ? maxCountPerPart + : maxCountPerPart - 1; + var nextNode = sliceListPart(node, partCount); + res.push(node); + node = nextNode; + count -= partCount; + } + return res; +}; + +var getListCount = function(head) { + var count = 0; + var node = head; + while (node) { + count++; + node = node.next; + } + return count; +}; + +var sliceListPart = function(node, count) { + var n = 0; + while (n < count) { + n++; + if (n === count) { + var tmp = node.next; + node.next = null; + return tmp; + } else { + node = node.next; + } + } + return node; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/701-800/739. Daily Temperatures.md b/701-800/739. Daily Temperatures.md new file mode 100644 index 0000000..b26efe6 --- /dev/null +++ b/701-800/739. Daily Temperatures.md @@ -0,0 +1,64 @@ +# 739. Daily Temperatures + +- Difficulty: Medium. +- Related Topics: Array, Stack, Monotonic Stack. +- Similar Questions: Next Greater Element I, Online Stock Span. + +## Problem + +Given an array of integers `temperatures` represents the daily temperatures, return **an array** `answer` **such that** `answer[i]` **is the number of days you have to wait after the** `ith` **day to get a warmer temperature**. If there is no future day for which this is possible, keep `answer[i] == 0` instead. + +  +Example 1: +``` +Input: temperatures = [73,74,75,71,69,72,76,73] +Output: [1,1,4,2,1,1,0,0] +```Example 2: +``` +Input: temperatures = [30,40,50,60] +Output: [1,1,1,0] +```Example 3: +``` +Input: temperatures = [30,60,90] +Output: [1,1,0] +``` +  +**Constraints:** + + + +- `1 <= temperatures.length <= 105` + +- `30 <= temperatures[i] <= 100` + + + +## Solution + +```javascript +/** + * @param {number[]} temperatures + * @return {number[]} + */ +var dailyTemperatures = function(temperatures) { + var stack = []; + var res = Array(temperatures.length).fill(0); + for (var i = 0; i < temperatures.length; i++) { + while (stack.length && temperatures[i] > temperatures[stack[stack.length - 1]]) { + var index = stack.pop(); + res[index] = i - index; + } + stack.push(i); + } + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* 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/701-800/787. Cheapest Flights Within K Stops.md b/701-800/787. Cheapest Flights Within K Stops.md new file mode 100644 index 0000000..43e2e9c --- /dev/null +++ b/701-800/787. Cheapest Flights Within K Stops.md @@ -0,0 +1,121 @@ +# 787. Cheapest Flights Within K Stops + +- Difficulty: Medium. +- Related Topics: Dynamic Programming, Depth-First Search, Breadth-First Search, Graph, Heap (Priority Queue), Shortest Path. +- Similar Questions: Maximum Vacation Days, Minimum Cost to Reach City With Discounts. + +## Problem + +There are `n` cities connected by some number of flights. You are given an array `flights` where `flights[i] = [fromi, toi, pricei]` indicates that there is a flight from city `fromi` to city `toi` with cost `pricei`. + +You are also given three integers `src`, `dst`, and `k`, return ****the cheapest price** from **`src`** to **`dst`** with at most **`k`** stops. **If there is no such route, return** **`-1`. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2022/03/18/cheapest-flights-within-k-stops-3drawio.png) + +``` +Input: n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1 +Output: 700 +Explanation: +The graph is shown above. +The optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700. +Note that the path through cities [0,1,2,3] is cheaper but is invalid because it uses 2 stops. +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2022/03/18/cheapest-flights-within-k-stops-1drawio.png) + +``` +Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1 +Output: 200 +Explanation: +The graph is shown above. +The optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200. +``` + +Example 3: + +![](https://assets.leetcode.com/uploads/2022/03/18/cheapest-flights-within-k-stops-2drawio.png) + +``` +Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0 +Output: 500 +Explanation: +The graph is shown above. +The optimal path with no stops from city 0 to 2 is marked in red and has cost 500. +``` + +  +**Constraints:** + + + +- `1 <= n <= 100` + +- `0 <= flights.length <= (n * (n - 1) / 2)` + +- `flights[i].length == 3` + +- `0 <= fromi, toi < n` + +- `fromi != toi` + +- `1 <= pricei <= 104` + +- There will not be any multiple flights between two cities. + +- `0 <= src, dst, k < n` + +- `src != dst` + + + +## Solution + +```javascript +/** + * @param {number} n + * @param {number[][]} flights + * @param {number} src + * @param {number} dst + * @param {number} k + * @return {number} + */ +var findCheapestPrice = function(n, flights, src, dst, k) { + var map = Array(n).fill(0).map(() => []); + for (var i = 0; i < flights.length; i++) { + map[flights[i][0]].push([flights[i][1], flights[i][2]]); + } + var dp = Array(n).fill(0).map(() => ({})); + var res = dfs(src, dst, k, map, dp); + return res; +}; + +var dfs = function(src, dst, k, map, dp) { + if (dp[src][k] !== undefined) return dp[src][k]; + if (src === dst) return 0; + if (k === -1) return -1; + var res = -1; + for (var i = 0; i < map[src].length; i++) { + var tmp = dfs(map[src][i][0], dst, k - 1, map, dp); + if (tmp === -1) continue; + if (res === -1 || res > tmp + map[src][i][1]) { + res = tmp + map[src][i][1]; + } + } + dp[src][k] = res; + return res; +}; +``` + +**Explain:** + +DFS + DP. + +**Complexity:** + +* Time complexity : O(n * k). +* Space complexity : O(n * k). diff --git a/801-900/872. Leaf-Similar Trees.md b/801-900/872. Leaf-Similar Trees.md new file mode 100644 index 0000000..e854bd1 --- /dev/null +++ b/801-900/872. Leaf-Similar Trees.md @@ -0,0 +1,90 @@ +# 872. Leaf-Similar Trees + +- Difficulty: Easy. +- Related Topics: Tree, Depth-First Search, Binary Tree. +- Similar Questions: . + +## Problem + +Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a **leaf value sequence****.** + + +![](https://s3-lc-upload.s3.amazonaws.com/uploads/2018/07/16/tree.png) + + +For example, in the given tree above, the leaf value sequence is `(6, 7, 4, 9, 8)`. + +Two binary trees are considered **leaf-similar** if their leaf value sequence is the same. + +Return `true` if and only if the two given trees with head nodes `root1` and `root2` are leaf-similar. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2020/09/03/leaf-similar-1.jpg) + +``` +Input: root1 = [3,5,1,6,2,9,8,null,null,7,4], root2 = [3,5,1,6,7,4,2,null,null,null,null,null,null,9,8] +Output: true +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2020/09/03/leaf-similar-2.jpg) + +``` +Input: root1 = [1,2,3], root2 = [1,3,2] +Output: false +``` + +  +**Constraints:** + + + +- The number of nodes in each tree will be in the range `[1, 200]`. + +- Both of the given trees will have values in the range `[0, 200]`. + + + +## 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} root1 + * @param {TreeNode} root2 + * @return {boolean} + */ +var leafSimilar = function(root1, root2) { + var arr1 = []; + var arr2 = []; + getLeafNodes(root1, arr1); + getLeafNodes(root2, arr2); + return arr1.length === arr2.length + && arr1.every((item, index) => item === arr2[index]); +}; + +var getLeafNodes = function(root, result) { + if (!root.left && !root.right) result.push(root.val); + root.left && getLeafNodes(root.left, result); + root.right && getLeafNodes(root.right, result); +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/801-900/875. Koko Eating Bananas.md b/801-900/875. Koko Eating Bananas.md new file mode 100644 index 0000000..e464df4 --- /dev/null +++ b/801-900/875. Koko Eating Bananas.md @@ -0,0 +1,91 @@ +# 875. Koko Eating Bananas + +- Difficulty: Medium. +- Related Topics: Array, Binary Search. +- Similar Questions: Minimize Max Distance to Gas Station, Maximum Candies Allocated to K Children, Minimized Maximum of Products Distributed to Any Store, Frog Jump II, Minimum Time to Repair Cars. + +## Problem + +Koko loves to eat bananas. There are `n` piles of bananas, the `ith` pile has `piles[i]` bananas. The guards have gone and will come back in `h` hours. + +Koko can decide her bananas-per-hour eating speed of `k`. Each hour, she chooses some pile of bananas and eats `k` bananas from that pile. If the pile has less than `k` bananas, she eats all of them instead and will not eat any more bananas during this hour. + +Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return. + +Return **the minimum integer** `k` **such that she can eat all the bananas within** `h` **hours**. + +  +Example 1: + +``` +Input: piles = [3,6,7,11], h = 8 +Output: 4 +``` + +Example 2: + +``` +Input: piles = [30,11,23,4,20], h = 5 +Output: 30 +``` + +Example 3: + +``` +Input: piles = [30,11,23,4,20], h = 6 +Output: 23 +``` + +  +**Constraints:** + + + +- `1 <= piles.length <= 104` + +- `piles.length <= h <= 109` + +- `1 <= piles[i] <= 109` + + + +## Solution + +```javascript +/** + * @param {number[]} piles + * @param {number} h + * @return {number} + */ +var minEatingSpeed = function(piles, h) { + var left = 1; + var right = Math.max(...piles); + while (left < right) { + var mid = left + Math.floor((right - left) / 2); + var hours = getHours(piles, mid); + if (hours > h) { + left = mid + 1; + } else { + right = mid; + } + } + return left; +}; + +var getHours = function(piles, num) { + var hours = 0; + for (var i = 0; i < piles.length; i++) { + hours += Math.ceil(piles[i] / num); + } + return hours; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * log(n)). +* Space complexity : O(1). 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/907. Sum of Subarray Minimums.md b/901-1000/907. Sum of Subarray Minimums.md new file mode 100644 index 0000000..05b6570 --- /dev/null +++ b/901-1000/907. Sum of Subarray Minimums.md @@ -0,0 +1,84 @@ +# 907. Sum of Subarray Minimums + +- Difficulty: Medium. +- Related Topics: Array, Dynamic Programming, Stack, Monotonic Stack. +- Similar Questions: Sum of Subarray Ranges, Sum of Total Strength of Wizards. + +## Problem + +Given an array of integers arr, find the sum of `min(b)`, where `b` ranges over every (contiguous) subarray of `arr`. Since the answer may be large, return the answer **modulo** `109 + 7`. + +  +Example 1: + +``` +Input: arr = [3,1,2,4] +Output: 17 +Explanation: +Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4]. +Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1. +Sum is 17. +``` + +Example 2: + +``` +Input: arr = [11,81,94,43,3] +Output: 444 +``` + +  +**Constraints:** + + + +- `1 <= arr.length <= 3 * 104` + +- `1 <= arr[i] <= 3 * 104` + + + +## Solution + +```javascript +/** + * @param {number[]} arr + * @return {number} + */ +var sumSubarrayMins = function(arr) { + var stack = []; + var rightBiggerNums = Array(arr.length).fill(1); + for (var i = 0; i <= arr.length; i++) { + while (stack.length && (i === arr.length || arr[i] < arr[stack[stack.length - 1]])) { + var index = stack.pop(); + rightBiggerNums[index] = i - index; + } + stack.push(i); + } + stack = []; + var leftBiggerNums = Array(arr.length).fill(1); + for (var i = arr.length - 1; i >= -1; i--) { + while (stack.length && (i === -1 || arr[i] <= arr[stack[stack.length - 1]])) { + var index = stack.pop(); + leftBiggerNums[index] = index - i; + } + stack.push(i); + } + var sum = 0; + var mod = Math.pow(10, 9) + 7; + for (var i = 0; i < arr.length; i++) { + sum += rightBiggerNums[i] * leftBiggerNums[i] * arr[i]; + sum %= mod; + } + return sum; +}; +``` + +**Explain:** + +Monotonic stack, be careful about duplicate nums. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/901-1000/931. Minimum Falling Path Sum.md b/901-1000/931. Minimum Falling Path Sum.md new file mode 100644 index 0000000..f5477b4 --- /dev/null +++ b/901-1000/931. Minimum Falling Path Sum.md @@ -0,0 +1,75 @@ +# 931. Minimum Falling Path Sum + +- Difficulty: Medium. +- Related Topics: Array, Dynamic Programming, Matrix. +- Similar Questions: Minimum Falling Path Sum II. + +## Problem + +Given an `n x n` array of integers `matrix`, return **the **minimum sum** of any **falling path** through** `matrix`. + +A **falling path** starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position `(row, col)` will be `(row + 1, col - 1)`, `(row + 1, col)`, or `(row + 1, col + 1)`. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2021/11/03/failing1-grid.jpg) + +``` +Input: matrix = [[2,1,3],[6,5,4],[7,8,9]] +Output: 13 +Explanation: There are two falling paths with a minimum sum as shown. +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2021/11/03/failing2-grid.jpg) + +``` +Input: matrix = [[-19,57],[-40,-5]] +Output: -59 +Explanation: The falling path with a minimum sum is shown. +``` + +  +**Constraints:** + + + +- `n == matrix.length == matrix[i].length` + +- `1 <= n <= 100` + +- `-100 <= matrix[i][j] <= 100` + + + +## Solution + +```javascript +/** + * @param {number[][]} matrix + * @return {number} + */ +var minFallingPathSum = function(matrix) { + for (var i = 1; i < matrix.length; i++) { + for (var j = 0; j < matrix[i].length; j++) { + matrix[i][j] += Math.min( + j === 0 ? Number.MAX_SAFE_INTEGER : matrix[i - 1][j - 1], + matrix[i - 1][j], + j === matrix[i - 1].length - 1 ? Number.MAX_SAFE_INTEGER : matrix[i - 1][j + 1], + ); + } + } + return Math.min(...matrix[matrix.length - 1]); +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * m). +* Space complexity : O(n). diff --git a/901-1000/938. Range Sum of BST.md b/901-1000/938. Range Sum of BST.md new file mode 100644 index 0000000..a92ebaa --- /dev/null +++ b/901-1000/938. Range Sum of BST.md @@ -0,0 +1,85 @@ +# 938. Range Sum of BST + +- Difficulty: Easy. +- Related Topics: Tree, Depth-First Search, Binary Search Tree, Binary Tree. +- Similar Questions: . + +## Problem + +Given the `root` node of a binary search tree and two integers `low` and `high`, return **the sum of values of all nodes with a value in the **inclusive** range **`[low, high]`. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2020/11/05/bst1.jpg) + +``` +Input: root = [10,5,15,3,7,null,18], low = 7, high = 15 +Output: 32 +Explanation: Nodes 7, 10, and 15 are in the range [7, 15]. 7 + 10 + 15 = 32. +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2020/11/05/bst2.jpg) + +``` +Input: root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10 +Output: 23 +Explanation: Nodes 6, 7, and 10 are in the range [6, 10]. 6 + 7 + 10 = 23. +``` + +  +**Constraints:** + + + +- The number of nodes in the tree is in the range `[1, 2 * 104]`. + +- `1 <= Node.val <= 105` + +- `1 <= low <= high <= 105` + +- All `Node.val` are **unique**. + + + +## 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} low + * @param {number} high + * @return {number} + */ +var rangeSumBST = function(root, low, high) { + if (!root) return 0; + if (root.val >= low && root.val <= high) { + return root.val + + rangeSumBST(root.left, low, high) + + rangeSumBST(root.right, low, high); + } else if (root.val < low) { + return rangeSumBST(root.right, low, high); + } else { + return rangeSumBST(root.left, low, high); + } +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/901-1000/948. Bag of Tokens.md b/901-1000/948. Bag of Tokens.md new file mode 100644 index 0000000..a0c2386 --- /dev/null +++ b/901-1000/948. Bag of Tokens.md @@ -0,0 +1,116 @@ +# 948. Bag of Tokens + +- Difficulty: Medium. +- Related Topics: Array, Two Pointers, Greedy, Sorting. +- Similar Questions: . + +## Problem + +You start with an initial **power** of `power`, an initial **score** of `0`, and a bag of tokens given as an integer array `tokens`, where each `tokens[i]` donates the value of token**i**. + +Your goal is to **maximize** the total **score** by strategically playing these tokens. In one move, you can play an **unplayed** token in one of the two ways (but not both for the same token): + + + +- **Face-up**: If your current power is **at least** `tokens[i]`, you may play token**i**, losing `tokens[i]` power and gaining `1` score. + +- **Face-down**: If your current score is **at least** `1`, you may play token**i**, gaining `tokens[i]` power and losing `1` score. + + +Return **the **maximum** possible score you can achieve after playing **any** number of tokens**. + +  +Example 1: + + +**Input:** tokens = [100], power = 50 + +**Output:** 0 + +**Explanation****:** Since your score is `0` initially, you cannot play the token face-down. You also cannot play it face-up since your power (`50`) is less than `tokens[0]` (`100`). + + +Example 2: + + +**Input:** tokens = [200,100], power = 150 + +**Output:** 1 + +**Explanation:** Play token**1** (`100`) face-up, reducing your power to `50` and increasing your score to `1`. + +There is no need to play token**0**, since you cannot play it face-up to add to your score. The maximum score achievable is `1`. + + +Example 3: + + +**Input:** tokens = [100,200,300,400], power = 200 + +**Output:** 2 + +**Explanation:** Play the tokens in this order to get a score of `2`: + + + +- Play token**0** (`100`) face-up, reducing power to `100` and increasing score to `1`. + +- Play token**3** (`400`) face-down, increasing power to `500` and reducing score to `0`. + +- Play token**1** (`200`) face-up, reducing power to `300` and increasing score to `1`. + +- Play token**2** (`300`) face-up, reducing power to `0` and increasing score to `2`. + + +The maximum score achievable is 2. + + +  +**Constraints:** + + + +- `0 <= tokens.length <= 1000` + +- `0 <= tokens[i], power < 104` + + + +## Solution + +```javascript +/** + * @param {number[]} tokens + * @param {number} power + * @return {number} + */ +var bagOfTokensScore = function(tokens, power) { + tokens.sort((a, b) => a - b); + var left = 0; + var right = tokens.length - 1; + var maxScore = 0; + var score = 0; + while (left <= right) { + if (power >= tokens[left]) { + power -= tokens[left++]; + score += 1; + maxScore = Math.max(maxScore, score); + } else if (score > 0) { + score -= 1; + power += tokens[right--]; + } else { + break; + } + } + return maxScore; +}; +``` + +**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/901-1000/980. Unique Paths III.md b/901-1000/980. Unique Paths III.md new file mode 100644 index 0000000..b93b95b --- /dev/null +++ b/901-1000/980. Unique Paths III.md @@ -0,0 +1,131 @@ +# 980. Unique Paths III + +- Difficulty: Hard. +- Related Topics: Array, Backtracking, Bit Manipulation, Matrix. +- Similar Questions: Sudoku Solver, Unique Paths II, Word Search II. + +## Problem + +You are given an `m x n` integer array `grid` where `grid[i][j]` could be: + + + +- `1` representing the starting square. There is exactly one starting square. + +- `2` representing the ending square. There is exactly one ending square. + +- `0` representing empty squares we can walk over. + +- `-1` representing obstacles that we cannot walk over. + + +Return **the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once**. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2021/08/02/lc-unique1.jpg) + +``` +Input: grid = [[1,0,0,0],[0,0,0,0],[0,0,2,-1]] +Output: 2 +Explanation: We have the following two paths: +1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2) +2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2) +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2021/08/02/lc-unique2.jpg) + +``` +Input: grid = [[1,0,0,0],[0,0,0,0],[0,0,0,2]] +Output: 4 +Explanation: We have the following four paths: +1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3) +2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3) +3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3) +4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3) +``` + +Example 3: + +![](https://assets.leetcode.com/uploads/2021/08/02/lc-unique3-.jpg) + +``` +Input: grid = [[0,1],[2,0]] +Output: 0 +Explanation: There is no path that walks over every empty square exactly once. +Note that the starting and ending square can be anywhere in the grid. +``` + +  +**Constraints:** + + + +- `m == grid.length` + +- `n == grid[i].length` + +- `1 <= m, n <= 20` + +- `1 <= m * n <= 20` + +- `-1 <= grid[i][j] <= 2` + +- There is exactly one starting cell and one ending cell. + + + +## Solution + +```javascript +/** + * @param {number[][]} grid + * @return {number} + */ +var uniquePathsIII = function(grid) { + var start; + var m = grid.length; + var n = grid[0].length; + var emptyNum = 0; + for (var i = 0; i < m; i++) { + for (var j = 0; j < n; j++) { + if (grid[i][j] === 1) start = [i, j]; + else if (grid[i][j] === 0) emptyNum++; + } + } + return getPathNum(start[0], start[1], grid, 0, emptyNum); +}; + +var getPathNum = function(i, j, grid, visitedNum, emptyNum) { + var res = 0; + var directions = [ + [1, 0], // up + [-1, 0], // down + [0, -1], // left + [0, 1], // right + ]; + for (var k = 0; k < 4; k++) { + var [diffX, diffY] = directions[k]; + if (grid[i + diffX] && grid[i + diffX][j + diffY] === 0) { + grid[i + diffX][j + diffY] = -1; + res += getPathNum(i + diffX, j + diffY, grid, visitedNum + 1, emptyNum); + grid[i + diffX][j + diffY] = 0; + } else if (grid[i + diffX] && grid[i + diffX][j + diffY] === 2) { + res += (visitedNum === emptyNum ? 1 : 0); + } + } + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n!). +* Space complexity : O(1). diff --git a/901-1000/984. String Without AAA or BBB.md b/901-1000/984. String Without AAA or BBB.md new file mode 100644 index 0000000..bb819ee --- /dev/null +++ b/901-1000/984. String Without AAA or BBB.md @@ -0,0 +1,81 @@ +# 984. String Without AAA or BBB + +- Difficulty: Medium. +- Related Topics: String, Greedy. +- Similar Questions: . + +## Problem + +Given two integers `a` and `b`, return **any** string `s` such that: + + + +- `s` has length `a + b` and contains exactly `a` `'a'` letters, and exactly `b` `'b'` letters, + +- The substring `'aaa'` does not occur in `s`, and + +- The substring `'bbb'` does not occur in `s`. + + +  +Example 1: + +``` +Input: a = 1, b = 2 +Output: "abb" +Explanation: "abb", "bab" and "bba" are all correct answers. +``` + +Example 2: + +``` +Input: a = 4, b = 1 +Output: "aabaa" +``` + +  +**Constraints:** + + + +- `0 <= a, b <= 100` + +- It is guaranteed such an `s` exists for the given `a` and `b`. + + + +## Solution + +```javascript +/** + * @param {number} a + * @param {number} b + * @return {string} + */ +var strWithout3a3b = function(a, b, isRevert) { + if (b > a) return strWithout3a3b(b, a, true); + var res = ''; + while (a > 0 || b > 0) { + if (a > 0) { + var num = a > 2 ? 2 : 1; + res += (isRevert ? 'b' : 'a').repeat(num); + a -= num; + } + if (b > 0) { + var num = b > Math.ceil(a / 2) && b >= 2 ? 2 : 1; + res += (isRevert ? 'a' : 'b').repeat(num); + b -= num; + } + } + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/901-1000/997. Find the Town Judge.md b/901-1000/997. Find the Town Judge.md new file mode 100644 index 0000000..00257b9 --- /dev/null +++ b/901-1000/997. Find the Town Judge.md @@ -0,0 +1,95 @@ +# 997. Find the Town Judge + +- Difficulty: Easy. +- Related Topics: Array, Hash Table, Graph. +- Similar Questions: Find the Celebrity. + +## Problem + +In a town, there are `n` people labeled from `1` to `n`. There is a rumor that one of these people is secretly the town judge. + +If the town judge exists, then: + + + +- The town judge trusts nobody. + +- Everybody (except for the town judge) trusts the town judge. + +- There is exactly one person that satisfies properties **1** and **2**. + + +You are given an array `trust` where `trust[i] = [ai, bi]` representing that the person labeled `ai` trusts the person labeled `bi`. If a trust relationship does not exist in `trust` array, then such a trust relationship does not exist. + +Return **the label of the town judge if the town judge exists and can be identified, or return **`-1`** otherwise**. + +  +Example 1: + +``` +Input: n = 2, trust = [[1,2]] +Output: 2 +``` + +Example 2: + +``` +Input: n = 3, trust = [[1,3],[2,3]] +Output: 3 +``` + +Example 3: + +``` +Input: n = 3, trust = [[1,3],[2,3],[3,1]] +Output: -1 +``` + +  +**Constraints:** + + + +- `1 <= n <= 1000` + +- `0 <= trust.length <= 104` + +- `trust[i].length == 2` + +- All the pairs of `trust` are **unique**. + +- `ai != bi` + +- `1 <= ai, bi <= n` + + + +## Solution + +```javascript +/** + * @param {number} n + * @param {number[][]} trust + * @return {number} + */ +var findJudge = function(n, trust) { + var map = Array(n + 1).fill(0).map(() => [0, 0]); + for (var i = 0; i < trust.length; i++) { + map[trust[i][0]][0] += 1; + map[trust[i][1]][1] += 1; + } + for (var j = 1; j <= n; j++) { + if (map[j][0] === 0 && map[j][1] === n - 1) return j; + } + return -1; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/create/index.js b/create/index.js index 708c901..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`); @@ -95,6 +95,10 @@ const queryAndCreate = name => { const url = `https://leetcode.com/graphql?query=query%20getQuestionDetail($titleSlug:%20String!)%20%7B%0A%20%20question(titleSlug:%20$titleSlug)%20%7B%0A%20%20%20%20questionId%0A%20%20%20%20questionFrontendId%0A%20%20%20%20questionTitle%0A%20%20%20%20content%0A%20%20%20%20difficulty%0A%20%20%20%20stats%0A%20%20%20%20similarQuestions%0A%20%20%20%20topicTags%20%7B%0A%20%20%20%20%20%20name%0A%20%20%20%20%7D%0A%20%20%7D%0A%7D%0A&operationName=getQuestionDetail&variables=%7B%22titleSlug%22:%22${name}%22%7D`; axios.get(url).then(res => { + if (!res.data?.data?.question) { + console.error('fetch question info error, probably wrong problem url\n'); + return; + } create(res.data.data.question); }).catch(err => { console.error(err);