diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml new file mode 100644 index 0000000..0788b47 --- /dev/null +++ b/.github/workflows/docs.yml @@ -0,0 +1,77 @@ +name: Deploy to Pages + +on: + # Runs on pushes targeting the default branch + push: + branches: ["master"] + + # Allows you to run this workflow manually from the Actions tab + workflow_dispatch: + +# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages +permissions: + contents: read + pages: write + id-token: write + +# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued. +# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete. +concurrency: + group: "pages" + cancel-in-progress: false + +# Default to bash +defaults: + run: + shell: bash + +jobs: + # Build job + build: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v3 + - name: Detect package manager + id: detect-package-manager + run: | + if [ -f "${{ github.workspace }}/yarn.lock" ]; then + echo "manager=yarn" >> $GITHUB_OUTPUT + echo "command=install" >> $GITHUB_OUTPUT + exit 0 + elif [ -f "${{ github.workspace }}/package.json" ]; then + echo "manager=npm" >> $GITHUB_OUTPUT + echo "command=ci" >> $GITHUB_OUTPUT + exit 0 + else + echo "Unable to determine package manager" + exit 1 + fi + - name: Setup Node + uses: actions/setup-node@v3 + with: + node-version: "18" + cache: ${{ steps.detect-package-manager.outputs.manager }} + - name: Setup Pages + id: pages + uses: actions/configure-pages@v3 + - name: Install dependencies + run: ${{ steps.detect-package-manager.outputs.manager }} ${{ steps.detect-package-manager.outputs.command }} + - name: Build + run: ${{ steps.detect-package-manager.outputs.manager }} run build + - name: Upload artifact + uses: actions/upload-pages-artifact@v1 + with: + path: ./docs + + # Deployment job + deploy: + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + runs-on: ubuntu-latest + needs: build + steps: + - name: Deploy to GitHub Pages + id: deployment + uses: actions/deploy-pages@v2 diff --git a/.gitignore b/.gitignore index 20de930..1088cdb 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ node_modules/ .vscode/ +docs/ diff --git a/001-100/34. Find First and Last Position of Element in Sorted Array.md b/001-100/34. Find First and Last Position of Element in Sorted Array.md new file mode 100644 index 0000000..42d1bd9 --- /dev/null +++ b/001-100/34. Find First and Last Position of Element in Sorted Array.md @@ -0,0 +1,111 @@ +# 34. Find First and Last Position of Element in Sorted Array + +- Difficulty: Medium. +- Related Topics: Array, Binary Search. +- Similar Questions: First Bad Version, Plates Between Candles, Find Target Indices After Sorting Array. + +## Problem + +Given an array of integers `nums` sorted in non-decreasing order, find the starting and ending position of a given `target` value. + +If `target` is not found in the array, return `[-1, -1]`. + +You must write an algorithm with `O(log n)` runtime complexity. + +  +Example 1: +``` +Input: nums = [5,7,7,8,8,10], target = 8 +Output: [3,4] +```Example 2: +``` +Input: nums = [5,7,7,8,8,10], target = 6 +Output: [-1,-1] +```Example 3: +``` +Input: nums = [], target = 0 +Output: [-1,-1] +``` +  +**Constraints:** + + + +- `0 <= nums.length <= 105` + +- `-109 <= nums[i] <= 109` + +- `nums` is a non-decreasing array. + +- `-109 <= target <= 109` + + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @param {number} target + * @return {number[]} + */ +var searchRange = function(nums, target) { + var index = findIndex(nums, target); + return index === -1 + ? [-1, -1] + : [findLeft(nums, target, index), findRight(nums, target, index)]; +}; + +var findIndex = function(nums, target) { + var left = 0; + var right = nums.length - 1; + while (left <= right) { + var mid = left + Math.floor((right - left) / 2); + if (nums[mid] === target) { + return mid; + } else if (nums[mid] > target) { + right = mid - 1; + } else { + left = mid + 1; + } + } + return -1; +}; + +var findLeft = function(nums, target, index) { + var left = 0; + var right = index; + while (left < right) { + var mid = left + Math.floor((right - left) / 2); + if (nums[mid] === target) { + right = mid; + } else { + left = mid + 1; + } + } + return left; +}; + +var findRight = function(nums, target, index) { + var left = index; + var right = nums.length - 1; + while (left < right) { + var mid = left + Math.ceil((right - left) / 2); + if (nums[mid] === target) { + left = mid; + } else { + right = mid - 1; + } + } + return right; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(log(n)). +* Space complexity : O(1). diff --git a/001-100/5. Longest Palindromic Substring.md b/001-100/5. Longest Palindromic Substring.md index 621c252..ce66690 100644 --- a/001-100/5. Longest Palindromic Substring.md +++ b/001-100/5. Longest Palindromic Substring.md @@ -65,3 +65,38 @@ var expandAroundCenter = function (s, left, right) { * Time complexity : O(n^2). * Space complexity : O(1). + + +```js +/** + * @param {string} s + * @return {string} + */ +var longestPalindrome = function(s) { + let startIndex = 0; + let maxLength = 1; + + function expandAroundCenter(left, right) { + while (left >=0 && right < s.length && s[left] === s[right]) { + const currentPalLength = right - left + 1; + if (currentPalLength > maxLength) { + maxLength = currentPalLength; + startIndex = left; + } + left -= 1; + right += 1; + } + } + + for (let i = 0; i < s.length; i++) { + expandAroundCenter(i-1, i+1); + expandAroundCenter(i, i+1); + } + + return s.slice(startIndex, startIndex + maxLength) +}; +``` +**Complexity:** + +* Time complexity : O(n^2). +* Space complexity : O(1). 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/1026. Maximum Difference Between Node and Ancestor.md b/1001-1100/1026. Maximum Difference Between Node and Ancestor.md new file mode 100644 index 0000000..abfb87b --- /dev/null +++ b/1001-1100/1026. Maximum Difference Between Node and Ancestor.md @@ -0,0 +1,88 @@ +# 1026. Maximum Difference Between Node and Ancestor + +- Difficulty: Medium. +- Related Topics: Tree, Depth-First Search, Binary Tree. +- Similar Questions: . + +## Problem + +Given the ```root``` of a binary tree, find the maximum value ```v``` for which there exist **different** nodes ```a``` and ```b``` where ```v = |a.val - b.val|``` and ```a``` is an ancestor of ```b```. + +A node ```a``` is an ancestor of ```b``` if either: any child of ```a``` is equal to ```b``` or any child of ```a``` is an ancestor of ```b```. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2020/11/09/tmp-tree.jpg) + +``` +Input: root = [8,3,10,1,6,null,14,null,null,4,7,13] +Output: 7 +Explanation: We have various ancestor-node differences, some of which are given below : +|8 - 3| = 5 +|3 - 7| = 4 +|8 - 1| = 7 +|10 - 13| = 3 +Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7. +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2020/11/09/tmp-tree-1.jpg) + +``` +Input: root = [1,null,2,null,0,3] +Output: 3 +``` + +  +**Constraints:** + + + +- The number of nodes in the tree is in the range ```[2, 5000]```. + +- ```0 <= Node.val <= 105``` + + + +## 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 maxAncestorDiff = function(root) { + return helper(root.val, root.val, root); +}; + +var helper = function(max, min, node) { + if (!node) return 0; + var newMax = node.val > max ? node.val : max; + var newMin = node.val < min ? node.val : min; + return Math.max( + Math.abs(max - node.val), + Math.abs(min - node.val), + node.left ? helper(newMax, newMin, node.left) : 0, + node.right ? helper(newMax, newMin, node.right) : 0, + ); +}; +``` + +**Explain:** + +use dfs to visit every node in the tree, carry the maximum and minimum number all the way down, the result should be |max - node.val| or |min - node.val| + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/1001-1100/1037. Valid Boomerang.md b/1001-1100/1037. Valid Boomerang.md new file mode 100644 index 0000000..8cfe58c --- /dev/null +++ b/1001-1100/1037. Valid Boomerang.md @@ -0,0 +1,59 @@ +# 1037. Valid Boomerang + +- Difficulty: Easy. +- Related Topics: Array, Math, Geometry. +- Similar Questions: . + +## Problem + +Given an array `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane, return `true` **if these points are a **boomerang****. + +A **boomerang** is a set of three points that are **all distinct** and **not in a straight line**. + +  +Example 1: +``` +Input: points = [[1,1],[2,3],[3,2]] +Output: true +```Example 2: +``` +Input: points = [[1,1],[2,2],[3,3]] +Output: false +``` +  +**Constraints:** + + + +- `points.length == 3` + +- `points[i].length == 2` + +- `0 <= xi, yi <= 100` + + + +## Solution + +```javascript +/** + * @param {number[][]} points + * @return {boolean} + */ +var isBoomerang = function(points) { + var a = points[0][0] - points[1][0]; + var b = points[0][1] - points[1][1]; + var c = points[0][0] - points[2][0]; + var d = points[0][1] - points[2][1]; + return a * d !== b * c; +}; +``` + +**Explain:** + +Math + +**Complexity:** + +* Time complexity : O(1). +* Space complexity : O(1). diff --git a/1001-1100/1042. Flower Planting With No Adjacent.md b/1001-1100/1042. Flower Planting With No Adjacent.md new file mode 100644 index 0000000..43f85f5 --- /dev/null +++ b/1001-1100/1042. Flower Planting With No Adjacent.md @@ -0,0 +1,104 @@ +# 1042. Flower Planting With No Adjacent + +- Difficulty: Medium. +- Related Topics: Depth-First Search, Breadth-First Search, Graph. +- Similar Questions: . + +## Problem + +You have ```n``` gardens, labeled from ```1``` to ```n```, and an array ```paths``` where ```paths[i] = [xi, yi]``` describes a bidirectional path between garden ```xi``` to garden ```yi```. In each garden, you want to plant one of 4 types of flowers. + +All gardens have **at most 3** paths coming into or leaving it. + +Your task is to choose a flower type for each garden such that, for any two gardens connected by a path, they have different types of flowers. + +Return ****any** such a choice as an array **```answer```**, where **```answer[i]```** is the type of flower planted in the **```(i+1)th```** garden. The flower types are denoted **```1```**, **```2```**, **```3```**, or **```4```**. It is guaranteed an answer exists.** + +  +Example 1: + +``` +Input: n = 3, paths = [[1,2],[2,3],[3,1]] +Output: [1,2,3] +Explanation: +Gardens 1 and 2 have different types. +Gardens 2 and 3 have different types. +Gardens 3 and 1 have different types. +Hence, [1,2,3] is a valid answer. Other valid answers include [1,2,4], [1,4,2], and [3,2,1]. +``` + +Example 2: + +``` +Input: n = 4, paths = [[1,2],[3,4]] +Output: [1,2,1,2] +``` + +Example 3: + +``` +Input: n = 4, paths = [[1,2],[2,3],[3,4],[4,1],[1,3],[2,4]] +Output: [1,2,3,4] +``` + +  +**Constraints:** + + + +- ```1 <= n <= 104``` + +- ```0 <= paths.length <= 2 * 104``` + +- ```paths[i].length == 2``` + +- ```1 <= xi, yi <= n``` + +- ```xi != yi``` + +- Every garden has **at most 3** paths coming into or leaving it. + + + +## Solution + +```javascript +/** + * @param {number} n + * @param {number[][]} paths + * @return {number[]} + */ +var gardenNoAdj = function(n, paths) { + var pathMap = Array(n).fill(0).map(() => ({})); + for (var i = 0; i < paths.length; i++) { + pathMap[paths[i][0] - 1][paths[i][1] - 1] = true; + pathMap[paths[i][1] - 1][paths[i][0] - 1] = true; + } + var possibleMap = Array(n).fill(0).map(() => [1,1,1,1]); + var result = Array(n).fill(0); + for (var j = 0; j < n; j++) { + var type = possibleMap[j].findIndex(item => item === 1); + var others = Object.keys(pathMap[j]); + for (var k = 0; k < others.length; k++) { + possibleMap[others[k]][type] = 0; + } + result[j] = type + 1; + } + return result; +}; +``` + +**Explain:** + +In the beginning, every garden can plant 4 types of flower. + +We go through the gardens, pick one flower type from all passible choices for that garden. + +And remove this kind of flower type from the possible types of all neighbor gardens. + +In the end, you will have (one of) the result. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/1001-1100/1043. Partition Array for Maximum Sum.md b/1001-1100/1043. Partition Array for Maximum Sum.md new file mode 100644 index 0000000..ae3f754 --- /dev/null +++ b/1001-1100/1043. Partition Array for Maximum Sum.md @@ -0,0 +1,88 @@ +# 1043. Partition Array for Maximum Sum + +- Difficulty: Medium. +- Related Topics: Array, Dynamic Programming. +- Similar Questions: Subsequence of Size K With the Largest Even Sum. + +## Problem + +Given an integer array ```arr```, partition the array into (contiguous) subarrays of length **at most** ```k```. After partitioning, each subarray has their values changed to become the maximum value of that subarray. + +Return **the largest sum of the given array after partitioning. Test cases are generated so that the answer fits in a **32-bit** integer.** + +  +Example 1: + +``` +Input: arr = [1,15,7,9,2,5,10], k = 3 +Output: 84 +Explanation: arr becomes [15,15,15,9,10,10,10] +``` + +Example 2: + +``` +Input: arr = [1,4,1,5,7,3,6,1,9,9,3], k = 4 +Output: 83 +``` + +Example 3: + +``` +Input: arr = [1], k = 1 +Output: 1 +``` + +  +**Constraints:** + + + +- ```1 <= arr.length <= 500``` + +- ```0 <= arr[i] <= 109``` + +- ```1 <= k <= arr.length``` + + + +## Solution + +```javascript +/** + * @param {number[]} arr + * @param {number} k + * @return {number} + */ +var maxSumAfterPartitioning = function(arr, k) { + var dp = Array(arr.length).fill(0); + for (var i = 0; i < arr.length; i++) { + var maxValue = 0; + for (var j = 1; j <= k && j - 1 <= i; j++) { + maxValue = Math.max(maxValue, arr[i - j + 1]); + dp[i] = Math.max(dp[i], ( dp[i - j + 1] + maxValue * j); + } + } + return dp[arr.length]; +}; +``` + +**Explain:** + +`dp[i + 1]` represents array `[0 ... i]` 's maxSumAfterPartitioning. (dp[0] = 0 means nothing, it just helps calculate.) + +``` +dp[i] = max( + dp[i - 1] + max(arr[i]) * 1, + dp[i - 2] + max(arr[i], arr[i - 1]) * 2, + ... + dp[i - k] + max(arr[i], arr[i - 1], ..., arr[i - k]) * k +) +``` + +`dp[arr.length - 1]` would be the answer in the end of the iteration. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). 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/1048. Longest String Chain.md b/1001-1100/1048. Longest String Chain.md new file mode 100644 index 0000000..70ab24a --- /dev/null +++ b/1001-1100/1048. Longest String Chain.md @@ -0,0 +1,117 @@ +# 1048. Longest String Chain + +- Difficulty: Medium. +- Related Topics: Array, Hash Table, Two Pointers, String, Dynamic Programming. +- Similar Questions: . + +## Problem + +You are given an array of `words` where each word consists of lowercase English letters. + +`wordA` is a **predecessor** of `wordB` if and only if we can insert **exactly one** letter anywhere in `wordA` **without changing the order of the other characters** to make it equal to `wordB`. + + + +- For example, `"abc"` is a **predecessor** of `"abac"`, while `"cba"` is not a **predecessor** of `"bcad"`. + + +A **word chain**** **is a sequence of words `[word1, word2, ..., wordk]` with `k >= 1`, where `word1` is a **predecessor** of `word2`, `word2` is a **predecessor** of `word3`, and so on. A single word is trivially a **word chain** with `k == 1`. + +Return **the **length** of the **longest possible word chain** with words chosen from the given list of **`words`. + +  +Example 1: + +``` +Input: words = ["a","b","ba","bca","bda","bdca"] +Output: 4 +Explanation: One of the longest word chains is ["a","ba","bda","bdca"]. +``` + +Example 2: + +``` +Input: words = ["xbc","pcxbcf","xb","cxbc","pcxbc"] +Output: 5 +Explanation: All the words can be put in a word chain ["xb", "xbc", "cxbc", "pcxbc", "pcxbcf"]. +``` + +Example 3: + +``` +Input: words = ["abcd","dbqca"] +Output: 1 +Explanation: The trivial word chain ["abcd"] is one of the longest word chains. +["abcd","dbqca"] is not a valid word chain because the ordering of the letters is changed. +``` + +  +**Constraints:** + + + +- `1 <= words.length <= 1000` + +- `1 <= words[i].length <= 16` + +- `words[i]` only consists of lowercase English letters. + + + +## Solution + +```javascript +/** + * @param {string[]} words + * @return {number} + */ +var longestStrChain = function(words) { + var map = Array(17).fill(0).map(() => []); + for (var i = 0; i < words.length; i++) { + map[words[i].length].push(words[i]); + } + var max = 0; + for (var i = 0; i < words.length; i++) { + max = Math.max(max, helper(map, words[i], {})); + } + return max; +}; + +var helper = function(map, word, dp) { + if (dp[word] !== undefined) return dp[word]; + var arr = map[word.length + 1] || []; + var max = 1; + for (var j = 0; j < arr.length; j++) { + if (!isPredecessor(word, arr[j])) continue; + max = Math.max(max, 1 + helper(map, arr[j], dp)); + } + dp[word] = max; + return max; +}; + +var isPredecessor = function(word1, word2) { + var i = 0; + var skipped = false; + for (var j = 0; j < word2.length; j++) { + if (word1[i] !== word2[j]) { + if (!skipped) { + skipped = true; + continue; + } else { + return false; + } + } + i++; + } + return true; +}; +``` + +**Explain:** + +DFS and DP. + +**Complexity:** + +* Time complexity : O(n ^ 2). +* Space complexity : O(n). diff --git a/1001-1100/1051. Height Checker.md b/1001-1100/1051. Height Checker.md new file mode 100644 index 0000000..fae30fa --- /dev/null +++ b/1001-1100/1051. Height Checker.md @@ -0,0 +1,86 @@ +# 1051. Height Checker + +- Difficulty: Easy. +- Related Topics: Array, Sorting, Counting Sort. +- Similar Questions: . + +## Problem + +A school is trying to take an annual photo of all the students. The students are asked to stand in a single file line in **non-decreasing order** by height. Let this ordering be represented by the integer array `expected` where `expected[i]` is the expected height of the `ith` student in line. + +You are given an integer array `heights` representing the **current order** that the students are standing in. Each `heights[i]` is the height of the `ith` student in line (**0-indexed**). + +Return **the **number of indices** where **`heights[i] != expected[i]`. + +  +Example 1: + +``` +Input: heights = [1,1,4,2,1,3] +Output: 3 +Explanation: +heights: [1,1,4,2,1,3] +expected: [1,1,1,2,3,4] +Indices 2, 4, and 5 do not match. +``` + +Example 2: + +``` +Input: heights = [5,1,2,3,4] +Output: 5 +Explanation: +heights: [5,1,2,3,4] +expected: [1,2,3,4,5] +All indices do not match. +``` + +Example 3: + +``` +Input: heights = [1,2,3,4,5] +Output: 0 +Explanation: +heights: [1,2,3,4,5] +expected: [1,2,3,4,5] +All indices match. +``` + +  +**Constraints:** + + + +- `1 <= heights.length <= 100` + +- `1 <= heights[i] <= 100` + + + +## Solution + +```javascript +/** + * @param {number[]} heights + * @return {number} + */ +var heightChecker = function(heights) { + var arr = Array.from(heights).sort((a, b) => a - b); + var count = 0; + for (var i = 0; i < heights.length; i++) { + if (heights[i] !== arr[i]) { + count += 1; + } + } + return count; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(nlog(n)). +* Space complexity : O(n). diff --git a/1001-1100/1053. Previous Permutation With One Swap.md b/1001-1100/1053. Previous Permutation With One Swap.md new file mode 100644 index 0000000..084059f --- /dev/null +++ b/1001-1100/1053. Previous Permutation With One Swap.md @@ -0,0 +1,125 @@ +# 1053. Previous Permutation With One Swap + +- Difficulty: Medium. +- Related Topics: Array, Greedy. +- Similar Questions: . + +## Problem + +Given an array of positive integers ```arr``` (not necessarily distinct), return **the ****lexicographically**** largest permutation that is smaller than** ```arr```, that can be **made with exactly one swap**. If it cannot be done, then return the same array. + +**Note** that a **swap** exchanges the positions of two numbers ```arr[i]``` and ```arr[j]``` + +  +Example 1: + +``` +Input: arr = [3,2,1] +Output: [3,1,2] +Explanation: Swapping 2 and 1. +``` + +Example 2: + +``` +Input: arr = [1,1,5] +Output: [1,1,5] +Explanation: This is already the smallest permutation. +``` + +Example 3: + +``` +Input: arr = [1,9,4,6,7] +Output: [1,7,4,6,9] +Explanation: Swapping 9 and 7. +``` + +  +**Constraints:** + + + +- ```1 <= arr.length <= 104``` + +- ```1 <= arr[i] <= 104``` + + + +## Solution + +```javascript +/** + * @param {number[]} arr + * @return {number[]} + */ +var prevPermOpt1 = function(arr) { + for (var i = arr.length - 2; i >= 0; i--) { + if (arr[i] <= arr[i + 1]) continue; + var max = 0; + var maxIndex = -1; + for (var j = i + 1; j < arr.length; j++) { + if (arr[j] > max && arr[j] < arr[i]) { + max = arr[j]; + maxIndex = j; + } + } + swap(arr, i, maxIndex); + break; + } + return arr; +}; + +var swap = function(arr, i, j) { + var tmp = arr[i]; + arr[i] = arr[j]; + arr[j] = tmp; +}; +``` + +**Explain:** + +1. we need a smaller array than the current one, so that we need to swap a smaller number from right to left +2. we need a largest array from all the possible result, so that we are going to find the first possible index to swap, from the right of array +3. from right find a possible index to swap, find biggest number smaller than this one to swap on the right + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). + +## Solution 2 + +```javascript +/** + * @param {number[]} arr + * @return {number[]} + */ +var prevPermOpt1 = function(arr) { + for (var i = arr.length - 2; i >= 0; i--) { + if (arr[i] <= arr[i + 1]) continue; + for (var j = arr.length; j > i; j--) { + if (arr[j] < arr[i] && arr[j] !== arr[j - 1]) { + swap(arr, i, j); + return arr; + } + } + } + return arr; +}; + +var swap = function(arr, i, j) { + var tmp = arr[i]; + arr[i] = arr[j]; + arr[j] = tmp; +}; +``` + +**Explain:** + +because we know that numbers from right to left is in order, (from solution 1), we can just find the first one from right. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). 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/1001-1100/1095. Find in Mountain Array.md b/1001-1100/1095. Find in Mountain Array.md new file mode 100644 index 0000000..8e045d4 --- /dev/null +++ b/1001-1100/1095. Find in Mountain Array.md @@ -0,0 +1,157 @@ +# 1095. Find in Mountain Array + +- Difficulty: Hard. +- Related Topics: Array, Binary Search, Interactive. +- Similar Questions: Peak Index in a Mountain Array, Minimum Number of Removals to Make Mountain Array, Find Good Days to Rob the Bank. + +## Problem + +**(This problem is an **interactive problem**.)** + +You may recall that an array `arr` is a **mountain array** if and only if: + + + +- `arr.length >= 3` + There exists some `i` with `0 < i < arr.length - 1` such that: + + +- `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` + +- `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]` + + + + +Given a mountain array `mountainArr`, return the **minimum** `index` such that `mountainArr.get(index) == target`. If such an `index` does not exist, return `-1`. + +**You cannot access the mountain array directly.** You may only access the array using a `MountainArray` interface: + + + +- `MountainArray.get(k)` returns the element of the array at index `k` (0-indexed). + +- `MountainArray.length()` returns the length of the array. + + +Submissions making more than `100` calls to `MountainArray.get` will be judged **Wrong Answer**. Also, any solutions that attempt to circumvent the judge will result in disqualification. + +  +Example 1: + +``` +Input: array = [1,2,3,4,5,3,1], target = 3 +Output: 2 +Explanation: 3 exists in the array, at index=2 and index=5. Return the minimum index, which is 2. +``` + +Example 2: + +``` +Input: array = [0,1,2,4,2,1], target = 3 +Output: -1 +Explanation: 3 does not exist in the array, so we return -1. +``` + +  +**Constraints:** + + + +- `3 <= mountain_arr.length() <= 104` + +- `0 <= target <= 109` + +- `0 <= mountain_arr.get(index) <= 109` + + + +## Solution + +```javascript +/** + * // This is the MountainArray's API interface. + * // You should not implement it, or speculate about its implementation + * function MountainArray() { + * @param {number} index + * @return {number} + * this.get = function(index) { + * ... + * }; + * + * @return {number} + * this.length = function() { + * ... + * }; + * }; + */ + +/** + * @param {number} target + * @param {MountainArray} mountainArr + * @return {number} + */ +var findInMountainArray = function(target, mountainArr) { + var maxIndex = findMaxIndex(mountainArr); + var leftIndex = findInLeft(target, mountainArr, maxIndex); + if (leftIndex !== -1) return leftIndex; + return findInRight(target, mountainArr, maxIndex); +}; + +var findMaxIndex = function(mountainArr) { + var left = 0; + var right = mountainArr.length() - 1; + while (left < right) { + var mid = left + Math.floor((right - left) / 2); + if (mountainArr.get(mid) > mountainArr.get(mid + 1)) { + right = mid; + } else { + left = mid + 1; + } + } + return left; +}; + +var findInLeft = function(target, mountainArr, maxIndex) { + var left = 0; + var right = maxIndex; + while (left <= right) { + var mid = left + Math.floor((right - left) / 2); + var midVal = mountainArr.get(mid); + if (midVal === target) { + return mid; + } else if (midVal > target) { + right = mid - 1; + } else { + left = mid + 1; + } + } + return -1; +}; + +var findInRight = function(target, mountainArr, maxIndex) { + var left = maxIndex; + var right = mountainArr.length() - 1; + while (left <= right) { + var mid = left + Math.floor((right - left) / 2); + var midVal = mountainArr.get(mid); + if (midVal === target) { + return mid; + } else if (midVal < target) { + right = mid - 1; + } else { + left = mid + 1; + } + } + return -1; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(log(n)). +* Space complexity : O(1). diff --git a/101-200/125. Valid Palindrome.md b/101-200/125. Valid Palindrome.md index 4c67e40..cfed0d7 100644 --- a/101-200/125. Valid Palindrome.md +++ b/101-200/125. Valid Palindrome.md @@ -61,3 +61,34 @@ nope. * Time complexity : O(n). * Space complexity : O(n). + + +```js +/** + * @param {string} s + * @return {boolean} + */ +var isPalindrome = function(s) { + + s = s.toLowerCase().replace(/[\W_]/g, ''); + + let left = 0; + let right = s.length - 1; + + while (left < right) { + if (s[left] !== s[right]) { + return false + } + left++; + right--; + } + + return true; + +}; +``` + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). left and right pointers take the constant space. diff --git a/101-200/187. Repeated DNA Sequences.md b/101-200/187. Repeated DNA Sequences.md new file mode 100644 index 0000000..9d0820e --- /dev/null +++ b/101-200/187. Repeated DNA Sequences.md @@ -0,0 +1,73 @@ +# 187. Repeated DNA Sequences + +- Difficulty: Medium. +- Related Topics: Hash Table, String, Bit Manipulation, Sliding Window, Rolling Hash, Hash Function. +- Similar Questions: . + +## Problem + +The **DNA sequence** is composed of a series of nucleotides abbreviated as `'A'`, `'C'`, `'G'`, and `'T'`. + + + +- For example, `"ACGAATTCCG"` is a **DNA sequence**. + + +When studying **DNA**, it is useful to identify repeated sequences within the DNA. + +Given a string `s` that represents a **DNA sequence**, return all the **`10`-letter-long** sequences (substrings) that occur more than once in a DNA molecule. You may return the answer in **any order**. + +  +Example 1: +``` +Input: s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT" +Output: ["AAAAACCCCC","CCCCCAAAAA"] +```Example 2: +``` +Input: s = "AAAAAAAAAAAAA" +Output: ["AAAAAAAAAA"] +``` +  +**Constraints:** + + + +- `1 <= s.length <= 105` + +- `s[i]` is either `'A'`, `'C'`, `'G'`, or `'T'`. + + + +## Solution + +```javascript +/** + * @param {string} s + * @return {string[]} + */ +var findRepeatedDnaSequences = function(s) { + var res = []; + var map = {}; + for (var i = 0; i <= s.length - 10; i++) { + var str = s.slice(i, i + 10); + var num = map[str]; + if (num === -1) continue; + if (num === 1) { + map[str] = -1; + res.push(str); + continue; + } + map[str] = 1; + } + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/101-200/191. Number of 1 Bits.md b/101-200/191. Number of 1 Bits.md new file mode 100644 index 0000000..4e9ee42 --- /dev/null +++ b/101-200/191. Number of 1 Bits.md @@ -0,0 +1,80 @@ +# 191. Number of 1 Bits + +- Difficulty: Easy. +- Related Topics: Divide and Conquer, Bit Manipulation. +- Similar Questions: Reverse Bits, Power of Two, Counting Bits, Binary Watch, Hamming Distance, Binary Number with Alternating Bits, Prime Number of Set Bits in Binary Representation. + +## Problem + +Write a function that takes the binary representation of an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight). + +**Note:** + + + +- Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned. + +- In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 3, the input represents the signed integer. `-3`. + + +  +Example 1: + +``` +Input: n = 00000000000000000000000000001011 +Output: 3 +Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits. +``` + +Example 2: + +``` +Input: n = 00000000000000000000000010000000 +Output: 1 +Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit. +``` + +Example 3: + +``` +Input: n = 11111111111111111111111111111101 +Output: 31 +Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits. +``` + +  +**Constraints:** + + + +- The input must be a **binary string** of length `32`. + + +  +**Follow up:** If this function is called many times, how would you optimize it? + +## Solution + +```javascript +/** + * @param {number} n - a positive integer + * @return {number} + */ +var hammingWeight = function(n) { + var count = 0; + while (n) { + if (n & 1) count++; + n >>>= 1; + } + return count; +}; +``` + +**Explain:** + +use `>>>` instead of `>>`. + +**Complexity:** + +* Time complexity : O(1). +* Space complexity : O(1). diff --git a/101-200/196. Delete Duplicate Emails.md b/101-200/196. Delete Duplicate Emails.md new file mode 100644 index 0000000..9af9a93 --- /dev/null +++ b/101-200/196. Delete Duplicate Emails.md @@ -0,0 +1,72 @@ +# 196. Delete Duplicate Emails + +- Difficulty: Easy. +- Related Topics: Database. +- Similar Questions: . + +## Problem + +Table: `Person` + +``` ++-------------+---------+ +| Column Name | Type | ++-------------+---------+ +| id | int | +| email | varchar | ++-------------+---------+ +id is the primary key (column with unique values) for this table. +Each row of this table contains an email. The emails will not contain uppercase letters. +``` + +  + +Write a solution to** delete** all duplicate emails, keeping only one unique email with the smallest `id`. + +For SQL users, please note that you are supposed to write a `DELETE` statement and not a `SELECT` one. + +For Pandas users, please note that you are supposed to modify `Person` in place. + +After running your script, the answer shown is the `Person` table. The driver will first compile and run your piece of code and then show the `Person` table. The final order of the `Person` table **does not matter**. + +The result format is in the following example. + +  +Example 1: + +``` +Input: +Person table: ++----+------------------+ +| id | email | ++----+------------------+ +| 1 | john@example.com | +| 2 | bob@example.com | +| 3 | john@example.com | ++----+------------------+ +Output: ++----+------------------+ +| id | email | ++----+------------------+ +| 1 | john@example.com | +| 2 | bob@example.com | ++----+------------------+ +Explanation: john@example.com is repeated two times. We keep the row with the smallest Id = 1. +``` + + +## Solution + +```javascript +# Write your MySQL query statement below +DELETE p1 FROM Person p1, Person p2 WHERE p1.email = p2.email AND p1.id > p2.id; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). 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/1101-1200/1160. Find Words That Can Be Formed by Characters.md b/1101-1200/1160. Find Words That Can Be Formed by Characters.md new file mode 100644 index 0000000..294ea1b --- /dev/null +++ b/1101-1200/1160. Find Words That Can Be Formed by Characters.md @@ -0,0 +1,78 @@ +# 1160. Find Words That Can Be Formed by Characters + +- Difficulty: Easy. +- Related Topics: Array, Hash Table, String. +- Similar Questions: Rearrange Characters to Make Target String. + +## Problem + +You are given an array of strings `words` and a string `chars`. + +A string is **good** if it can be formed by characters from chars (each character can only be used once). + +Return **the sum of lengths of all good strings in words**. + +  +Example 1: + +``` +Input: words = ["cat","bt","hat","tree"], chars = "atach" +Output: 6 +Explanation: The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6. +``` + +Example 2: + +``` +Input: words = ["hello","world","leetcode"], chars = "welldonehoneyr" +Output: 10 +Explanation: The strings that can be formed are "hello" and "world" so the answer is 5 + 5 = 10. +``` + +  +**Constraints:** + + + +- `1 <= words.length <= 1000` + +- `1 <= words[i].length, chars.length <= 100` + +- `words[i]` and `chars` consist of lowercase English letters. + + + +## Solution + +```javascript +/** + * @param {string[]} words + * @param {string} chars + * @return {number} + */ +var countCharacters = function(words, chars) { + var map = Array(26).fill(0); + var a = 'a'.charCodeAt(0); + for (var i = 0; i < chars.length; i++) { + map[chars.charCodeAt(i) - a]++; + } + var res = 0; + outerLoop: for (var m = 0; m < words.length; m++) { + var arr = Array.from(map); + for (var n = 0; n < words[m].length; n++) { + if (--arr[words[m].charCodeAt(n) - a] < 0) continue outerLoop; + } + res += words[m].length; + } + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(m * n). +* Space complexity : O(1). 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/1220. Count Vowels Permutation.md b/1201-1300/1220. Count Vowels Permutation.md new file mode 100644 index 0000000..cf7f42a --- /dev/null +++ b/1201-1300/1220. Count Vowels Permutation.md @@ -0,0 +1,95 @@ +# 1220. Count Vowels Permutation + +- Difficulty: Hard. +- Related Topics: Dynamic Programming. +- Similar Questions: . + +## Problem + +Given an integer `n`, your task is to count how many strings of length `n` can be formed under the following rules: + + + +- Each character is a lower case vowel (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`) + +- Each vowel `'a'` may only be followed by an `'e'`. + +- Each vowel `'e'` may only be followed by an `'a'` or an `'i'`. + +- Each vowel `'i'` **may not** be followed by another `'i'`. + +- Each vowel `'o'` may only be followed by an `'i'` or a `'u'`. + +- Each vowel `'u'` may only be followed by an `'a'.` + + +Since the answer may be too large, return it modulo `10^9 + 7.` + +  +Example 1: + +``` +Input: n = 1 +Output: 5 +Explanation: All possible strings are: "a", "e", "i" , "o" and "u". +``` + +Example 2: + +``` +Input: n = 2 +Output: 10 +Explanation: All possible strings are: "ae", "ea", "ei", "ia", "ie", "io", "iu", "oi", "ou" and "ua". +``` + +Example 3:  + +``` +Input: n = 5 +Output: 68 +``` + +  +**Constraints:** + + + +- `1 <= n <= 2 * 10^4` + + + +## Solution + +```javascript +/** + * @param {number} n + * @return {number} + */ +var countVowelPermutation = function(n) { + var dp = Array(n).fill(0).map(() => ({})); + return helper('', n, dp); +}; + +var helper = function(lastChar, n, dp) { + if (n === 0) return 1; + if (dp[n - 1][lastChar] !== undefined) return dp[n - 1][lastChar]; + var mod = Math.pow(10, 9) + 7; + var res = 0; + if (!lastChar || lastChar === 'e') res = (res + helper('a', n - 1, dp)) % mod; + if (!lastChar || lastChar === 'a' || lastChar === 'i') res = (res + helper('e', n - 1, dp)) % mod; + if (!lastChar || lastChar !== 'i') res = (res + helper('i', n - 1, dp)) % mod; + if (!lastChar || lastChar === 'i' || lastChar === 'u') res = (res + helper('o', n - 1, dp)) % mod; + if (!lastChar || lastChar === 'a') res = (res + helper('u', n - 1, dp)) % mod; + dp[n - 1][lastChar] = res; + return res; +}; +``` + +**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/1266. Minimum Time Visiting All Points.md b/1201-1300/1266. Minimum Time Visiting All Points.md new file mode 100644 index 0000000..1e78569 --- /dev/null +++ b/1201-1300/1266. Minimum Time Visiting All Points.md @@ -0,0 +1,92 @@ +# 1266. Minimum Time Visiting All Points + +- Difficulty: Easy. +- Related Topics: Array, Math, Geometry. +- Similar Questions: . + +## Problem + +On a 2D plane, there are `n` points with integer coordinates `points[i] = [xi, yi]`. Return **the **minimum time** in seconds to visit all the points in the order given by **`points`. + +You can move according to these rules: + + + In `1` second, you can either: + + + +- move vertically by one unit, + +- move horizontally by one unit, or + +- move diagonally `sqrt(2)` units (in other words, move one unit vertically then one unit horizontally in `1` second). + + + +- You have to visit the points in the same order as they appear in the array. + +- You are allowed to pass through points that appear later in the order, but these do not count as visits. + + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2019/11/14/1626_example_1.PNG) + +``` +Input: points = [[1,1],[3,4],[-1,0]] +Output: 7 +Explanation: One optimal path is [1,1] -> [2,2] -> [3,3] -> [3,4] -> [2,3] -> [1,2] -> [0,1] -> [-1,0] +Time from [1,1] to [3,4] = 3 seconds +Time from [3,4] to [-1,0] = 4 seconds +Total time = 7 seconds +``` + +Example 2: + +``` +Input: points = [[3,2],[-2,2]] +Output: 5 +``` + +  +**Constraints:** + + + +- `points.length == n` + +- `1 <= n <= 100` + +- `points[i].length == 2` + +- `-1000 <= points[i][0], points[i][1] <= 1000` + + + +## Solution + +```javascript +/** + * @param {number[][]} points + * @return {number} + */ +var minTimeToVisitAllPoints = function(points) { + return points.reduce((sum, point, index) => { + if (index === 0) return 0; + var diffX = Math.abs(point[0] - points[index - 1][0]); + var diffY = Math.abs(point[1] - points[index - 1][1]); + var second = Math.max(diffX, diffY); + return sum + second; + }, 0); +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/1201-1300/1269. Number of Ways to Stay in the Same Place After Some Steps.md b/1201-1300/1269. Number of Ways to Stay in the Same Place After Some Steps.md new file mode 100644 index 0000000..a6ed3e8 --- /dev/null +++ b/1201-1300/1269. Number of Ways to Stay in the Same Place After Some Steps.md @@ -0,0 +1,87 @@ +# 1269. Number of Ways to Stay in the Same Place After Some Steps + +- Difficulty: Hard. +- Related Topics: Dynamic Programming. +- Similar Questions: Number of Ways to Reach a Position After Exactly k Steps. + +## Problem + +You have a pointer at index `0` in an array of size `arrLen`. At each step, you can move 1 position to the left, 1 position to the right in the array, or stay in the same place (The pointer should not be placed outside the array at any time). + +Given two integers `steps` and `arrLen`, return the number of ways such that your pointer is still at index `0` after **exactly** `steps` steps. Since the answer may be too large, return it **modulo** `109 + 7`. + +  +Example 1: + +``` +Input: steps = 3, arrLen = 2 +Output: 4 +Explanation: There are 4 differents ways to stay at index 0 after 3 steps. +Right, Left, Stay +Stay, Right, Left +Right, Stay, Left +Stay, Stay, Stay +``` + +Example 2: + +``` +Input: steps = 2, arrLen = 4 +Output: 2 +Explanation: There are 2 differents ways to stay at index 0 after 2 steps +Right, Left +Stay, Stay +``` + +Example 3: + +``` +Input: steps = 4, arrLen = 2 +Output: 8 +``` + +  +**Constraints:** + + + +- `1 <= steps <= 500` + +- `1 <= arrLen <= 106` + + + +## Solution + +```javascript +/** + * @param {number} steps + * @param {number} arrLen + * @return {number} + */ +var numWays = function(steps, arrLen) { + if (arrLen === 1) return 1; + arrLen = Math.min(arrLen, steps); + var mod = Math.pow(10, 9) + 7; + var lastArr = Array(arrLen).fill(0); + lastArr[0] = 1; + lastArr[1] = 1; + for (var i = 1; i < steps; i++) { + var newArr = Array(arrLen); + for (var j = 0; j < arrLen; j++) { + newArr[j] = (lastArr[j] + (lastArr[j - 1] || 0) + (lastArr[j + 1] || 0)) % mod; + } + lastArr = newArr; + } + return lastArr[0]; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * min(n * m)). +* Space complexity : O(n). diff --git a/1201-1300/1282. Group the People Given the Group Size They Belong To.md b/1201-1300/1282. Group the People Given the Group Size They Belong To.md new file mode 100644 index 0000000..dd2d93d --- /dev/null +++ b/1201-1300/1282. Group the People Given the Group Size They Belong To.md @@ -0,0 +1,79 @@ +# 1282. Group the People Given the Group Size They Belong To + +- Difficulty: Medium. +- Related Topics: Array, Hash Table. +- Similar Questions: Maximum Number of Groups With Increasing Length. + +## Problem + +There are `n` people that are split into some unknown number of groups. Each person is labeled with a **unique ID** from `0` to `n - 1`. + +You are given an integer array `groupSizes`, where `groupSizes[i]` is the size of the group that person `i` is in. For example, if `groupSizes[1] = 3`, then person `1` must be in a group of size `3`. + +Return **a list of groups such that each person `i` is in a group of size `groupSizes[i]`**. + +Each person should appear in **exactly one group**, and every person must be in a group. If there are multiple answers, **return any of them**. It is **guaranteed** that there will be **at least one** valid solution for the given input. + +  +Example 1: + +``` +Input: groupSizes = [3,3,3,3,3,1,3] +Output: [[5],[0,1,2],[3,4,6]] +Explanation: +The first group is [5]. The size is 1, and groupSizes[5] = 1. +The second group is [0,1,2]. The size is 3, and groupSizes[0] = groupSizes[1] = groupSizes[2] = 3. +The third group is [3,4,6]. The size is 3, and groupSizes[3] = groupSizes[4] = groupSizes[6] = 3. +Other possible solutions are [[2,1,6],[5],[0,4,3]] and [[5],[0,6,2],[4,3,1]]. +``` + +Example 2: + +``` +Input: groupSizes = [2,1,3,3,3,2] +Output: [[1],[0,5],[2,3,4]] +``` + +  +**Constraints:** + + + +- `groupSizes.length == n` + +- `1 <= n <= 500` + +- `1 <= groupSizes[i] <= n` + + + +## Solution + +```javascript +/** + * @param {number[]} groupSizes + * @return {number[][]} + */ +var groupThePeople = function(groupSizes) { + var map = Array(groupSizes.length + 1).fill(0).map(() => []); + var res = []; + for (var i = 0; i < groupSizes.length; i++) { + var size = groupSizes[i]; + map[size].push(i); + if (map[size].length === size) { + res.push(map[size]); + map[size] = []; + } + } + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(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/1318. Minimum Flips to Make a OR b Equal to c.md b/1301-1400/1318. Minimum Flips to Make a OR b Equal to c.md new file mode 100644 index 0000000..3f2a23e --- /dev/null +++ b/1301-1400/1318. Minimum Flips to Make a OR b Equal to c.md @@ -0,0 +1,82 @@ +# 1318. Minimum Flips to Make a OR b Equal to c + +- Difficulty: Medium. +- Related Topics: Bit Manipulation. +- Similar Questions: Minimum Bit Flips to Convert Number. + +## Problem + +Given 3 positives numbers `a`, `b` and `c`. Return the minimum flips required in some bits of `a` and `b` to make ( `a` OR `b` == `c` ). (bitwise OR operation). +Flip operation consists of change **any** single bit 1 to 0 or change the bit 0 to 1 in their binary representation. + +  +Example 1: + + +![](https://assets.leetcode.com/uploads/2020/01/06/sample_3_1676.png) + + +``` +Input: a = 2, b = 6, c = 5 +Output: 3 +Explanation: After flips a = 1 , b = 4 , c = 5 such that (a OR b == c) +``` + +Example 2: + +``` +Input: a = 4, b = 2, c = 7 +Output: 1 +``` + +Example 3: + +``` +Input: a = 1, b = 2, c = 3 +Output: 0 +``` + +  +**Constraints:** + + + +- `1 <= a <= 10^9` + +- `1 <= b <= 10^9` + +- `1 <= c <= 10^9` + + +## Solution + +```javascript +/** + * @param {number} a + * @param {number} b + * @param {number} c + * @return {number} + */ +var minFlips = function(a, b, c) { + var num = 0; + for (var i = 0; i < 32; i++) { + var n = Math.pow(2, i); + if ((c & n) && !(a & n) && !(b & n)) { + num += 1; + } else if (!(c & n)) { + if (a & n) num += 1; + if (b & n) num += 1; + } + } + return num; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(1). +* Space complexity : O(1). 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/1341. Split a String in Balanced Strings.md b/1301-1400/1341. Split a String in Balanced Strings.md new file mode 100644 index 0000000..ccc83b1 --- /dev/null +++ b/1301-1400/1341. Split a String in Balanced Strings.md @@ -0,0 +1,93 @@ +# 1341. Split a String in Balanced Strings + +- Difficulty: Easy. +- Related Topics: String, Greedy, Counting. +- Similar Questions: . + +## Problem + +**Balanced** strings are those that have an equal quantity of ```'L'``` and ```'R'``` characters. + +Given a **balanced** string ```s```, split it into some number of substrings such that: + + + +- Each substring is balanced. + + +Return **the **maximum** number of balanced strings you can obtain.** + +  +Example 1: + +``` +Input: s = "RLRRLLRLRL" +Output: 4 +Explanation: s can be split into "RL", "RRLL", "RL", "RL", each substring contains same number of 'L' and 'R'. +``` + +Example 2: + +``` +Input: s = "RLRRRLLRLL" +Output: 2 +Explanation: s can be split into "RL", "RRRLLRLL", each substring contains same number of 'L' and 'R'. +Note that s cannot be split into "RL", "RR", "RL", "LR", "LL", because the 2nd and 5th substrings are not balanced. +``` + +Example 3: + +``` +Input: s = "LLLLRRRR" +Output: 1 +Explanation: s can be split into "LLLLRRRR". +``` + +  +**Constraints:** + + + +- ```2 <= s.length <= 1000``` + +- ```s[i]``` is either ```'L'``` or ```'R'```. + +- ```s``` is a **balanced** string. + + + +## Solution + +```javascript +/** + * @param {string} s + * @return {number} + */ +var balancedStringSplit = function(s) { + var num = 0; + var S = 0; + var L = 0; + for (var i = 0; i < s.length; i++) { + if (s[i] === 'L') { + L++; + } else { + S++; + } + if (S === L) { + num++; + S = 0; + L = 0; + } + } + return num; +}; +``` + +**Explain:** + +Every time you meet a balanced string, split it. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). 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/1301-1400/1359. Count All Valid Pickup and Delivery Options.md b/1301-1400/1359. Count All Valid Pickup and Delivery Options.md new file mode 100644 index 0000000..bb710b7 --- /dev/null +++ b/1301-1400/1359. Count All Valid Pickup and Delivery Options.md @@ -0,0 +1,81 @@ +# 1359. Count All Valid Pickup and Delivery Options + +- Difficulty: Hard. +- Related Topics: Math, Dynamic Programming, Combinatorics. +- Similar Questions: . + +## Problem + +Given `n` orders, each order consist in pickup and delivery services.  + +Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i).  + +Since the answer may be too large, return it modulo 10^9 + 7. + +  +Example 1: + +``` +Input: n = 1 +Output: 1 +Explanation: Unique order (P1, D1), Delivery 1 always is after of Pickup 1. +``` + +Example 2: + +``` +Input: n = 2 +Output: 6 +Explanation: All possible orders: +(P1,P2,D1,D2), (P1,P2,D2,D1), (P1,D1,P2,D2), (P2,P1,D1,D2), (P2,P1,D2,D1) and (P2,D2,P1,D1). +This is an invalid order (P1,D2,P2,D1) because Pickup 2 is after of Delivery 2. +``` + +Example 3: + +``` +Input: n = 3 +Output: 90 +``` + +  +**Constraints:** + + + +- `1 <= n <= 500` + + + +## Solution + +```javascript +/** + * @param {number} n + * @return {number} + */ +var countOrders = function(n) { + return helper(n, 0, 0, {}); +}; + +var helper = function(n, x, y, dp) { + if (x === n && y === n) return 1; + var mod = Math.pow(10, 9) + 7; + var key = `${x}-${y}`; + if (dp[key] === undefined) { + var choosePickup = x < n ? ((n - x) * helper(n, x + 1, y, dp) % mod) : 0; + var chooseDelivery = y < n && x > y ? ((x - y) * helper(n, x, y + 1, dp) % mod) : 0; + dp[key] = (choosePickup + chooseDelivery) % mod; + } + return dp[key]; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/1301-1400/1361. Validate Binary Tree Nodes.md b/1301-1400/1361. Validate Binary Tree Nodes.md new file mode 100644 index 0000000..1e7ff82 --- /dev/null +++ b/1301-1400/1361. Validate Binary Tree Nodes.md @@ -0,0 +1,90 @@ +# 1361. Validate Binary Tree Nodes + +- Difficulty: Medium. +- Related Topics: Tree, Depth-First Search, Breadth-First Search, Union Find, Graph, Binary Tree. +- Similar Questions: . + +## Problem + +You have `n` binary tree nodes numbered from `0` to `n - 1` where node `i` has two children `leftChild[i]` and `rightChild[i]`, return `true` if and only if **all** the given nodes form **exactly one** valid binary tree. + +If node `i` has no left child then `leftChild[i]` will equal `-1`, similarly for the right child. + +Note that the nodes have no values and that we only use the node numbers in this problem. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2019/08/23/1503_ex1.png) + +``` +Input: n = 4, leftChild = [1,-1,3,-1], rightChild = [2,-1,-1,-1] +Output: true +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2019/08/23/1503_ex2.png) + +``` +Input: n = 4, leftChild = [1,-1,3,-1], rightChild = [2,3,-1,-1] +Output: false +``` + +Example 3: + +![](https://assets.leetcode.com/uploads/2019/08/23/1503_ex3.png) + +``` +Input: n = 2, leftChild = [1,0], rightChild = [-1,-1] +Output: false +``` + +  +**Constraints:** + + + +- `n == leftChild.length == rightChild.length` + +- `1 <= n <= 104` + +- `-1 <= leftChild[i], rightChild[i] <= n - 1` + + + +## Solution + +```javascript +/** + * @param {number} n + * @param {number[]} leftChild + * @param {number[]} rightChild + * @return {boolean} + */ +var validateBinaryTreeNodes = function(n, leftChild, rightChild) { + var indegree = Array(n).fill(0); + for (var i = 0; i < n; i++) { + leftChild[i] !== -1 && indegree[leftChild[i]]++; + rightChild[i] !== -1 && indegree[rightChild[i]]++; + } + var root = indegree.findIndex(num => num === 0); + var visited = Array(n).fill(false); + var visit = function(node) { + if (visited[node]) return false; + visited[node] = true; + return (leftChild[node] === -1 || visit(leftChild[node])) + && (rightChild[node] === -1 || visit(rightChild[node])); + }; + return visit(root) && visited.every(n => n); +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/1401-1500/1420. Build Array Where You Can Find The Maximum Exactly K Comparisons.md b/1401-1500/1420. Build Array Where You Can Find The Maximum Exactly K Comparisons.md new file mode 100644 index 0000000..94b15d9 --- /dev/null +++ b/1401-1500/1420. Build Array Where You Can Find The Maximum Exactly K Comparisons.md @@ -0,0 +1,107 @@ +# 1420. Build Array Where You Can Find The Maximum Exactly K Comparisons + +- Difficulty: Hard. +- Related Topics: Dynamic Programming, Prefix Sum. +- Similar Questions: . + +## Problem + +You are given three integers `n`, `m` and `k`. Consider the following algorithm to find the maximum element of an array of positive integers: + +![](https://assets.leetcode.com/uploads/2020/04/02/e.png) + +You should build the array arr which has the following properties: + + + +- `arr` has exactly `n` integers. + +- `1 <= arr[i] <= m` where `(0 <= i < n)`. + +- After applying the mentioned algorithm to `arr`, the value `search_cost` is equal to `k`. + + +Return **the number of ways** to build the array `arr` under the mentioned conditions. As the answer may grow large, the answer **must be** computed modulo `109 + 7`. + +  +Example 1: + +``` +Input: n = 2, m = 3, k = 1 +Output: 6 +Explanation: The possible arrays are [1, 1], [2, 1], [2, 2], [3, 1], [3, 2] [3, 3] +``` + +Example 2: + +``` +Input: n = 5, m = 2, k = 3 +Output: 0 +Explanation: There are no possible arrays that satisify the mentioned conditions. +``` + +Example 3: + +``` +Input: n = 9, m = 1, k = 1 +Output: 1 +Explanation: The only possible array is [1, 1, 1, 1, 1, 1, 1, 1, 1] +``` + +  +**Constraints:** + + + +- `1 <= n <= 50` + +- `1 <= m <= 100` + +- `0 <= k <= n` + + + +## Solution + +```javascript +/** + * @param {number} n + * @param {number} m + * @param {number} k + * @return {number} + */ +var numOfArrays = function(n, m, k) { + return helper(n, m, k, 0, {}); +}; + +var helper = function (n, m, k, maxSoFar, dp) { + if (n === 0 && k === 0) return 1; + if (n === 0) return 0; + if (maxSoFar === m && k > 0) return 0; + var key = `${n}-${k}-${maxSoFar}`; + if (dp[key] !== undefined) { + return dp[key]; + } + var mod = Math.pow(10, 9) + 7; + var ans = 0; + // choose num less than the current max value + for (var i = 1; i <= maxSoFar; i++) { + ans = (ans + helper(n - 1, m, k, maxSoFar, dp)) % mod; + } + // choose num bigger than the current max value + for (var j = maxSoFar + 1; j <= m; j++) { + ans = (ans + helper(n - 1, m, k - 1, j, dp)) % mod; + } + dp[key] = ans; + return dp[key]; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * m ^ 2 * k). +* Space complexity : O(n * m * k). 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/1424. Diagonal Traverse II.md b/1401-1500/1424. Diagonal Traverse II.md new file mode 100644 index 0000000..c3a3f9f --- /dev/null +++ b/1401-1500/1424. Diagonal Traverse II.md @@ -0,0 +1,71 @@ +# 1424. Diagonal Traverse II + +- Difficulty: Medium. +- Related Topics: Array, Sorting, Heap (Priority Queue). +- Similar Questions: . + +## Problem + +Given a 2D integer array `nums`, return **all elements of **`nums`** in diagonal order as shown in the below images**. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2020/04/08/sample_1_1784.png) + +``` +Input: nums = [[1,2,3],[4,5,6],[7,8,9]] +Output: [1,4,2,7,5,3,8,6,9] +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2020/04/08/sample_2_1784.png) + +``` +Input: nums = [[1,2,3,4,5],[6,7],[8],[9,10,11],[12,13,14,15,16]] +Output: [1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16] +``` + +  +**Constraints:** + + + +- `1 <= nums.length <= 105` + +- `1 <= nums[i].length <= 105` + +- `1 <= sum(nums[i].length) <= 105` + +- `1 <= nums[i][j] <= 105` + + + +## Solution + +```javascript +/** + * @param {number[][]} nums + * @return {number[]} + */ +var findDiagonalOrder = function(nums) { + var groups = []; + for (var i = nums.length - 1 ; i >= 0; i--) { + for (var j = 0; j < nums[i].length; j++) { + groups[i + j] = groups[i + j] || []; + groups[i + j].push(nums[i][j]); + } + } + return [].concat(...groups); +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/1401-1500/1425. Constrained Subsequence Sum.md b/1401-1500/1425. Constrained Subsequence Sum.md new file mode 100644 index 0000000..1db105b --- /dev/null +++ b/1401-1500/1425. Constrained Subsequence Sum.md @@ -0,0 +1,110 @@ +# 1425. Constrained Subsequence Sum + +- Difficulty: Hard. +- Related Topics: Array, Dynamic Programming, Queue, Sliding Window, Heap (Priority Queue), Monotonic Queue. +- Similar Questions: Maximum Element-Sum of a Complete Subset of Indices. + +## Problem + +Given an integer array `nums` and an integer `k`, return the maximum sum of a **non-empty** subsequence of that array such that for every two **consecutive** integers in the subsequence, `nums[i]` and `nums[j]`, where `i < j`, the condition `j - i <= k` is satisfied. + +A **subsequence** of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order. + +  +Example 1: + +``` +Input: nums = [10,2,-10,5,20], k = 2 +Output: 37 +Explanation: The subsequence is [10, 2, 5, 20]. +``` + +Example 2: + +``` +Input: nums = [-1,-2,-3], k = 1 +Output: -1 +Explanation: The subsequence must be non-empty, so we choose the largest number. +``` + +Example 3: + +``` +Input: nums = [10,-2,-10,-5,20], k = 2 +Output: 23 +Explanation: The subsequence is [10, -2, -5, 20]. +``` + +  +**Constraints:** + + + +- `1 <= k <= nums.length <= 105` + +- `-104 <= nums[i] <= 104` + + +## Solution 1 + +```javascript +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var constrainedSubsetSum = function(nums, k) { + var queue = new MaxPriorityQueue(); + var max = Number.MIN_SAFE_INTEGER; + for (var i = nums.length - 1; i >= 0; i--) { + while (queue.size() && queue.front().element[1] - i > k) queue.dequeue(); + + var num = nums[i] + (queue.size() ? queue.front().element[0] : 0); + max = Math.max(max, num); + queue.enqueue([num, i], num); + + max = Math.max(max, nums[i]); + queue.enqueue([nums[i], i], nums[i]); + } + return max; +}; +``` + +**Explain:** + +Priority Queue. + +**Complexity:** + +* Time complexity : O(n * log(n)). +* Space complexity : O(n). + + +## Solution 2 + +```javascript +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var constrainedSubsetSum = function(nums, k) { + var deque = []; + for (var i = nums.length - 1; i >= 0; i--) { + while (deque.length && deque[deque.length - 1] - i > k) deque.pop(); + nums[i] += (deque.length ? nums[deque[deque.length - 1]] : 0); + while (deque.length && nums[deque[0]] <= nums[i]) deque.shift(); + if (nums[i] > 0) deque.unshift(i); + } + return Math.max(...nums); +}; +``` + +**Explain:** + +Monotonic Deque. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). 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/1441. Build an Array With Stack Operations.md b/1401-1500/1441. Build an Array With Stack Operations.md new file mode 100644 index 0000000..167574a --- /dev/null +++ b/1401-1500/1441. Build an Array With Stack Operations.md @@ -0,0 +1,117 @@ +# 1441. Build an Array With Stack Operations + +- Difficulty: Medium. +- Related Topics: Array, Stack, Simulation. +- Similar Questions: Minimum Operations to Collect Elements. + +## Problem + +You are given an integer array `target` and an integer `n`. + +You have an empty stack with the two following operations: + + + +- **`"Push"`**: pushes an integer to the top of the stack. + +- **`"Pop"`**: removes the integer on the top of the stack. + + +You also have a stream of the integers in the range `[1, n]`. + +Use the two stack operations to make the numbers in the stack (from the bottom to the top) equal to `target`. You should follow the following rules: + + + +- If the stream of the integers is not empty, pick the next integer from the stream and push it to the top of the stack. + +- If the stack is not empty, pop the integer at the top of the stack. + +- If, at any moment, the elements in the stack (from the bottom to the top) are equal to `target`, do not read new integers from the stream and do not do more operations on the stack. + + +Return **the stack operations needed to build **`target` following the mentioned rules. If there are multiple valid answers, return **any of them**. + +  +Example 1: + +``` +Input: target = [1,3], n = 3 +Output: ["Push","Push","Pop","Push"] +Explanation: Initially the stack s is empty. The last element is the top of the stack. +Read 1 from the stream and push it to the stack. s = [1]. +Read 2 from the stream and push it to the stack. s = [1,2]. +Pop the integer on the top of the stack. s = [1]. +Read 3 from the stream and push it to the stack. s = [1,3]. +``` + +Example 2: + +``` +Input: target = [1,2,3], n = 3 +Output: ["Push","Push","Push"] +Explanation: Initially the stack s is empty. The last element is the top of the stack. +Read 1 from the stream and push it to the stack. s = [1]. +Read 2 from the stream and push it to the stack. s = [1,2]. +Read 3 from the stream and push it to the stack. s = [1,2,3]. +``` + +Example 3: + +``` +Input: target = [1,2], n = 4 +Output: ["Push","Push"] +Explanation: Initially the stack s is empty. The last element is the top of the stack. +Read 1 from the stream and push it to the stack. s = [1]. +Read 2 from the stream and push it to the stack. s = [1,2]. +Since the stack (from the bottom to the top) is equal to target, we stop the stack operations. +The answers that read integer 3 from the stream are not accepted. +``` + +  +**Constraints:** + + + +- `1 <= target.length <= 100` + +- `1 <= n <= 100` + +- `1 <= target[i] <= n` + +- `target` is strictly increasing. + + + +## Solution + +```javascript +/** + * @param {number[]} target + * @param {number} n + * @return {string[]} + */ +var buildArray = function(target, n) { + var res = []; + var j = 1; + for (var i = 0; i < target.length; i++) { + while (j < target[i]) { + res.push('Push'); + res.push('Pop'); + j++; + } + res.push('Push'); + j++; + } + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/1401-1500/1443. Minimum Time to Collect All Apples in a Tree.md b/1401-1500/1443. Minimum Time to Collect All Apples in a Tree.md new file mode 100644 index 0000000..1e60731 --- /dev/null +++ b/1401-1500/1443. Minimum Time to Collect All Apples in a Tree.md @@ -0,0 +1,99 @@ +# 1443. Minimum Time to Collect All Apples in a Tree + +- Difficulty: Medium. +- Related Topics: Hash Table, Tree, Depth-First Search, Breadth-First Search. +- Similar Questions: . + +## Problem + +Given an undirected tree consisting of `n` vertices numbered from `0` to `n-1`, which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. **Return the minimum time in seconds you have to spend to collect all apples in the tree, starting at **vertex 0** and coming back to this vertex.** + +The edges of the undirected tree are given in the array `edges`, where `edges[i] = [ai, bi]` means that exists an edge connecting the vertices `ai` and `bi`. Additionally, there is a boolean array `hasApple`, where `hasApple[i] = true` means that vertex `i` has an apple; otherwise, it does not have any apple. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2020/04/23/min_time_collect_apple_1.png) + +``` +Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,true,true,false] +Output: 8 +Explanation: The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows. +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2020/04/23/min_time_collect_apple_2.png) + +``` +Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,false,true,false] +Output: 6 +Explanation: The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows. +``` + +Example 3: + +``` +Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,false,false,false,false,false] +Output: 0 +``` + +  +**Constraints:** + + + +- `1 <= n <= 105` + +- `edges.length == n - 1` + +- `edges[i].length == 2` + +- `0 <= ai < bi <= n - 1` + +- `hasApple.length == n` + + + +## Solution + +```javascript +/** + * @param {number} n + * @param {number[][]} edges + * @param {boolean[]} hasApple + * @return {number} + */ +var minTime = function(n, edges, hasApple) { + var nodeMap = Array(n).fill(0).map(() => []); + for (var i = 0; i < edges.length; i++) { + nodeMap[edges[i][0]].push(edges[i][1]); + nodeMap[edges[i][1]].push(edges[i][0]); + } + return dfs(0, nodeMap, hasApple, Array(n))[1]; +}; + +var dfs = function(root, nodeMap, hasApple, visited) { + if (visited[root]) return [false, 0]; + var has = hasApple[root]; + var time = 0; + visited[root] = true; + for (var i = 0; i < nodeMap[root].length; i++) { + var item = dfs(nodeMap[root][i], nodeMap, hasApple, visited); + if (item[0]) { + has = true; + time += item[1] + 2; + } + } + return [has, time]; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/1401-1500/1456. Maximum Number of Vowels in a Substring of Given Length.md b/1401-1500/1456. Maximum Number of Vowels in a Substring of Given Length.md new file mode 100644 index 0000000..a1f5b36 --- /dev/null +++ b/1401-1500/1456. Maximum Number of Vowels in a Substring of Given Length.md @@ -0,0 +1,88 @@ +# 1456. Maximum Number of Vowels in a Substring of Given Length + +- Difficulty: Medium. +- Related Topics: String, Sliding Window. +- Similar Questions: Maximum White Tiles Covered by a Carpet, Minimum Recolors to Get K Consecutive Black Blocks, Length of the Longest Alphabetical Continuous Substring. + +## Problem + +Given a string `s` and an integer `k`, return **the maximum number of vowel letters in any substring of **`s`** with length **`k`. + +**Vowel letters** in English are `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`. + +  +Example 1: + +``` +Input: s = "abciiidef", k = 3 +Output: 3 +Explanation: The substring "iii" contains 3 vowel letters. +``` + +Example 2: + +``` +Input: s = "aeiou", k = 2 +Output: 2 +Explanation: Any substring of length 2 contains 2 vowels. +``` + +Example 3: + +``` +Input: s = "leetcode", k = 3 +Output: 2 +Explanation: "lee", "eet" and "ode" contain 2 vowels. +``` + +  +**Constraints:** + + + +- `1 <= s.length <= 105` + +- `s` consists of lowercase English letters. + +- `1 <= k <= s.length` + + + +## Solution + +```javascript +/** + * @param {string} s + * @param {number} k + * @return {number} + */ +var maxVowels = function(s, k) { + var i = 0; + var j = 0; + var count = isVowel(s, j) ? 1 : 0; + var max = count; + while (j < s.length - 1) { + j++; + count += (isVowel(s, j) ? 1 : 0); + if (j - i > k - 1) { + count -= (isVowel(s, i) ? 1 : 0); + i++; + } + max = Math.max(max, count); + } + return max; +}; + +var isVowel = function(s, i) { + return ['a', 'e', 'i', 'o', 'u'].includes(s[i]); +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). 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/1458. Max Dot Product of Two Subsequences.md b/1401-1500/1458. Max Dot Product of Two Subsequences.md new file mode 100644 index 0000000..530c5cc --- /dev/null +++ b/1401-1500/1458. Max Dot Product of Two Subsequences.md @@ -0,0 +1,92 @@ +# 1458. Max Dot Product of Two Subsequences + +- Difficulty: Hard. +- Related Topics: Array, Dynamic Programming. +- Similar Questions: . + +## Problem + +Given two arrays `nums1` and `nums2`. + +Return the maximum dot product between **non-empty** subsequences of nums1 and nums2 with the same length. + +A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, `[2,3,5]` is a subsequence of `[1,2,3,4,5]` while `[1,5,3]` is not). + +  +Example 1: + +``` +Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6] +Output: 18 +Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2. +Their dot product is (2*3 + (-2)*(-6)) = 18. +``` + +Example 2: + +``` +Input: nums1 = [3,-2], nums2 = [2,-6,7] +Output: 21 +Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2. +Their dot product is (3*7) = 21. +``` + +Example 3: + +``` +Input: nums1 = [-1,-1], nums2 = [1,1] +Output: -1 +Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2. +Their dot product is -1. +``` + +  +**Constraints:** + + + +- `1 <= nums1.length, nums2.length <= 500` + +- `-1000 <= nums1[i], nums2[i] <= 1000` + + + +## Solution + +```javascript +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number} + */ +var maxDotProduct = function(nums1, nums2) { + var dp = Array(nums1.length).fill(0).map(() => Array(nums2.length)); + return helper(nums1, nums2, 0, 0, dp); +}; + +var helper = function(nums1, nums2, i, j, dp) { + if (i === nums1.length || j === nums2.length) return Number.MIN_SAFE_INTEGER; + if (dp[i][j] !== undefined) return dp[i][j]; + var max = Number.MIN_SAFE_INTEGER; + // use i,j + max = Math.max(max, nums1[i] * nums2[j] + Math.max(0, helper(nums1, nums2, i + 1, j + 1, dp))); + // not use i,j + // not use i, j both + max = Math.max(max, helper(nums1, nums2, i + 1, j + 1, dp)); + // not use j + max = Math.max(max, helper(nums1, nums2, i, j + 1, dp)); + // not use i + max = Math.max(max, helper(nums1, nums2, i + 1, j, dp)); + dp[i][j] = max; + return max; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * m). +* Space complexity : O(n * m). 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/1475. Final Prices With a Special Discount in a Shop.md b/1401-1500/1475. Final Prices With a Special Discount in a Shop.md new file mode 100644 index 0000000..1f580cf --- /dev/null +++ b/1401-1500/1475. Final Prices With a Special Discount in a Shop.md @@ -0,0 +1,82 @@ +# 1475. Final Prices With a Special Discount in a Shop + +- Difficulty: Easy. +- Related Topics: Array, Stack, Monotonic Stack. +- Similar Questions: . + +## Problem + +You are given an integer array `prices` where `prices[i]` is the price of the `ith` item in a shop. + +There is a special discount for items in the shop. If you buy the `ith` item, then you will receive a discount equivalent to `prices[j]` where `j` is the minimum index such that `j > i` and `prices[j] <= prices[i]`. Otherwise, you will not receive any discount at all. + +Return an integer array `answer` where `answer[i]` is the final price you will pay for the `ith` item of the shop, considering the special discount. + +  +Example 1: + +``` +Input: prices = [8,4,6,2,3] +Output: [4,2,4,2,3] +Explanation: +For item 0 with price[0]=8 you will receive a discount equivalent to prices[1]=4, therefore, the final price you will pay is 8 - 4 = 4. +For item 1 with price[1]=4 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 4 - 2 = 2. +For item 2 with price[2]=6 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 6 - 2 = 4. +For items 3 and 4 you will not receive any discount at all. +``` + +Example 2: + +``` +Input: prices = [1,2,3,4,5] +Output: [1,2,3,4,5] +Explanation: In this case, for all items, you will not receive any discount at all. +``` + +Example 3: + +``` +Input: prices = [10,1,1,6] +Output: [9,0,1,6] +``` + +  +**Constraints:** + + + +- `1 <= prices.length <= 500` + +- `1 <= prices[i] <= 1000` + + + +## Solution + +```javascript +/** + * @param {number[]} prices + * @return {number[]} + */ +var finalPrices = function(prices) { + var res = Array.from(prices); + for (var i = 0; i < prices.length; i++) { + for (var j = i + 1; j < prices.length; j++) { + if (prices[j] <= prices[i]) { + res[i] = prices[i] - prices[j]; + break; + } + } + } + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n ^ 2). +* Space complexity : O(n). 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/1489. Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree.md b/1401-1500/1489. Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree.md new file mode 100644 index 0000000..a8d7eef --- /dev/null +++ b/1401-1500/1489. Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree.md @@ -0,0 +1,137 @@ +# 1489. Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree + +- Difficulty: Hard. +- Related Topics: Union Find, Graph, Sorting, Minimum Spanning Tree, Strongly Connected Component. +- Similar Questions: . + +## Problem + +Given a weighted undirected connected graph with `n` vertices numbered from `0` to `n - 1`, and an array `edges` where `edges[i] = [ai, bi, weighti]` represents a bidirectional and weighted edge between nodes `ai` and `bi`. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices without cycles and with the minimum possible total edge weight. + +Find **all the critical and pseudo-critical edges in the given graph's minimum spanning tree (MST)**. An MST edge whose deletion from the graph would cause the MST weight to increase is called a **critical edge**. On the other hand, a pseudo-critical edge is that which can appear in some MSTs but not all. + +Note that you can return the indices of the edges in any order. + +  +Example 1: + + +![](https://assets.leetcode.com/uploads/2020/06/04/ex1.png) + + +``` +Input: n = 5, edges = [[0,1,1],[1,2,1],[2,3,2],[0,3,2],[0,4,3],[3,4,3],[1,4,6]] +Output: [[0,1],[2,3,4,5]] +Explanation: The figure above describes the graph. +The following figure shows all the possible MSTs: + +Notice that the two edges 0 and 1 appear in all MSTs, therefore they are critical edges, so we return them in the first list of the output. +The edges 2, 3, 4, and 5 are only part of some MSTs, therefore they are considered pseudo-critical edges. We add them to the second list of the output. +``` + +Example 2: + + +![](https://assets.leetcode.com/uploads/2020/06/04/ex2.png) + + +``` +Input: n = 4, edges = [[0,1,1],[1,2,1],[2,3,1],[0,3,1]] +Output: [[],[0,1,2,3]] +Explanation: We can observe that since all 4 edges have equal weight, choosing any 3 edges from the given 4 will yield an MST. Therefore all 4 edges are pseudo-critical. +``` + +  +**Constraints:** + + + +- `2 <= n <= 100` + +- `1 <= edges.length <= min(200, n * (n - 1) / 2)` + +- `edges[i].length == 3` + +- `0 <= ai < bi < n` + +- `1 <= weighti <= 1000` + +- All pairs `(ai, bi)` are **distinct**. + + + +## Solution + +```javascript +/** + * @param {number} n + * @param {number[][]} edges + * @return {number[][]} + */ +var findCriticalAndPseudoCriticalEdges = function(n, edges) { + var [min] = findMinSpanningTreeWeight(n, edges); + var res = [[], []]; + for (var i = 0; i < edges.length; i++) { + var [num, parents] = findMinSpanningTreeWeight(n, edges, undefined, edges[i]); + var root = find(parents, 0); + var isCritical = num > min || !Array(n).fill(0).every((_, k) => find(parents, k) === root); + if (isCritical) { + res[0].push(i); + } else { + var [num2] = findMinSpanningTreeWeight(n, edges, edges[i], undefined); + if (num2 === min) res[1].push(i); + } + } + return res; +}; + +var findMinSpanningTreeWeight = function(n, edges, mustHaveItem, mustNotHaveItem) { + edges = [...edges]; + edges.sort((a, b) => a[2] - b[2]); + + if (mustHaveItem !== undefined) { + edges = edges.filter((item) => item !== mustHaveItem); + edges.unshift(mustHaveItem); + } + + var res = 0; + var parents = Array(n).fill(0).map((_, i) => i); + var count = Array(n).fill(0); + for (var i = 0; i < edges.length; i++) { + if (edges[i] === mustNotHaveItem) continue; + var [m, k, distance] = edges[i]; + var j = find(parents, m); + var p = find(parents, k); + if (j === p) continue; + if (count[j] <= count[p]) { + union(parents, j, p); + count[p]++; + } else { + union(parents, p, j); + count[j]++; + } + res += distance; + } + + return [res, parents]; +}; + +var find = function(parents, i) { + if (parents[i] === i) return i + parents[i] = find(parents, parents[i]); + return parents[i]; +}; + +var union = function(parents, i, j) { + parents[i] = j; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(m * n ^ 2). +* Space complexity : O(n ^ 2). diff --git a/1401-1500/1493. Longest Subarray of 1's After Deleting One Element.md b/1401-1500/1493. Longest Subarray of 1's After Deleting One Element.md new file mode 100644 index 0000000..35bfe9a --- /dev/null +++ b/1401-1500/1493. Longest Subarray of 1's After Deleting One Element.md @@ -0,0 +1,82 @@ +# 1493. Longest Subarray of 1's After Deleting One Element + +- Difficulty: Medium. +- Related Topics: Array, Dynamic Programming, Sliding Window. +- Similar Questions: . + +## Problem + +Given a binary array `nums`, you should delete one element from it. + +Return **the size of the longest non-empty subarray containing only **`1`**'s in the resulting array**. Return `0` if there is no such subarray. + +  +Example 1: + +``` +Input: nums = [1,1,0,1] +Output: 3 +Explanation: After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1's. +``` + +Example 2: + +``` +Input: nums = [0,1,1,1,0,1,1,0,1] +Output: 5 +Explanation: After deleting the number in position 4, [0,1,1,1,1,1,0,1] longest subarray with value of 1's is [1,1,1,1,1]. +``` + +Example 3: + +``` +Input: nums = [1,1,1] +Output: 2 +Explanation: You must delete one element. +``` + +  +**Constraints:** + + + +- `1 <= nums.length <= 105` + +- `nums[i]` is either `0` or `1`. + + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @return {number} + */ +var longestSubarray = function(nums) { + var max = 0; + var last = 0; + var current = 0; + var hasZero = false; + for (var i = 0; i <= nums.length; i++) { + if (nums[i] === 0 || i === nums.length) { + max = Math.max(max, last + current); + last = current; + current = 0; + } else { + current += 1; + } + hasZero = hasZero || nums[i] === 0; + } + return hasZero ? max : max - 1; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). 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/1401-1500/1498. Number of Subsequences That Satisfy the Given Sum Condition.md b/1401-1500/1498. Number of Subsequences That Satisfy the Given Sum Condition.md new file mode 100644 index 0000000..c650b10 --- /dev/null +++ b/1401-1500/1498. Number of Subsequences That Satisfy the Given Sum Condition.md @@ -0,0 +1,98 @@ +# 1498. Number of Subsequences That Satisfy the Given Sum Condition + +- Difficulty: Medium. +- Related Topics: Array, Two Pointers, Binary Search, Sorting. +- Similar Questions: . + +## Problem + +You are given an array of integers `nums` and an integer `target`. + +Return **the number of **non-empty** subsequences of **`nums`** such that the sum of the minimum and maximum element on it is less or equal to **`target`. Since the answer may be too large, return it **modulo** `109 + 7`. + +  +Example 1: + +``` +Input: nums = [3,5,6,7], target = 9 +Output: 4 +Explanation: There are 4 subsequences that satisfy the condition. +[3] -> Min value + max value <= target (3 + 3 <= 9) +[3,5] -> (3 + 5 <= 9) +[3,5,6] -> (3 + 6 <= 9) +[3,6] -> (3 + 6 <= 9) +``` + +Example 2: + +``` +Input: nums = [3,3,6,8], target = 10 +Output: 6 +Explanation: There are 6 subsequences that satisfy the condition. (nums can have repeated numbers). +[3] , [3] , [3,3], [3,6] , [3,6] , [3,3,6] +``` + +Example 3: + +``` +Input: nums = [2,3,3,4,6,7], target = 12 +Output: 61 +Explanation: There are 63 non-empty subsequences, two of them do not satisfy the condition ([6,7], [7]). +Number of valid subsequences (63 - 2 = 61). +``` + +  +**Constraints:** + + + +- `1 <= nums.length <= 105` + +- `1 <= nums[i] <= 106` + +- `1 <= target <= 106` + + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +var numSubseq = function(nums, target) { + nums.sort((a, b) => a - b); + var res = 0; + var l = 0; + var r = nums.length - 1; + var mod = Math.pow(10, 9) + 7; + var pows = Array(nums.length); + pows[0] = 1; + for (var i = 1; i < nums.length; i++) { + pows[i] = (pows[i - 1] * 2) % mod; + } + while (l <= r) { + if (nums[l] + nums[r] <= target) { + res += pows[r - l]; + res %= mod; + l++; + } else { + r--; + } + } + return res; +}; +``` + +**Explain:** + +1. sort the array won't change the result, so we sort it first +2. then use two pointer to find out answers +3. keep it in mind: do not let numbers overflow + +**Complexity:** + +* Time complexity : O(nlog(n)). +* Space complexity : O(n). diff --git a/1501-1600/1502. Can Make Arithmetic Progression From Sequence.md b/1501-1600/1502. Can Make Arithmetic Progression From Sequence.md new file mode 100644 index 0000000..17c0c18 --- /dev/null +++ b/1501-1600/1502. Can Make Arithmetic Progression From Sequence.md @@ -0,0 +1,63 @@ +# 1502. Can Make Arithmetic Progression From Sequence + +- Difficulty: Easy. +- Related Topics: Array, Sorting. +- Similar Questions: Arithmetic Subarrays. + +## Problem + +A sequence of numbers is called an **arithmetic progression** if the difference between any two consecutive elements is the same. + +Given an array of numbers `arr`, return `true` **if the array can be rearranged to form an **arithmetic progression**. Otherwise, return** `false`. + +  +Example 1: + +``` +Input: arr = [3,5,1] +Output: true +Explanation: We can reorder the elements as [1,3,5] or [5,3,1] with differences 2 and -2 respectively, between each consecutive elements. +``` + +Example 2: + +``` +Input: arr = [1,2,4] +Output: false +Explanation: There is no way to reorder the elements to obtain an arithmetic progression. +``` + +  +**Constraints:** + + + +- `2 <= arr.length <= 1000` + +- `-106 <= arr[i] <= 106` + + + +## Solution + +```javascript +/** + * @param {number[]} arr + * @return {boolean} + */ +var canMakeArithmeticProgression = function(arr) { + if (arr.length <= 2) return true; + arr.sort((a, b) => a - b); + const differ = arr[1] - arr[0]; + return arr.every((item, i) => i === 0 || item - arr[i - 1] === differ); +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(nlogn). +* Space complexity : O(1). diff --git a/1501-1600/1503. Last Moment Before All Ants Fall Out of a Plank.md b/1501-1600/1503. Last Moment Before All Ants Fall Out of a Plank.md new file mode 100644 index 0000000..871e893 --- /dev/null +++ b/1501-1600/1503. Last Moment Before All Ants Fall Out of a Plank.md @@ -0,0 +1,104 @@ +# 1503. Last Moment Before All Ants Fall Out of a Plank + +- Difficulty: Medium. +- Related Topics: Array, Brainteaser, Simulation. +- Similar Questions: Count Collisions on a Road, Movement of Robots. + +## Problem + +We have a wooden plank of the length `n` **units**. Some ants are walking on the plank, each ant moves with a speed of **1 unit per second**. Some of the ants move to the **left**, the other move to the **right**. + +When two ants moving in two **different** directions meet at some point, they change their directions and continue moving again. Assume changing directions does not take any additional time. + +When an ant reaches **one end** of the plank at a time `t`, it falls out of the plank immediately. + +Given an integer `n` and two integer arrays `left` and `right`, the positions of the ants moving to the left and the right, return **the moment when the last ant(s) fall out of the plank**. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2020/06/17/ants.jpg) + +``` +Input: n = 4, left = [4,3], right = [0,1] +Output: 4 +Explanation: In the image above: +-The ant at index 0 is named A and going to the right. +-The ant at index 1 is named B and going to the right. +-The ant at index 3 is named C and going to the left. +-The ant at index 4 is named D and going to the left. +The last moment when an ant was on the plank is t = 4 seconds. After that, it falls immediately out of the plank. (i.e., We can say that at t = 4.0000000001, there are no ants on the plank). +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2020/06/17/ants2.jpg) + +``` +Input: n = 7, left = [], right = [0,1,2,3,4,5,6,7] +Output: 7 +Explanation: All ants are going to the right, the ant at index 0 needs 7 seconds to fall. +``` + +Example 3: + +![](https://assets.leetcode.com/uploads/2020/06/17/ants3.jpg) + +``` +Input: n = 7, left = [0,1,2,3,4,5,6,7], right = [] +Output: 7 +Explanation: All ants are going to the left, the ant at index 7 needs 7 seconds to fall. +``` + +  +**Constraints:** + + + +- `1 <= n <= 104` + +- `0 <= left.length <= n + 1` + +- `0 <= left[i] <= n` + +- `0 <= right.length <= n + 1` + +- `0 <= right[i] <= n` + +- `1 <= left.length + right.length <= n + 1` + +- All values of `left` and `right` are unique, and each value can appear **only in one** of the two arrays. + + + +## Solution + +```javascript +/** + * @param {number} n + * @param {number[]} left + * @param {number[]} right + * @return {number} + */ +var getLastMoment = function(n, left, right) { + var max = 0; + for (var i = 0; i < left.length; i++) { + max = Math.max(max, left[i]); + } + for (var j = 0; j < right.length; j++) { + max = Math.max(max, n - right[j]); + } + return max; +}; +``` + +**Explain:** + +If two ants meet, the case they change direction is the same as they do not change direction (the total time needed for them is the same, they just switched their direction). + +So the solution is to find out which ant need the most time to walk to the end. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). 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/1512. Number of Good Pairs.md b/1501-1600/1512. Number of Good Pairs.md new file mode 100644 index 0000000..5902736 --- /dev/null +++ b/1501-1600/1512. Number of Good Pairs.md @@ -0,0 +1,79 @@ +# 1512. Number of Good Pairs + +- Difficulty: Easy. +- Related Topics: Array, Hash Table, Math, Counting. +- Similar Questions: Number of Pairs of Interchangeable Rectangles, Substrings That Begin and End With the Same Letter. + +## Problem + +Given an array of integers `nums`, return **the number of **good pairs****. + +A pair `(i, j)` is called **good** if `nums[i] == nums[j]` and `i` < `j`. + +  +Example 1: + +``` +Input: nums = [1,2,3,1,1,3] +Output: 4 +Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed. +``` + +Example 2: + +``` +Input: nums = [1,1,1,1] +Output: 6 +Explanation: Each pair in the array are good. +``` + +Example 3: + +``` +Input: nums = [1,2,3] +Output: 0 +``` + +  +**Constraints:** + + + +- `1 <= nums.length <= 100` + +- `1 <= nums[i] <= 100` + + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @return {number} + */ +var numIdenticalPairs = function(nums) { + var map = Array(100).fill(0); + for (var i = 0; i < nums.length; i++) { + map[nums[i] - 1]++; + } + var res = 0; + for (var j = 0; j < map.length; j++) { + res += helper(map[j] - 1); + } + return res; +}; + +var helper = function(num) { + return num * (1 + num) / 2; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). 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/1535. Find the Winner of an Array Game.md b/1501-1600/1535. Find the Winner of an Array Game.md new file mode 100644 index 0000000..d26f912 --- /dev/null +++ b/1501-1600/1535. Find the Winner of an Array Game.md @@ -0,0 +1,81 @@ +# 1535. Find the Winner of an Array Game + +- Difficulty: Medium. +- Related Topics: Array, Simulation. +- Similar Questions: . + +## Problem + +Given an integer array `arr` of **distinct** integers and an integer `k`. + +A game will be played between the first two elements of the array (i.e. `arr[0]` and `arr[1]`). In each round of the game, we compare `arr[0]` with `arr[1]`, the larger integer wins and remains at position `0`, and the smaller integer moves to the end of the array. The game ends when an integer wins `k` consecutive rounds. + +Return **the integer which will win the game**. + +It is **guaranteed** that there will be a winner of the game. + +  +Example 1: + +``` +Input: arr = [2,1,3,5,4,6,7], k = 2 +Output: 5 +Explanation: Let's see the rounds of the game: +Round | arr | winner | win_count + 1 | [2,1,3,5,4,6,7] | 2 | 1 + 2 | [2,3,5,4,6,7,1] | 3 | 1 + 3 | [3,5,4,6,7,1,2] | 5 | 1 + 4 | [5,4,6,7,1,2,3] | 5 | 2 +So we can see that 4 rounds will be played and 5 is the winner because it wins 2 consecutive games. +``` + +Example 2: + +``` +Input: arr = [3,2,1], k = 10 +Output: 3 +Explanation: 3 will win the first 10 rounds consecutively. +``` + +  +**Constraints:** + + + +- `2 <= arr.length <= 105` + +- `1 <= arr[i] <= 106` + +- `arr` contains **distinct** integers. + +- `1 <= k <= 109` + + + +## Solution + +```javascript +/** + * @param {number[]} arr + * @param {number} k + * @return {number} + */ +var getWinner = function(arr, k) { + var maxIndex = 0; + for (var i = 1; i < arr.length; i++) { + if (arr[i] > arr[maxIndex]) maxIndex = i; + if (i - maxIndex + (maxIndex === 0 ? 0 : 1) === k) break; + } + return arr[maxIndex]; +}; +``` + +**Explain:** + +We keep track of the maximum number index while iterating the array, in index i, the maximum number wined `i - maxIndex + 1` times (or `i - maxIndex` times if `maxIndex` is zero) + + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/1501-1600/1544. Make The String Great.md b/1501-1600/1544. Make The String Great.md new file mode 100644 index 0000000..901dee2 --- /dev/null +++ b/1501-1600/1544. Make The String Great.md @@ -0,0 +1,95 @@ +# 1544. Make The String Great + +- Difficulty: Easy. +- Related Topics: String, Stack. +- Similar Questions: . + +## Problem + +Given a string `s` of lower and upper case English letters. + +A good string is a string which doesn't have **two adjacent characters** `s[i]` and `s[i + 1]` where: + + + +- `0 <= i <= s.length - 2` + +- `s[i]` is a lower-case letter and `s[i + 1]` is the same letter but in upper-case or **vice-versa**. + + +To make the string good, you can choose **two adjacent** characters that make the string bad and remove them. You can keep doing this until the string becomes good. + +Return **the string** after making it good. The answer is guaranteed to be unique under the given constraints. + +**Notice** that an empty string is also good. + +  +Example 1: + +``` +Input: s = "leEeetcode" +Output: "leetcode" +Explanation: In the first step, either you choose i = 1 or i = 2, both will result "leEeetcode" to be reduced to "leetcode". +``` + +Example 2: + +``` +Input: s = "abBAcC" +Output: "" +Explanation: We have many possible scenarios, and all lead to the same answer. For example: +"abBAcC" --> "aAcC" --> "cC" --> "" +"abBAcC" --> "abBA" --> "aA" --> "" +``` + +Example 3: + +``` +Input: s = "s" +Output: "s" +``` + +  +**Constraints:** + + + +- `1 <= s.length <= 100` + +- `s` contains only lower and upper case English letters. + + + +## Solution + +```javascript +/** + * @param {string} s + * @return {string} + */ +var makeGood = function(s) { + var i = 0; + var res = []; + while (i < s.length) { + if (res.length + && s[i] !== res[res.length - 1] + && s[i].toLowerCase() === res[res.length - 1].toLowerCase() + ) { + res.pop(); + } else { + res.push(s[i]); + } + i += 1; + } + return res.join(''); +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/1501-1600/1557. Minimum Number of Vertices to Reach All Nodes.md b/1501-1600/1557. Minimum Number of Vertices to Reach All Nodes.md new file mode 100644 index 0000000..4553618 --- /dev/null +++ b/1501-1600/1557. Minimum Number of Vertices to Reach All Nodes.md @@ -0,0 +1,86 @@ +# 1557. Minimum Number of Vertices to Reach All Nodes + +- Difficulty: Medium. +- Related Topics: Graph. +- Similar Questions: . + +## Problem + +Given a** directed acyclic graph**, with `n` vertices numbered from `0` to `n-1`, and an array `edges` where `edges[i] = [fromi, toi]` represents a directed edge from node `fromi` to node `toi`. + +Find **the smallest set of vertices from which all nodes in the graph are reachable**. It's guaranteed that a unique solution exists. + +Notice that you can return the vertices in any order. + +  +Example 1: + + +![](https://assets.leetcode.com/uploads/2020/07/07/untitled22.png) + + +``` +Input: n = 6, edges = [[0,1],[0,2],[2,5],[3,4],[4,2]] +Output: [0,3] +Explanation: It's not possible to reach all the nodes from a single vertex. From 0 we can reach [0,1,2,5]. From 3 we can reach [3,4,2,5]. So we output [0,3]. +``` + +Example 2: + + +![](https://assets.leetcode.com/uploads/2020/07/07/untitled.png) + + +``` +Input: n = 5, edges = [[0,1],[2,1],[3,1],[1,4],[2,4]] +Output: [0,2,3] +Explanation: Notice that vertices 0, 3 and 2 are not reachable from any other node, so we must include them. Also any of these vertices can reach nodes 1 and 4. +``` + +  +**Constraints:** + + + +- `2 <= n <= 10^5` + +- `1 <= edges.length <= min(10^5, n * (n - 1) / 2)` + +- `edges[i].length == 2` + +- `0 <= fromi, toi < n` + +- All pairs `(fromi, toi)` are distinct. + + +## Solution + +```javascript +/** + * @param {number} n + * @param {number[][]} edges + * @return {number[]} + */ +var findSmallestSetOfVertices = function(n, edges) { + var map = Array(n).fill(0); + for (var i = 0; i < edges.length; i++) { + map[edges[i][1]]++; + } + var res = []; + for (var j = 0; j < n; j++) { + if (map[j] === 0) { + res.push(j); + } + } + return res; +}; +``` + +**Explain:** + +Because it's guaranteed that a unique solution exists, so we can simply collect nodes with no incoming edge. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/1501-1600/1560. Most Visited Sector in a Circular Track.md b/1501-1600/1560. Most Visited Sector in a Circular Track.md new file mode 100644 index 0000000..a5c6f9d --- /dev/null +++ b/1501-1600/1560. Most Visited Sector in a Circular Track.md @@ -0,0 +1,98 @@ +# 1560. Most Visited Sector in a Circular Track + +- Difficulty: Easy. +- Related Topics: Array, Simulation. +- Similar Questions: . + +## Problem + +Given an integer `n` and an integer array `rounds`. We have a circular track which consists of `n` sectors labeled from `1` to `n`. A marathon will be held on this track, the marathon consists of `m` rounds. The `ith` round starts at sector `rounds[i - 1]` and ends at sector `rounds[i]`. For example, round 1 starts at sector `rounds[0]` and ends at sector `rounds[1]` + +Return **an array of the most visited sectors** sorted in **ascending** order. + +Notice that you circulate the track in ascending order of sector numbers in the counter-clockwise direction (See the first example). + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2020/08/14/tmp.jpg) + +``` +Input: n = 4, rounds = [1,3,1,2] +Output: [1,2] +Explanation: The marathon starts at sector 1. The order of the visited sectors is as follows: +1 --> 2 --> 3 (end of round 1) --> 4 --> 1 (end of round 2) --> 2 (end of round 3 and the marathon) +We can see that both sectors 1 and 2 are visited twice and they are the most visited sectors. Sectors 3 and 4 are visited only once. +``` + +Example 2: + +``` +Input: n = 2, rounds = [2,1,2,1,2,1,2,1,2] +Output: [2] +``` + +Example 3: + +``` +Input: n = 7, rounds = [1,3,5,7] +Output: [1,2,3,4,5,6,7] +``` + +  +**Constraints:** + + + +- `2 <= n <= 100` + +- `1 <= m <= 100` + +- `rounds.length == m + 1` + +- `1 <= rounds[i] <= n` + +- `rounds[i] != rounds[i + 1]` for `0 <= i < m` + + + +## Solution + +```javascript +/** + * @param {number} n + * @param {number[]} rounds + * @return {number[]} + */ +var mostVisited = function(n, rounds) { + var start = rounds[0]; + var end = rounds[rounds.length - 1]; + if (end >= start) { + return Array(end - start + 1).fill(0).reduce((arr, num, i) => { + arr.push(start + i); + return arr; + }, []); + } else { + var arr1 = Array(n - start + 1).fill(0).reduce((arr, num, i) => { + arr.push(start + i); + return arr; + }, []); + var arr2 = Array(end).fill(0).reduce((arr, num, i) => { + arr.push(i + 1); + return arr; + }, []); + return arr2.concat(arr1); + } +}; +``` + +**Explain:** + +if start <= end, return range[start, end] + +else return range[0, end] + range[start, n] + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/1501-1600/1561. Maximum Number of Coins You Can Get.md b/1501-1600/1561. Maximum Number of Coins You Can Get.md new file mode 100644 index 0000000..7145dbd --- /dev/null +++ b/1501-1600/1561. Maximum Number of Coins You Can Get.md @@ -0,0 +1,91 @@ +# 1561. Maximum Number of Coins You Can Get + +- Difficulty: Medium. +- Related Topics: Array, Math, Greedy, Sorting, Game Theory. +- Similar Questions: . + +## Problem + +There are `3n` piles of coins of varying size, you and your friends will take piles of coins as follows: + + + +- In each step, you will choose **any **`3` piles of coins (not necessarily consecutive). + +- Of your choice, Alice will pick the pile with the maximum number of coins. + +- You will pick the next pile with the maximum number of coins. + +- Your friend Bob will pick the last pile. + +- Repeat until there are no more piles of coins. + + +Given an array of integers `piles` where `piles[i]` is the number of coins in the `ith` pile. + +Return the maximum number of coins that you can have. + +  +Example 1: + +``` +Input: piles = [2,4,1,2,7,8] +Output: 9 +Explanation: Choose the triplet (2, 7, 8), Alice Pick the pile with 8 coins, you the pile with 7 coins and Bob the last one. +Choose the triplet (1, 2, 4), Alice Pick the pile with 4 coins, you the pile with 2 coins and Bob the last one. +The maximum number of coins which you can have are: 7 + 2 = 9. +On the other hand if we choose this arrangement (1, 2, 8), (2, 4, 7) you only get 2 + 4 = 6 coins which is not optimal. +``` + +Example 2: + +``` +Input: piles = [2,4,5] +Output: 4 +``` + +Example 3: + +``` +Input: piles = [9,8,7,6,5,1,2,3,4] +Output: 18 +``` + +  +**Constraints:** + + + +- `3 <= piles.length <= 105` + +- `piles.length % 3 == 0` + +- `1 <= piles[i] <= 104` + + + +## Solution + +```javascript +/** + * @param {number[]} piles + * @return {number} + */ +var maxCoins = function(piles) { + piles.sort((a, b) => a - b); + var res = 0; + for (var i = 0; i < piles.length / 3; i++) { + res += piles[piles.length - (i * 2) - 1 - 1]; + } + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * log(n)). +* Space complexity : O(1). diff --git a/1501-1600/1572. Matrix Diagonal Sum.md b/1501-1600/1572. Matrix Diagonal Sum.md new file mode 100644 index 0000000..b0f8c27 --- /dev/null +++ b/1501-1600/1572. Matrix Diagonal Sum.md @@ -0,0 +1,84 @@ +# 1572. Matrix Diagonal Sum + +- Difficulty: Easy. +- Related Topics: Array, Matrix. +- Similar Questions: Check if Every Row and Column Contains All Numbers, Check if Matrix Is X-Matrix. + +## Problem + +Given a square matrix `mat`, return the sum of the matrix diagonals. + +Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2020/08/14/sample_1911.png) + +``` +Input: mat = [[1,2,3], +  [4,5,6], +  [7,8,9]] +Output: 25 +Explanation: Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25 +Notice that element mat[1][1] = 5 is counted only once. +``` + +Example 2: + +``` +Input: mat = [[1,1,1,1], +  [1,1,1,1], +  [1,1,1,1], +  [1,1,1,1]] +Output: 8 +``` + +Example 3: + +``` +Input: mat = [[5]] +Output: 5 +``` + +  +**Constraints:** + + + +- `n == mat.length == mat[i].length` + +- `1 <= n <= 100` + +- `1 <= mat[i][j] <= 100` + + + +## Solution + +```javascript +/** + * @param {number[][]} mat + * @return {number} + */ +var diagonalSum = function(mat) { + var res = 0; + for (var i = 0; i < mat.length; i++) { + res += mat[i][i] + mat[i][mat.length - 1 - i]; + } + if (mat.length % 2) { + var mid = Math.floor(mat.length / 2); + res -= mat[mid][mid]; + } + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). 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/1501-1600/1584. Min Cost to Connect All Points.md b/1501-1600/1584. Min Cost to Connect All Points.md new file mode 100644 index 0000000..e4d7a5c --- /dev/null +++ b/1501-1600/1584. Min Cost to Connect All Points.md @@ -0,0 +1,110 @@ +# 1584. Min Cost to Connect All Points + +- Difficulty: Medium. +- Related Topics: Array, Union Find, Graph, Minimum Spanning Tree. +- Similar Questions: Minimum Number of Lines to Cover Points. + +## Problem + +You are given an array `points` representing integer coordinates of some points on a 2D-plane, where `points[i] = [xi, yi]`. + +The cost of connecting two points `[xi, yi]` and `[xj, yj]` is the **manhattan distance** between them: `|xi - xj| + |yi - yj|`, where `|val|` denotes the absolute value of `val`. + +Return **the minimum cost to make all points connected.** All points are connected if there is **exactly one** simple path between any two points. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2020/08/26/d.png) + +``` +Input: points = [[0,0],[2,2],[3,10],[5,2],[7,0]] +Output: 20 +Explanation: + +We can connect the points as shown above to get the minimum cost of 20. +Notice that there is a unique path between every pair of points. +``` + +Example 2: + +``` +Input: points = [[3,12],[-2,5],[-4,1]] +Output: 18 +``` + +  +**Constraints:** + + + +- `1 <= points.length <= 1000` + +- `-106 <= xi, yi <= 106` + +- All pairs `(xi, yi)` are distinct. + + + +## Solution + +```javascript +/** + * @param {number[][]} points + * @return {number} + */ +var minCostConnectPoints = function(points) { + var edges = []; + for (var i = 0; i < points.length; i++) { + for (var j = i + 1; j < points.length; j++) { + edges.push([i, j, getDistance(points, i, j)]); + } + } + edges.sort((a, b) => a[2] - b[2]); + var res = 0; + var parents = Array(points.length).fill(0).map((_, i) => i); + var rank = Array(points.length).fill(0); + for (var m = 0; m < edges.length; m++) { + var [i, j, distance] = edges[m]; + var n = find(parents, i); + var k = find(parents, j); + if (n === k) continue; + if (rank[n] <= rank[k]) { + union(parents, n, k); + rank[k]++; + } else { + union(parents, k, n); + rank[n]++; + } + res += distance; + } + return res; +}; + +var getDistance = function(points, i, j) { + return Math.abs(points[i][0] - points[j][0]) + Math.abs(points[i][1] - points[j][1]); +}; + +var union = function(parents, i, j) { + parents[i] = j; +}; + +var find = function(parents, i) { + if (parents[i] === i) { + return i; + } + parents[i] = find(parents, parents[i]); + return parents[i]; +}; +``` + +**Explain:** + +Union-find to detect circle. + +Kruskal’s Algorithm to get minimum spanning tree. + +**Complexity:** + +* Time complexity : O(n ^ 2). +* Space complexity : O(n ^ 2). diff --git a/1601-1700/1601. Maximum Number of Achievable Transfer Requests.md b/1601-1700/1601. Maximum Number of Achievable Transfer Requests.md new file mode 100644 index 0000000..b248a2a --- /dev/null +++ b/1601-1700/1601. Maximum Number of Achievable Transfer Requests.md @@ -0,0 +1,109 @@ +# 1601. Maximum Number of Achievable Transfer Requests + +- Difficulty: Hard. +- Related Topics: Array, Backtracking, Bit Manipulation, Enumeration. +- Similar Questions: . + +## Problem + +We have `n` buildings numbered from `0` to `n - 1`. Each building has a number of employees. It's transfer season, and some employees want to change the building they reside in. + +You are given an array `requests` where `requests[i] = [fromi, toi]` represents an employee's request to transfer from building `fromi` to building `toi`. + +**All buildings are full**, so a list of requests is achievable only if for each building, the **net change in employee transfers is zero**. This means the number of employees **leaving** is **equal** to the number of employees **moving in**. For example if `n = 3` and two employees are leaving building `0`, one is leaving building `1`, and one is leaving building `2`, there should be two employees moving to building `0`, one employee moving to building `1`, and one employee moving to building `2`. + +Return **the maximum number of achievable requests**. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2020/09/10/move1.jpg) + +``` +Input: n = 5, requests = [[0,1],[1,0],[0,1],[1,2],[2,0],[3,4]] +Output: 5 +Explantion: Let's see the requests: +From building 0 we have employees x and y and both want to move to building 1. +From building 1 we have employees a and b and they want to move to buildings 2 and 0 respectively. +From building 2 we have employee z and they want to move to building 0. +From building 3 we have employee c and they want to move to building 4. +From building 4 we don't have any requests. +We can achieve the requests of users x and b by swapping their places. +We can achieve the requests of users y, a and z by swapping the places in the 3 buildings. +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2020/09/10/move2.jpg) + +``` +Input: n = 3, requests = [[0,0],[1,2],[2,1]] +Output: 3 +Explantion: Let's see the requests: +From building 0 we have employee x and they want to stay in the same building 0. +From building 1 we have employee y and they want to move to building 2. +From building 2 we have employee z and they want to move to building 1. +We can achieve all the requests. +``` + +Example 3: + +``` +Input: n = 4, requests = [[0,3],[3,1],[1,2],[2,0]] +Output: 4 +``` + +  +**Constraints:** + + + +- `1 <= n <= 20` + +- `1 <= requests.length <= 16` + +- `requests[i].length == 2` + +- `0 <= fromi, toi < n` + + + +## Solution + +```javascript +/** + * @param {number} n + * @param {number[][]} requests + * @return {number} + */ +var maximumRequests = function(n, requests) { + return solve(n, requests, Array(n).fill(0), 0, 0); +}; + +var solve = function(n, requests, indegree, index, count) { + // end + if (index === requests.length) { + return indegree.every(i => i === 0) ? count : 0; + } + // take this request + indegree[requests[index][0]]--; + indegree[requests[index][1]]++; + const res = solve(n, requests, indegree, index + 1, count + 1); + indegree[requests[index][0]]++; + indegree[requests[index][1]]--; + // ignore this request + return Math.max( + res, + solve(n, requests, indegree, index + 1, count), + ); +}; +``` + +**Explain:** + +For every request, we can take it or ignore it, use backtrack to track the count of people moved in a department, find out which way end up with maximum result. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/1601-1700/1605. Find Valid Matrix Given Row and Column Sums.md b/1601-1700/1605. Find Valid Matrix Given Row and Column Sums.md new file mode 100644 index 0000000..756e8bf --- /dev/null +++ b/1601-1700/1605. Find Valid Matrix Given Row and Column Sums.md @@ -0,0 +1,88 @@ +# 1605. Find Valid Matrix Given Row and Column Sums + +- Difficulty: Medium. +- Related Topics: Array, Greedy, Matrix. +- Similar Questions: Reconstruct a 2-Row Binary Matrix. + +## Problem + +You are given two arrays `rowSum` and `colSum` of non-negative integers where `rowSum[i]` is the sum of the elements in the `ith` row and `colSum[j]` is the sum of the elements of the `jth` column of a 2D matrix. In other words, you do not know the elements of the matrix, but you do know the sums of each row and column. + +Find any matrix of **non-negative** integers of size `rowSum.length x colSum.length` that satisfies the `rowSum` and `colSum` requirements. + +Return **a 2D array representing **any** matrix that fulfills the requirements**. It's guaranteed that **at least one **matrix that fulfills the requirements exists. + +  +Example 1: + +``` +Input: rowSum = [3,8], colSum = [4,7] +Output: [[3,0], + [1,7]] +Explanation: +0th row: 3 + 0 = 3 == rowSum[0] +1st row: 1 + 7 = 8 == rowSum[1] +0th column: 3 + 1 = 4 == colSum[0] +1st column: 0 + 7 = 7 == colSum[1] +The row and column sums match, and all matrix elements are non-negative. +Another possible matrix is: [[1,2], + [3,5]] +``` + +Example 2: + +``` +Input: rowSum = [5,7,10], colSum = [8,6,8] +Output: [[0,5,0], + [6,1,0], + [2,0,8]] +``` + +  +**Constraints:** + + + +- `1 <= rowSum.length, colSum.length <= 500` + +- `0 <= rowSum[i], colSum[i] <= 108` + +- `sum(rowSum) == sum(colSum)` + + + +## Solution + +```javascript +/** + * @param {number[]} rowSum + * @param {number[]} colSum + * @return {number[][]} + */ +var restoreMatrix = function(rowSum, colSum) { + var m = rowSum.length; + var n = colSum.length; + var res = Array(m).fill(0).map(() => Array(n).fill(0)); + for (var i = 0; i < m; i++) { + res[i][0] = rowSum[i]; + } + for (var i = 0; i < n - 1; i++) { + for (var j = 0; j < m; j++) { + var num = Math.min(res[j][i], colSum[i]); + res[j][i + 1] = res[j][i] - num; + res[j][i] = num; + colSum[i] -= num; + } + } + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * m). +* Space complexity : O(n * m). diff --git a/1601-1700/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/1615. Maximal Network Rank.md b/1601-1700/1615. Maximal Network Rank.md new file mode 100644 index 0000000..cdb8304 --- /dev/null +++ b/1601-1700/1615. Maximal Network Rank.md @@ -0,0 +1,108 @@ +# 1615. Maximal Network Rank + +- Difficulty: Medium. +- Related Topics: Graph. +- Similar Questions: . + +## Problem + +There is an infrastructure of `n` cities with some number of `roads` connecting these cities. Each `roads[i] = [ai, bi]` indicates that there is a bidirectional road between cities `ai` and `bi`. + +The **network rank**** **of **two different cities** is defined as the total number of **directly** connected roads to **either** city. If a road is directly connected to both cities, it is only counted **once**. + +The **maximal network rank **of the infrastructure is the **maximum network rank** of all pairs of different cities. + +Given the integer `n` and the array `roads`, return **the **maximal network rank** of the entire infrastructure**. + +  +Example 1: + + +![](https://assets.leetcode.com/uploads/2020/09/21/ex1.png) + + +``` +Input: n = 4, roads = [[0,1],[0,3],[1,2],[1,3]] +Output: 4 +Explanation: The network rank of cities 0 and 1 is 4 as there are 4 roads that are connected to either 0 or 1. The road between 0 and 1 is only counted once. +``` + +Example 2: + + +![](https://assets.leetcode.com/uploads/2020/09/21/ex2.png) + + +``` +Input: n = 5, roads = [[0,1],[0,3],[1,2],[1,3],[2,3],[2,4]] +Output: 5 +Explanation: There are 5 roads that are connected to cities 1 or 2. +``` + +Example 3: + +``` +Input: n = 8, roads = [[0,1],[1,2],[2,3],[2,4],[5,6],[5,7]] +Output: 5 +Explanation: The network rank of 2 and 5 is 5. Notice that all the cities do not have to be connected. +``` + +  +**Constraints:** + + + +- `2 <= n <= 100` + +- `0 <= roads.length <= n * (n - 1) / 2` + +- `roads[i].length == 2` + +- `0 <= ai, bi <= n-1` + +- `ai != bi` + +- Each pair of cities has **at most one** road connecting them. + + + +## Solution + +```javascript +/** + * @param {number} n + * @param {number[][]} roads + * @return {number} + */ +var maximalNetworkRank = function(n, roads) { + var map = {}; + for (var i = 0; i < roads.length; i++) { + var [m, k] = roads[i]; + if (!map[m]) map[m] = {}; + if (!map[k]) map[k] = {}; + map[m][k] = true; + map[k][m] = true; + } + var res = 0; + for (var i = 0; i < n; i++) { + for (var j = i + 1; j < n; j++) { + res = Math.max( + res, + Object.keys(map[i] || {}).length + + Object.keys(map[j] || {}).length + - (map[i] && map[i][j] ? 1 : 0) + ); + } + } + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n ^ 2 + m). +* 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/1630. Arithmetic Subarrays.md b/1601-1700/1630. Arithmetic Subarrays.md new file mode 100644 index 0000000..3f30ec7 --- /dev/null +++ b/1601-1700/1630. Arithmetic Subarrays.md @@ -0,0 +1,108 @@ +# 1630. Arithmetic Subarrays + +- Difficulty: Medium. +- Related Topics: Array, Sorting. +- Similar Questions: Arithmetic Slices, Can Make Arithmetic Progression From Sequence. + +## Problem + +A sequence of numbers is called **arithmetic** if it consists of at least two elements, and the difference between every two consecutive elements is the same. More formally, a sequence `s` is arithmetic if and only if `s[i+1] - s[i] == s[1] - s[0] `for all valid `i`. + +For example, these are **arithmetic** sequences: + +``` +1, 3, 5, 7, 9 +7, 7, 7, 7 +3, -1, -5, -9 +``` + +The following sequence is not **arithmetic**: + +``` +1, 1, 2, 5, 7 +``` + +You are given an array of `n` integers, `nums`, and two arrays of `m` integers each, `l` and `r`, representing the `m` range queries, where the `ith` query is the range `[l[i], r[i]]`. All the arrays are **0-indexed**. + +Return **a list of **`boolean` **elements** `answer`**, where** `answer[i]` **is** `true` **if the subarray** `nums[l[i]], nums[l[i]+1], ... , nums[r[i]]`** can be **rearranged** to form an **arithmetic** sequence, and** `false` **otherwise.** + +  +Example 1: + +``` +Input: nums = [4,6,5,9,3,7], l = [0,0,2], r = [2,3,5] +Output: [true,false,true] +Explanation: +In the 0th query, the subarray is [4,6,5]. This can be rearranged as [6,5,4], which is an arithmetic sequence. +In the 1st query, the subarray is [4,6,5,9]. This cannot be rearranged as an arithmetic sequence. +In the 2nd query, the subarray is [5,9,3,7]. This can be rearranged as [3,5,7,9], which is an arithmetic sequence. +``` + +Example 2: + +``` +Input: nums = [-12,-9,-3,-12,-6,15,20,-25,-20,-15,-10], l = [0,1,6,4,8,7], r = [4,4,9,7,9,10] +Output: [false,true,false,false,true,true] +``` + +  +**Constraints:** + + + +- `n == nums.length` + +- `m == l.length` + +- `m == r.length` + +- `2 <= n <= 500` + +- `1 <= m <= 500` + +- `0 <= l[i] < r[i] < n` + +- `-105 <= nums[i] <= 105` + + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @param {number[]} l + * @param {number[]} r + * @return {boolean[]} + */ +var checkArithmeticSubarrays = function(nums, l, r) { + return l.map((_, i) => check(nums, l[i], r[i])); +}; + +var check = function(nums, l, r) { + var map = {}; + var min = Number.MAX_SAFE_INTEGER; + var max = Number.MIN_SAFE_INTEGER; + for (var i = l; i <= r; i++) { + min = Math.min(min, nums[i]); + max = Math.max(max, nums[i]); + map[nums[i]] = true; + } + var diff = (max - min) / (r - l); + for (var num = min; num < max; num += diff) { + if (map[num] === undefined) { + return false; + } + } + return true; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * m). +* Space complexity : O(n). 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/1647. Minimum Deletions to Make Character Frequencies Unique.md b/1601-1700/1647. Minimum Deletions to Make Character Frequencies Unique.md new file mode 100644 index 0000000..d0c60ca --- /dev/null +++ b/1601-1700/1647. Minimum Deletions to Make Character Frequencies Unique.md @@ -0,0 +1,93 @@ +# 1647. Minimum Deletions to Make Character Frequencies Unique + +- Difficulty: Medium. +- Related Topics: Hash Table, String, Greedy, Sorting. +- Similar Questions: Minimum Deletions to Make Array Beautiful, Removing Minimum and Maximum From Array, Remove Letter To Equalize Frequency. + +## Problem + +A string `s` is called **good** if there are no two different characters in `s` that have the same **frequency**. + +Given a string `s`, return** the **minimum** number of characters you need to delete to make **`s`** **good**.** + +The **frequency** of a character in a string is the number of times it appears in the string. For example, in the string `"aab"`, the **frequency** of `'a'` is `2`, while the **frequency** of `'b'` is `1`. + +  +Example 1: + +``` +Input: s = "aab" +Output: 0 +Explanation: s is already good. +``` + +Example 2: + +``` +Input: s = "aaabbbcc" +Output: 2 +Explanation: You can delete two 'b's resulting in the good string "aaabcc". +Another way it to delete one 'b' and one 'c' resulting in the good string "aaabbc". +``` + +Example 3: + +``` +Input: s = "ceabaacb" +Output: 2 +Explanation: You can delete both 'c's resulting in the good string "eabaab". +Note that we only care about characters that are still in the string at the end (i.e. frequency of 0 is ignored). +``` + +  +**Constraints:** + + + +- `1 <= s.length <= 105` + +- `s` contains only lowercase English letters. + + + +## Solution + +```javascript +/** + * @param {string} s + * @return {number} + */ +var minDeletions = function(s) { + var frequencyMap = {}; + for (var i = 0; i < s.length; i++) { + frequencyMap[s[i]] = (frequencyMap[s[i]] || 0) + 1; + } + var frequencies = Object.values(frequencyMap).sort((a, b) => b - a); + var duplicatedFrequencies = []; + var result = 0; + for (var j = 0; j < frequencies.length; j++) { + var frequency = frequencies[j]; + if (frequency === frequencies[j + 1]) { + duplicatedFrequencies.push(frequency); + continue; + } + while (duplicatedFrequencies.length && frequency > (frequencies[j + 1] || 0) + 1) { + frequency -= 1; + result += duplicatedFrequencies.pop() - frequency; + } + } + while (duplicatedFrequencies.length) { + result += duplicatedFrequencies.pop(); + } + return result; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/1601-1700/1653. Minimum Deletions to Make String Balanced.md b/1601-1700/1653. Minimum Deletions to Make String Balanced.md new file mode 100644 index 0000000..76f367d --- /dev/null +++ b/1601-1700/1653. Minimum Deletions to Make String Balanced.md @@ -0,0 +1,83 @@ +# 1653. Minimum Deletions to Make String Balanced + +- Difficulty: Medium. +- Related Topics: String, Dynamic Programming, Stack. +- Similar Questions: Check if All A's Appears Before All B's. + +## Problem + +You are given a string `s` consisting only of characters `'a'` and `'b'`​​​​. + +You can delete any number of characters in `s` to make `s` **balanced**. `s` is **balanced** if there is no pair of indices `(i,j)` such that `i < j` and `s[i] = 'b'` and `s[j]= 'a'`. + +Return **the **minimum** number of deletions needed to make **`s`** **balanced****. + +  +Example 1: + +``` +Input: s = "aababbab" +Output: 2 +Explanation: You can either: +Delete the characters at 0-indexed positions 2 and 6 ("aababbab" -> "aaabbb"), or +Delete the characters at 0-indexed positions 3 and 6 ("aababbab" -> "aabbbb"). +``` + +Example 2: + +``` +Input: s = "bbaaaaabb" +Output: 2 +Explanation: The only solution is to delete the first two characters. +``` + +  +**Constraints:** + + + +- `1 <= s.length <= 105` + +- `s[i]` is `'a'` or `'b'`​​. + + + +## Solution + +```javascript +/** + * @param {string} s + * @return {number} + */ +var minimumDeletions = function(s) { + var map = Array(s.length).fill(0); + for (var i = s.length - 2; i >= 0; i--) { + map[i] = map[i + 1] + (s[i + 1] === 'a' ? 1 : 0); + } + return solve(s, 0, 0, Array(s.length), map); +}; + +var solve = function(s, i, num, map, map2) { + if (i >= s.length) return 0; + if (map[i] === undefined) { + if (s[i] === 'a') { + map[i] = solve(s, i + 1, 0, map, map2); + } else { + map[i] = Math.min( + solve(s, i + 1, 1, map, map2), + map2[i], + ); + } + } + return map[i] + num; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/1601-1700/1658. Minimum Operations to Reduce X to Zero.md b/1601-1700/1658. Minimum Operations to Reduce X to Zero.md new file mode 100644 index 0000000..353f7a4 --- /dev/null +++ b/1601-1700/1658. Minimum Operations to Reduce X to Zero.md @@ -0,0 +1,87 @@ +# 1658. Minimum Operations to Reduce X to Zero + +- Difficulty: Medium. +- Related Topics: Array, Hash Table, Binary Search, Sliding Window, Prefix Sum. +- Similar Questions: Minimum Size Subarray Sum, Subarray Sum Equals K, Minimum Operations to Convert Number, Removing Minimum Number of Magic Beans, Minimum Operations to Make the Integer Zero. + +## Problem + +You are given an integer array `nums` and an integer `x`. In one operation, you can either remove the leftmost or the rightmost element from the array `nums` and subtract its value from `x`. Note that this **modifies** the array for future operations. + +Return **the **minimum number** of operations to reduce **`x` **to **exactly**** `0` **if it is possible****, otherwise, return **`-1`. + +  +Example 1: + +``` +Input: nums = [1,1,4,2,3], x = 5 +Output: 2 +Explanation: The optimal solution is to remove the last two elements to reduce x to zero. +``` + +Example 2: + +``` +Input: nums = [5,6,7,8,9], x = 4 +Output: -1 +``` + +Example 3: + +``` +Input: nums = [3,2,20,1,1,3], x = 10 +Output: 5 +Explanation: The optimal solution is to remove the last three elements and the first two elements (5 operations in total) to reduce x to zero. +``` + +  +**Constraints:** + + + +- `1 <= nums.length <= 105` + +- `1 <= nums[i] <= 104` + +- `1 <= x <= 109` + + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @param {number} x + * @return {number} + */ +var minOperations = function(nums, x) { + var leftSumMap = { 0: 0 }; + var rightSumMap = { 0: 0 }; + var leftSum = 0; + var rightSum = 0; + var min = Number.MAX_SAFE_INTEGER; + for (var i = 0; i < nums.length; i++) { + leftSum += nums[i]; + rightSum += nums[nums.length - 1 - i]; + leftSumMap[leftSum] = i + 1; + rightSumMap[rightSum] = i + 1; + if (rightSumMap[x - leftSum] !== undefined && (i + 1 + rightSumMap[x - leftSum]) <= nums.length) { + min = Math.min(min, i + 1 + rightSumMap[x - leftSum]); + } + if (leftSumMap[x - rightSum] !== undefined && (i + 1 + leftSumMap[x - rightSum]) <= nums.length) { + min = Math.min(min, i + 1 + leftSumMap[x - rightSum]); + } + } + return min === Number.MAX_SAFE_INTEGER ? -1 : min; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n * n). diff --git a/1601-1700/1662. Check If Two String Arrays are Equivalent.md b/1601-1700/1662. Check If Two String Arrays are Equivalent.md new file mode 100644 index 0000000..ee78668 --- /dev/null +++ b/1601-1700/1662. Check If Two String Arrays are Equivalent.md @@ -0,0 +1,93 @@ +# 1662. Check If Two String Arrays are Equivalent + +- Difficulty: Easy. +- Related Topics: Array, String. +- Similar Questions: Check if an Original String Exists Given Two Encoded Strings. + +## Problem + +Given two string arrays `word1` and `word2`, return** **`true`** if the two arrays **represent** the same string, and **`false`** otherwise.** + +A string is **represented** by an array if the array elements concatenated **in order** forms the string. + +  +Example 1: + +``` +Input: word1 = ["ab", "c"], word2 = ["a", "bc"] +Output: true +Explanation: +word1 represents string "ab" + "c" -> "abc" +word2 represents string "a" + "bc" -> "abc" +The strings are the same, so return true. +``` + +Example 2: + +``` +Input: word1 = ["a", "cb"], word2 = ["ab", "c"] +Output: false +``` + +Example 3: + +``` +Input: word1 = ["abc", "d", "defg"], word2 = ["abcddefg"] +Output: true +``` + +  +**Constraints:** + + + +- `1 <= word1.length, word2.length <= 103` + +- `1 <= word1[i].length, word2[i].length <= 103` + +- `1 <= sum(word1[i].length), sum(word2[i].length) <= 103` + +- `word1[i]` and `word2[i]` consist of lowercase letters. + + + +## Solution + +```javascript +/** + * @param {string[]} word1 + * @param {string[]} word2 + * @return {boolean} + */ +var arrayStringsAreEqual = function(word1, word2) { + var i = 0; + var m = 0; + var j = 0; + var n = 0; + while (i < word1.length && j < word2.length) { + if (word1[i][m] !== word2[j][n]) return false; + if (m === word1[i].length - 1) { + i += 1; + m = 0; + } else { + m += 1; + } + if (n === word2[j].length - 1) { + j += 1; + n = 0; + } else { + n += 1; + } + } + return i === word1.length && j === word2.length; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/1601-1700/1685. Sum of Absolute Differences in a Sorted Array.md b/1601-1700/1685. Sum of Absolute Differences in a Sorted Array.md new file mode 100644 index 0000000..982ab69 --- /dev/null +++ b/1601-1700/1685. Sum of Absolute Differences in a Sorted Array.md @@ -0,0 +1,84 @@ +# 1685. Sum of Absolute Differences in a Sorted Array + +- Difficulty: Medium. +- Related Topics: Array, Math, Prefix Sum. +- Similar Questions: . + +## Problem + +You are given an integer array `nums` sorted in **non-decreasing** order. + +Build and return **an integer array **`result`** with the same length as **`nums`** such that **`result[i]`** is equal to the **summation of absolute differences** between **`nums[i]`** and all the other elements in the array.** + +In other words, `result[i]` is equal to `sum(|nums[i]-nums[j]|)` where `0 <= j < nums.length` and `j != i` (**0-indexed**). + +  +Example 1: + +``` +Input: nums = [2,3,5] +Output: [4,3,5] +Explanation: Assuming the arrays are 0-indexed, then +result[0] = |2-2| + |2-3| + |2-5| = 0 + 1 + 3 = 4, +result[1] = |3-2| + |3-3| + |3-5| = 1 + 0 + 2 = 3, +result[2] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5. +``` + +Example 2: + +``` +Input: nums = [1,4,6,8,10] +Output: [24,15,13,15,21] +``` + +  +**Constraints:** + + + +- `2 <= nums.length <= 105` + +- `1 <= nums[i] <= nums[i + 1] <= 104` + + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @return {number[]} + */ +var getSumAbsoluteDifferences = function(nums) { + var diffLeft = Array(nums.length); + for (var i = 0; i < nums.length; i++) { + if (i === 0) { + diffLeft[i] = 0; + } else { + diffLeft[i] = diffLeft[i - 1] + (nums[i] - nums[i - 1]) * i; + } + } + var diffRight = Array(nums.length); + for (var j = nums.length - 1; j >= 0; j--) { + if (j === nums.length - 1) { + diffRight[j] = 0; + } else { + diffRight[j] = diffRight[j + 1] + (nums[j + 1] - nums[j]) * (nums.length - 1 - j); + } + } + var diff = Array(nums.length); + for (var k = 0; k < nums.length; k++) { + diff[k] = diffLeft[k] + diffRight[k]; + } + return diff; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/1601-1700/1688. Count of Matches in Tournament.md b/1601-1700/1688. Count of Matches in Tournament.md new file mode 100644 index 0000000..7ba92ea --- /dev/null +++ b/1601-1700/1688. Count of Matches in Tournament.md @@ -0,0 +1,79 @@ +# 1688. Count of Matches in Tournament + +- Difficulty: Easy. +- Related Topics: Math, Simulation. +- Similar Questions: Count Distinct Numbers on Board. + +## Problem + +You are given an integer `n`, the number of teams in a tournament that has strange rules: + + + +- If the current number of teams is **even**, each team gets paired with another team. A total of `n / 2` matches are played, and `n / 2` teams advance to the next round. + +- If the current number of teams is **odd**, one team randomly advances in the tournament, and the rest gets paired. A total of `(n - 1) / 2` matches are played, and `(n - 1) / 2 + 1` teams advance to the next round. + + +Return **the number of matches played in the tournament until a winner is decided.** + +  +Example 1: + +``` +Input: n = 7 +Output: 6 +Explanation: Details of the tournament: +- 1st Round: Teams = 7, Matches = 3, and 4 teams advance. +- 2nd Round: Teams = 4, Matches = 2, and 2 teams advance. +- 3rd Round: Teams = 2, Matches = 1, and 1 team is declared the winner. +Total number of matches = 3 + 2 + 1 = 6. +``` + +Example 2: + +``` +Input: n = 14 +Output: 13 +Explanation: Details of the tournament: +- 1st Round: Teams = 14, Matches = 7, and 7 teams advance. +- 2nd Round: Teams = 7, Matches = 3, and 4 teams advance. +- 3rd Round: Teams = 4, Matches = 2, and 2 teams advance. +- 4th Round: Teams = 2, Matches = 1, and 1 team is declared the winner. +Total number of matches = 7 + 3 + 2 + 1 = 13. +``` + +  +**Constraints:** + + + +- `1 <= n <= 200` + + + +## Solution + +```javascript +/** + * @param {number} n + * @return {number} + */ +var numberOfMatches = function(n) { + if (n === 1) return 0; + if (n % 2) { + return Math.floor(n / 2) + numberOfMatches((n + 1) / 2); + } else { + return (n / 2) + numberOfMatches(n / 2); + } +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(log(n)). +* Space complexity : O(1). 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/1716. Calculate Money in Leetcode Bank.md b/1701-1800/1716. Calculate Money in Leetcode Bank.md new file mode 100644 index 0000000..d17b32d --- /dev/null +++ b/1701-1800/1716. Calculate Money in Leetcode Bank.md @@ -0,0 +1,74 @@ +# 1716. Calculate Money in Leetcode Bank + +- Difficulty: Easy. +- Related Topics: Math. +- Similar Questions: Distribute Money to Maximum Children. + +## Problem + +Hercy wants to save money for his first car. He puts money in the Leetcode bank **every day**. + +He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put in `$1` more than the day before. On every subsequent Monday, he will put in `$1` more than the **previous Monday**. + +Given `n`, return **the total amount of money he will have in the Leetcode bank at the end of the **`nth`** day.** + +  +Example 1: + +``` +Input: n = 4 +Output: 10 +Explanation: After the 4th day, the total is 1 + 2 + 3 + 4 = 10. +``` + +Example 2: + +``` +Input: n = 10 +Output: 37 +Explanation: After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts in $2. +``` + +Example 3: + +``` +Input: n = 20 +Output: 96 +Explanation: After the 20th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96. +``` + +  +**Constraints:** + + + +- `1 <= n <= 1000` + + + +## Solution + +```javascript +/** + * @param {number} n + * @return {number} + */ +var totalMoney = function(n) { + var weeks = Math.floor(n / 7); + var lastWeekDays = n % 7; + var sumOfWeeks = (4 + 4 + weeks - 1) * 7 * weeks / 2; + var sumOfLastDays = Array(lastWeekDays).fill(0).reduce((sum, _, i) => { + return sum + (i + 1) + weeks; + }, 0); + return sumOfWeeks + sumOfLastDays; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(1). +* 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/1718. Construct the Lexicographically Largest Valid Sequence.md b/1701-1800/1718. Construct the Lexicographically Largest Valid Sequence.md new file mode 100644 index 0000000..e45cdc5 --- /dev/null +++ b/1701-1800/1718. Construct the Lexicographically Largest Valid Sequence.md @@ -0,0 +1,89 @@ +# 1718. Construct the Lexicographically Largest Valid Sequence + +- Difficulty: Medium. +- Related Topics: Array, Backtracking. +- Similar Questions: The Number of Beautiful Subsets. + +## Problem + +Given an integer `n`, find a sequence that satisfies all of the following: + + + +- The integer `1` occurs once in the sequence. + +- Each integer between `2` and `n` occurs twice in the sequence. + +- For every integer `i` between `2` and `n`, the **distance** between the two occurrences of `i` is exactly `i`. + + +The **distance** between two numbers on the sequence, `a[i]` and `a[j]`, is the absolute difference of their indices, `|j - i|`. + +Return **the **lexicographically largest** sequence****. It is guaranteed that under the given constraints, there is always a solution. ** + +A sequence `a` is lexicographically larger than a sequence `b` (of the same length) if in the first position where `a` and `b` differ, sequence `a` has a number greater than the corresponding number in `b`. For example, `[0,1,9,0]` is lexicographically larger than `[0,1,5,6]` because the first position they differ is at the third number, and `9` is greater than `5`. + +  +Example 1: + +``` +Input: n = 3 +Output: [3,1,2,3,2] +Explanation: [2,3,2,1,3] is also a valid sequence, but [3,1,2,3,2] is the lexicographically largest valid sequence. +``` + +Example 2: + +``` +Input: n = 5 +Output: [5,3,1,4,3,5,2,4,2] +``` + +  +**Constraints:** + + + +- `1 <= n <= 20` + + + +## Solution + +```javascript +/** + * @param {number} n + * @return {number[]} + */ +var constructDistancedSequence = function(n) { + return dfs(n, Array(n), Array(n * 2 - 1), 0); +}; + +var dfs = function(n, used, res, m) { + if (m >= res.length) return res; + if (res[m]) return dfs(n, used, res, m + 1); + for (var i = n; i > 0; i--) { + if (used[i - 1]) continue; + if (i !== 1 && res[m + i]) continue; + if (m + i >= res.length && i !== 1) continue; + used[i - 1] = 1; + res[m] = i; + if (i !== 1) res[m + i] = i; + var tmp = dfs(n, used, res, m + 1); + if (tmp) return tmp; + used[i - 1] = 0; + res[m] = 0; + if (i !== 1) res[m + i] = 0; + } + return null; +}; +``` + +**Explain:** + +Backtrack and DFS. + +**Complexity:** + +* Time complexity : O(n * n). +* Space complexity : O(n). diff --git a/1701-1800/1719. Number Of Ways To Reconstruct A Tree.md b/1701-1800/1719. Number Of Ways To Reconstruct A Tree.md new file mode 100644 index 0000000..d073055 --- /dev/null +++ b/1701-1800/1719. Number Of Ways To Reconstruct A Tree.md @@ -0,0 +1,143 @@ +# 1719. Number Of Ways To Reconstruct A Tree + +- Difficulty: Hard. +- Related Topics: Tree, Graph. +- Similar Questions: Create Binary Tree From Descriptions, Maximum Star Sum of a Graph. + +## Problem + +You are given an array `pairs`, where `pairs[i] = [xi, yi]`, and: + + + +- There are no duplicates. + +- `xi < yi` + + +Let `ways` be the number of rooted trees that satisfy the following conditions: + + + +- The tree consists of nodes whose values appeared in `pairs`. + +- A pair `[xi, yi]` exists in `pairs` **if and only if** `xi` is an ancestor of `yi` or `yi` is an ancestor of `xi`. + +- **Note:** the tree does not have to be a binary tree. + + +Two ways are considered to be different if there is at least one node that has different parents in both ways. + +Return: + + + +- `0` if `ways == 0` + +- `1` if `ways == 1` + +- `2` if `ways > 1` + + +A **rooted tree** is a tree that has a single root node, and all edges are oriented to be outgoing from the root. + +An **ancestor** of a node is any node on the path from the root to that node (excluding the node itself). The root has no ancestors. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2020/12/03/trees2.png) + +``` +Input: pairs = [[1,2],[2,3]] +Output: 1 +Explanation: There is exactly one valid rooted tree, which is shown in the above figure. +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2020/12/03/tree.png) + +``` +Input: pairs = [[1,2],[2,3],[1,3]] +Output: 2 +Explanation: There are multiple valid rooted trees. Three of them are shown in the above figures. +``` + +Example 3: + +``` +Input: pairs = [[1,2],[2,3],[2,4],[1,5]] +Output: 0 +Explanation: There are no valid rooted trees. +``` + +  +**Constraints:** + + + +- `1 <= pairs.length <= 105` + +- `1 <= xi < yi <= 500` + +- The elements in `pairs` are unique. + + + +## Solution + +```javascript +/** + * @param {number[][]} pairs + * @return {number} + */ +var checkWays = function(pairs) { + var map = {}; + for (var i = 0; i < pairs.length; i++) { + var [x, y] = pairs[i]; + if (!map[x]) map[x] = []; + if (!map[y]) map[y] = []; + map[x].push(y); + map[y].push(x); + } + var nums = Object.keys(map).sort((a, b) => map[a].length - map[b].length); + var visited = {}; + var result = 1; + for (var i = nums.length - 1; i >= 0; i--) { + var num = nums[i]; + var parentDegree = Number.MAX_SAFE_INTEGER; + var parent = -1; + for (var j = 0; j < map[num].length; j++) { + var n = map[num][j]; + if (visited[n] && map[n].length >= map[num].length && map[n].length < parentDegree) { + parentDegree = map[n].length; + parent = n; + } + } + visited[num] = true; + if (parent === -1) { + if (map[num].length === nums.length - 1) continue; + return 0; + } + for (var j = 0; j < map[num].length; j++) { + if (map[num][j] !== parent && !map[parent].includes(map[num][j])) { + return 0; + } + } + if (map[parent].length === map[num].length) { + result = 2; + } + } + return result; +}; +``` + +**Explain:** + +see https://leetcode.com/problems/number-of-ways-to-reconstruct-a-tree/solutions/1009393/c-o-nlogn-soln-with-comments-descriptive-variable-naming-time-space-complexity-analysis/ + +**Complexity:** + +* Time complexity : O(n ^ 2). +* Space complexity : O(n ^ 2). diff --git a/1701-1800/1721. Swapping Nodes in a Linked List.md b/1701-1800/1721. Swapping Nodes in a Linked List.md new file mode 100644 index 0000000..d01f9ed --- /dev/null +++ b/1701-1800/1721. Swapping Nodes in a Linked List.md @@ -0,0 +1,85 @@ +# 1721. Swapping Nodes in a Linked List + +- Difficulty: Medium. +- Related Topics: Linked List, Two Pointers. +- Similar Questions: Remove Nth Node From End of List, Swap Nodes in Pairs, Reverse Nodes in k-Group. + +## Problem + +You are given the `head` of a linked list, and an integer `k`. + +Return **the head of the linked list after **swapping** the values of the **`kth` **node from the beginning and the **`kth` **node from the end (the list is **1-indexed**).** + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2020/09/21/linked1.jpg) + +``` +Input: head = [1,2,3,4,5], k = 2 +Output: [1,4,3,2,5] +``` + +Example 2: + +``` +Input: head = [7,9,6,6,7,8,3,0,9,5], k = 5 +Output: [7,9,6,6,8,7,3,0,9,5] +``` + +  +**Constraints:** + + + +- The number of nodes in the list is `n`. + +- `1 <= k <= n <= 105` + +- `0 <= Node.val <= 100` + + + +## 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 swapNodes = function(head, k) { + if (!head) { + return null; + } + let left = head, right = head; + for (let i = 1; i < k; i++) { + left = left.next; + } + let curr = left; + while (curr.next) { + curr = curr.next; + right = right.next; + } + let temp = left.val; + left.val = right.val; + right.val = temp; + return head; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/1701-1800/1727. Largest Submatrix With Rearrangements.md b/1701-1800/1727. Largest Submatrix With Rearrangements.md new file mode 100644 index 0000000..9f8a55f --- /dev/null +++ b/1701-1800/1727. Largest Submatrix With Rearrangements.md @@ -0,0 +1,144 @@ +# 1727. Largest Submatrix With Rearrangements + +- Difficulty: Medium. +- Related Topics: Array, Greedy, Sorting, Matrix. +- Similar Questions: Max Area of Island. + +## Problem + +You are given a binary matrix `matrix` of size `m x n`, and you are allowed to rearrange the **columns** of the `matrix` in any order. + +Return **the area of the largest submatrix within **`matrix`** where **every** element of the submatrix is **`1`** after reordering the columns optimally.** + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2020/12/29/screenshot-2020-12-30-at-40536-pm.png) + +``` +Input: matrix = [[0,0,1],[1,1,1],[1,0,1]] +Output: 4 +Explanation: You can rearrange the columns as shown above. +The largest submatrix of 1s, in bold, has an area of 4. +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2020/12/29/screenshot-2020-12-30-at-40852-pm.png) + +``` +Input: matrix = [[1,0,1,0,1]] +Output: 3 +Explanation: You can rearrange the columns as shown above. +The largest submatrix of 1s, in bold, has an area of 3. +``` + +Example 3: + +``` +Input: matrix = [[1,1,0],[1,0,1]] +Output: 2 +Explanation: Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2. +``` + +  +**Constraints:** + + + +- `m == matrix.length` + +- `n == matrix[i].length` + +- `1 <= m * n <= 105` + +- `matrix[i][j]` is either `0` or `1`. + + + +## Solution 1 + +```javascript +/** + * @param {number[][]} matrix + * @return {number} + */ +var largestSubmatrix = function(matrix) { + var max = 0; + for (var i = 0; i < matrix.length; i++) { + for (var j = 0; j < matrix[i].length; j++) { + if (matrix[i][j] !== 0 && i > 0) { + matrix[i][j] = matrix[i - 1][j] + 1; + } + } + var arr = [...matrix[i]].sort((a, b) => b - a); + for (var j = 0; j < arr.length; j++) { + if (arr[j] === 0) break; + max = Math.max(max, arr[j] * (j + 1)); + } + } + return max; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * m * log(m)). +* Space complexity : O(1). + +## Solution 2 + +```javascript +/** + * @param {number[][]} matrix + * @return {number} + */ +var largestSubmatrix = function(matrix) { + var max = 0; + var lastHeights = []; + for (var i = 0; i < matrix.length; i++) { + var seen = {}; + for (var j = 0; j < matrix[i].length; j++) { + if (matrix[i][j] === 1) { + i > 0 && (matrix[i][j] = matrix[i - 1][j] + 1); + seen[j] = true; + } + } + var heights = []; + // old ones + var used = {}; + for (var k = 0; k < lastHeights.length; k++) { + var item = lastHeights[k]; + if (seen[item[1]]) { + heights.push([item[0] + 1, item[1]]); + used[item[1]] = true; + } + } + // new ones + var keys = Object.keys(seen); + for (var n = 0; n < keys.length; n++) { + if (!used[keys[n]]) { + heights.push([1, Number(keys[n])]); + } + } + for (var m = 0; m < heights.length; m++) { + max = Math.max(max, heights[m][0] * (m + 1)); + } + lastHeights = heights; + } + return max; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * m). +* Space complexity : O(m). diff --git a/1701-1800/1732. Find the Highest Altitude.md b/1701-1800/1732. Find the Highest Altitude.md new file mode 100644 index 0000000..c68b0c3 --- /dev/null +++ b/1701-1800/1732. Find the Highest Altitude.md @@ -0,0 +1,68 @@ +# 1732. Find the Highest Altitude + +- Difficulty: Easy. +- Related Topics: Array, Prefix Sum. +- Similar Questions: . + +## Problem + +There is a biker going on a road trip. The road trip consists of `n + 1` points at different altitudes. The biker starts his trip on point `0` with altitude equal `0`. + +You are given an integer array `gain` of length `n` where `gain[i]` is the **net gain in altitude** between points `i`​​​​​​ and `i + 1` for all (`0 <= i < n)`. Return **the **highest altitude** of a point.** + +  +Example 1: + +``` +Input: gain = [-5,1,5,0,-7] +Output: 1 +Explanation: The altitudes are [0,-5,-4,1,1,-6]. The highest is 1. +``` + +Example 2: + +``` +Input: gain = [-4,-3,-2,-1,4,3,2] +Output: 0 +Explanation: The altitudes are [0,-4,-7,-9,-10,-6,-3,-1]. The highest is 0. +``` + +  +**Constraints:** + + + +- `n == gain.length` + +- `1 <= n <= 100` + +- `-100 <= gain[i] <= 100` + + + +## Solution + +```javascript +/** + * @param {number[]} gain + * @return {number} + */ +var largestAltitude = function(gain) { + var max = 0; + var cur = 0; + for (var i = 0; i < gain.length; i++) { + cur += gain[i]; + max = Math.max(max, cur); + } + return max; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/1701-1800/1743. Restore the Array From Adjacent Pairs.md b/1701-1800/1743. Restore the Array From Adjacent Pairs.md new file mode 100644 index 0000000..562b32f --- /dev/null +++ b/1701-1800/1743. Restore the Array From Adjacent Pairs.md @@ -0,0 +1,98 @@ +# 1743. Restore the Array From Adjacent Pairs + +- Difficulty: Medium. +- Related Topics: Array, Hash Table. +- Similar Questions: . + +## Problem + +There is an integer array `nums` that consists of `n` **unique **elements, but you have forgotten it. However, you do remember every pair of adjacent elements in `nums`. + +You are given a 2D integer array `adjacentPairs` of size `n - 1` where each `adjacentPairs[i] = [ui, vi]` indicates that the elements `ui` and `vi` are adjacent in `nums`. + +It is guaranteed that every adjacent pair of elements `nums[i]` and `nums[i+1]` will exist in `adjacentPairs`, either as `[nums[i], nums[i+1]]` or `[nums[i+1], nums[i]]`. The pairs can appear **in any order**. + +Return **the original array **`nums`**. If there are multiple solutions, return **any of them****. + +  +Example 1: + +``` +Input: adjacentPairs = [[2,1],[3,4],[3,2]] +Output: [1,2,3,4] +Explanation: This array has all its adjacent pairs in adjacentPairs. +Notice that adjacentPairs[i] may not be in left-to-right order. +``` + +Example 2: + +``` +Input: adjacentPairs = [[4,-2],[1,4],[-3,1]] +Output: [-2,4,1,-3] +Explanation: There can be negative numbers. +Another solution is [-3,1,4,-2], which would also be accepted. +``` + +Example 3: + +``` +Input: adjacentPairs = [[100000,-100000]] +Output: [100000,-100000] +``` + +  +**Constraints:** + + + +- `nums.length == n` + +- `adjacentPairs.length == n - 1` + +- `adjacentPairs[i].length == 2` + +- `2 <= n <= 105` + +- `-105 <= nums[i], ui, vi <= 105` + +- There exists some `nums` that has `adjacentPairs` as its pairs. + + + +## Solution + +```javascript +/** + * @param {number[][]} adjacentPairs + * @return {number[]} + */ +var restoreArray = function(adjacentPairs) { + var map = {}; + for (var i = 0 ; i < adjacentPairs.length; i++) { + map[adjacentPairs[i][0]] = map[adjacentPairs[i][0]] || []; + map[adjacentPairs[i][1]] = map[adjacentPairs[i][1]] || []; + map[adjacentPairs[i][0]].push(adjacentPairs[i][1]); + map[adjacentPairs[i][1]].push(adjacentPairs[i][0]); + } + var root = Number(Object.keys(map).find(num => map[num].length === 1)); + var res = [root]; + var last = root; + var now = map[root][0]; + while (now !== undefined) { + var next = map[now][0] === last ? map[now][1] : map[now][0]; + res.push(now); + last = now; + now = next; + } + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). 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/1751. Maximum Number of Events That Can Be Attended II.md b/1701-1800/1751. Maximum Number of Events That Can Be Attended II.md new file mode 100644 index 0000000..cd6b87f --- /dev/null +++ b/1701-1800/1751. Maximum Number of Events That Can Be Attended II.md @@ -0,0 +1,156 @@ +# 1751. Maximum Number of Events That Can Be Attended II + +- Difficulty: Hard. +- Related Topics: Array, Binary Search, Dynamic Programming, Sorting. +- Similar Questions: Maximum Number of Events That Can Be Attended, Maximum Earnings From Taxi, Two Best Non-Overlapping Events, Meeting Rooms III. + +## Problem + +You are given an array of `events` where `events[i] = [startDayi, endDayi, valuei]`. The `ith` event starts at `startDayi` and ends at `endDayi`, and if you attend this event, you will receive a value of `valuei`. You are also given an integer `k` which represents the maximum number of events you can attend. + +You can only attend one event at a time. If you choose to attend an event, you must attend the **entire** event. Note that the end day is **inclusive**: that is, you cannot attend two events where one of them starts and the other ends on the same day. + +Return **the **maximum sum** of values that you can receive by attending events.** + +  +Example 1: + + +![](https://assets.leetcode.com/uploads/2021/01/10/screenshot-2021-01-11-at-60048-pm.png) + + +``` +Input: events = [[1,2,4],[3,4,3],[2,3,1]], k = 2 +Output: 7 +Explanation: Choose the green events, 0 and 1 (0-indexed) for a total value of 4 + 3 = 7. +``` + +Example 2: + + +![](https://assets.leetcode.com/uploads/2021/01/10/screenshot-2021-01-11-at-60150-pm.png) + + +``` +Input: events = [[1,2,4],[3,4,3],[2,3,10]], k = 2 +Output: 10 +Explanation: Choose event 2 for a total value of 10. +Notice that you cannot attend any other event as they overlap, and that you do not have to attend k events. +``` + +Example 3: + + +![](https://assets.leetcode.com/uploads/2021/01/10/screenshot-2021-01-11-at-60703-pm.png) + + +``` +Input: events = [[1,1,1],[2,2,2],[3,3,3],[4,4,4]], k = 3 +Output: 9 +Explanation: Although the events do not overlap, you can only attend 3 events. Pick the highest valued three. +``` + +  +**Constraints:** + + + +- `1 <= k <= events.length` + +- `1 <= k * events.length <= 106` + +- `1 <= startDayi <= endDayi <= 109` + +- `1 <= valuei <= 106` + + + +## Solution + +```javascript +/** + * @param {number[][]} events + * @param {number} k + * @return {number} + */ +var maxValue = function(events, k) { + var dp = Array(events.length).fill(0).map(() => Array(k)); + events.sort((a, b) => a[0] - b[0]); + return dfs(events, k, dp, 0, 0); +}; + +var dfs = function(events, k, dp, index, count) { + if (count >= k || index >= events.length || index < 0) return 0; + if (dp[index][count] !== undefined) return dp[index][count]; + dp[index][count] = Math.max( + dfs(events, k, dp, index + 1, count), + events[index][2] + dfs(events, k, dp, find(events, index), count + 1) + ); + return dp[index][count]; +}; + +var find = function(events, index) { + for (var i = index + 1; i < events.length; i++) { + if (events[i][0] > events[index][1]) return i; + } + return -1; +}; +``` + +**Explain:** + +DFS with DP. + +**Complexity:** + +* Time complexity : O(k * n * n). +* Space complexity : O(k * n). + +## Solution 2 + +```javascript +/** + * @param {number[][]} events + * @param {number} k + * @return {number} + */ +var maxValue = function(events, k) { + var dp = Array(events.length).fill(0).map(() => Array(k)); + events.sort((a, b) => a[0] - b[0]); + return dfs(events, k, dp, 0, 0); +}; + +var dfs = function(events, k, dp, index, count) { + if (count >= k || index >= events.length || index < 0) return 0; + if (dp[index][count] !== undefined) return dp[index][count]; + dp[index][count] = Math.max( + dfs(events, k, dp, index + 1, count), + events[index][2] + dfs(events, k, dp, find(events, index), count + 1) + ); + return dp[index][count]; +}; + +var find = function(events, index) { + var left = index + 1; + var right = events.length - 1; + while (left <= right) { + var mid = left + Math.floor((right - left) / 2); + if (events[mid][0] > events[index][1]) { + if (right === left) return mid; + right = mid; + } else { + left = mid + 1; + } + } + return -1; +}; +``` + +**Explain:** + +DFS with DP and Binary Search. + +**Complexity:** + +* Time complexity : O(k * n * log(n)). +* Space complexity : O(k * n). diff --git a/1701-1800/1752. Check if Array Is Sorted and Rotated.md b/1701-1800/1752. Check if Array Is Sorted and Rotated.md new file mode 100644 index 0000000..8903628 --- /dev/null +++ b/1701-1800/1752. Check if Array Is Sorted and Rotated.md @@ -0,0 +1,83 @@ +# 1752. Check if Array Is Sorted and Rotated + +- Difficulty: Easy. +- Related Topics: Array. +- Similar Questions: Check if All A's Appears Before All B's. + +## Problem + +Given an array `nums`, return `true`** if the array was originally sorted in non-decreasing order, then rotated **some** number of positions (including zero)**. Otherwise, return `false`. + +There may be **duplicates** in the original array. + +**Note:** An array `A` rotated by `x` positions results in an array `B` of the same length such that `A[i] == B[(i+x) % A.length]`, where `%` is the modulo operation. + +  +Example 1: + +``` +Input: nums = [3,4,5,1,2] +Output: true +Explanation: [1,2,3,4,5] is the original sorted array. +You can rotate the array by x = 3 positions to begin on the the element of value 3: [3,4,5,1,2]. +``` + +Example 2: + +``` +Input: nums = [2,1,3,4] +Output: false +Explanation: There is no sorted array once rotated that can make nums. +``` + +Example 3: + +``` +Input: nums = [1,2,3] +Output: true +Explanation: [1,2,3] is the original sorted array. +You can rotate the array by x = 0 positions (i.e. no rotation) to make nums. +``` + +  +**Constraints:** + + + +- `1 <= nums.length <= 100` + +- `1 <= nums[i] <= 100` + + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @return {boolean} + */ +var check = function(nums) { + let hasBreak = false; + for (var i = 0; i < nums.length - 1; i++) { + if (nums[i + 1] < nums[i]) { + if (hasBreak) return false; + if (nums[i + 1] <= nums[0] && nums[nums.length - 1] <= nums[0]) { + hasBreak = true; + continue; + } + return false; + } + } + return true; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/1701-1800/1759. Count Number of Homogenous Substrings.md b/1701-1800/1759. Count Number of Homogenous Substrings.md new file mode 100644 index 0000000..0b733cd --- /dev/null +++ b/1701-1800/1759. Count Number of Homogenous Substrings.md @@ -0,0 +1,86 @@ +# 1759. Count Number of Homogenous Substrings + +- Difficulty: Medium. +- Related Topics: Math, String. +- Similar Questions: Consecutive Characters, Number of Substrings With Only 1s, Sum of Subarray Ranges, Count the Number of Good Subarrays. + +## Problem + +Given a string `s`, return **the number of **homogenous** substrings of **`s`**.** Since the answer may be too large, return it **modulo** `109 + 7`. + +A string is **homogenous** if all the characters of the string are the same. + +A **substring** is a contiguous sequence of characters within a string. + +  +Example 1: + +``` +Input: s = "abbcccaa" +Output: 13 +Explanation: The homogenous substrings are listed as below: +"a" appears 3 times. +"aa" appears 1 time. +"b" appears 2 times. +"bb" appears 1 time. +"c" appears 3 times. +"cc" appears 2 times. +"ccc" appears 1 time. +3 + 1 + 2 + 1 + 3 + 2 + 1 = 13. +``` + +Example 2: + +``` +Input: s = "xy" +Output: 2 +Explanation: The homogenous substrings are "x" and "y". +``` + +Example 3: + +``` +Input: s = "zzzzz" +Output: 15 +``` + +  +**Constraints:** + + + +- `1 <= s.length <= 105` + +- `s` consists of lowercase letters. + + +## Solution + +```javascript +/** + * @param {string} s + * @return {number} + */ +var countHomogenous = function(s) { + var startIndex = 0; + var sum = 0; + var mod = Math.pow(10, 9) + 7; + for (var i = 0; i < s.length; i++) { + if (s[i] === s[i + 1]) continue; + var num = i - startIndex + 1; + sum += ((1 + num) * num / 2) % mod; + sum %= mod; + startIndex = i + 1; + } + return sum; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/1701-1800/1761. Minimum Degree of a Connected Trio in a Graph.md b/1701-1800/1761. Minimum Degree of a Connected Trio in a Graph.md new file mode 100644 index 0000000..f5365a8 --- /dev/null +++ b/1701-1800/1761. Minimum Degree of a Connected Trio in a Graph.md @@ -0,0 +1,112 @@ +# 1761. Minimum Degree of a Connected Trio in a Graph + +- Difficulty: Hard. +- Related Topics: Graph. +- Similar Questions: Add Edges to Make Degrees of All Nodes Even. + +## Problem + +You are given an undirected graph. You are given an integer `n` which is the number of nodes in the graph and an array `edges`, where each `edges[i] = [ui, vi]` indicates that there is an undirected edge between `ui` and `vi`. + +A **connected trio** is a set of **three** nodes where there is an edge between **every** pair of them. + +The **degree of a connected trio** is the number of edges where one endpoint is in the trio, and the other is not. + +Return **the **minimum** degree of a connected trio in the graph, or** `-1` **if the graph has no connected trios.** + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2021/01/26/trios1.png) + +``` +Input: n = 6, edges = [[1,2],[1,3],[3,2],[4,1],[5,2],[3,6]] +Output: 3 +Explanation: There is exactly one trio, which is [1,2,3]. The edges that form its degree are bolded in the figure above. +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2021/01/26/trios2.png) + +``` +Input: n = 7, edges = [[1,3],[4,1],[4,3],[2,5],[5,6],[6,7],[7,5],[2,6]] +Output: 0 +Explanation: There are exactly three trios: +1) [1,4,3] with degree 0. +2) [2,5,6] with degree 2. +3) [5,6,7] with degree 2. +``` + +  +**Constraints:** + + + +- `2 <= n <= 400` + +- `edges[i].length == 2` + +- `1 <= edges.length <= n * (n-1) / 2` + +- `1 <= ui, vi <= n` + +- `ui != vi` + +- There are no repeated edges. + + + +## Solution + +```javascript +/** + * @param {number} n + * @param {number[][]} edges + * @return {number} + */ +var minTrioDegree = function(n, edges) { + var { map, lenMap } = buildMap(n, edges); + var res = Number.MAX_SAFE_INTEGER; + for (var i = 0; i < map.length; i++) { + var arr = Object.keys(map[i]); + for (var j = 0; j < arr.length; j++) { + var m = arr[j]; + if (m < i) continue; + for (var k = j + 1; k < arr.length; k++) { + var n = arr[k]; + if (n < i) continue; + if (map[m][n]) { + res = Math.min( + res, + arr.length - 2 + lenMap[m] - 2 + lenMap[n] - 2, + ); + } + } + } + } + return res === Number.MAX_SAFE_INTEGER ? -1 : res; +}; + +var buildMap = function(n, edges) { + var map = Array(n + 1).fill(0).map(() => ({})); + var lenMap = Array(n + 1).fill(0); + for (var i = 0; i < edges.length; i++) { + var [m, n] = edges[i]; + map[m][n] = 1; + map[n][m] = 1; + lenMap[n]++; + lenMap[m]++; + } + return { map, lenMap }; +}; +``` + +**Explain:** + +Brute-force with hashmap. + +**Complexity:** + +* Time complexity : O(n ^ 3). +* Space complexity : O(n ^ 2). diff --git a/1701-1800/1774. Closest Dessert Cost.md b/1701-1800/1774. Closest Dessert Cost.md new file mode 100644 index 0000000..7644136 --- /dev/null +++ b/1701-1800/1774. Closest Dessert Cost.md @@ -0,0 +1,128 @@ +# 1774. Closest Dessert Cost + +- Difficulty: Medium. +- Related Topics: Array, Dynamic Programming, Backtracking. +- Similar Questions: . + +## Problem + +You would like to make dessert and are preparing to buy the ingredients. You have `n` ice cream base flavors and `m` types of toppings to choose from. You must follow these rules when making your dessert: + + + +- There must be **exactly one** ice cream base. + +- You can add **one or more** types of topping or have no toppings at all. + +- There are **at most two** of **each type** of topping. + + +You are given three inputs: + + + +- `baseCosts`, an integer array of length `n`, where each `baseCosts[i]` represents the price of the `ith` ice cream base flavor. + +- `toppingCosts`, an integer array of length `m`, where each `toppingCosts[i]` is the price of **one** of the `ith` topping. + +- `target`, an integer representing your target price for dessert. + + +You want to make a dessert with a total cost as close to `target` as possible. + +Return **the closest possible cost of the dessert to **`target`. If there are multiple, return **the **lower** one.** + +  +Example 1: + +``` +Input: baseCosts = [1,7], toppingCosts = [3,4], target = 10 +Output: 10 +Explanation: Consider the following combination (all 0-indexed): +- Choose base 1: cost 7 +- Take 1 of topping 0: cost 1 x 3 = 3 +- Take 0 of topping 1: cost 0 x 4 = 0 +Total: 7 + 3 + 0 = 10. +``` + +Example 2: + +``` +Input: baseCosts = [2,3], toppingCosts = [4,5,100], target = 18 +Output: 17 +Explanation: Consider the following combination (all 0-indexed): +- Choose base 1: cost 3 +- Take 1 of topping 0: cost 1 x 4 = 4 +- Take 2 of topping 1: cost 2 x 5 = 10 +- Take 0 of topping 2: cost 0 x 100 = 0 +Total: 3 + 4 + 10 + 0 = 17. You cannot make a dessert with a total cost of 18. +``` + +Example 3: + +``` +Input: baseCosts = [3,10], toppingCosts = [2,5], target = 9 +Output: 8 +Explanation: It is possible to make desserts with cost 8 and 10. Return 8 as it is the lower cost. +``` + +  +**Constraints:** + + + +- `n == baseCosts.length` + +- `m == toppingCosts.length` + +- `1 <= n, m <= 10` + +- `1 <= baseCosts[i], toppingCosts[i] <= 104` + +- `1 <= target <= 104` + + + +## Solution + +```javascript +/** + * @param {number[]} baseCosts + * @param {number[]} toppingCosts + * @param {number} target + * @return {number} + */ +var closestCost = function(baseCosts, toppingCosts, target) { + var res = Number.MAX_SAFE_INTEGER; + for (var i = 0; i < baseCosts.length; i++) { + res = closest(target, res, baseCosts[i] + helper(toppingCosts, target - baseCosts[i], 0)); + } + return res; +}; + +var helper = function(toppingCosts, target, i) { + if (i === toppingCosts.length) return 0; + if (target <= 0) return 0; + var res = Number.MAX_SAFE_INTEGER; + res = closest(target, res, helper(toppingCosts, target, i + 1)); + res = closest(target, res, toppingCosts[i] + helper(toppingCosts, target - toppingCosts[i], i + 1)); + res = closest(target, res, toppingCosts[i] * 2 + helper(toppingCosts, target - toppingCosts[i] * 2, i + 1)); + return res; +}; + +var closest = function(target, num1, num2) { + var diff1 = Math.abs(num1 - target); + var diff2 = Math.abs(num2 - target); + if (diff1 === diff2) return Math.min(num1, num2); + return diff1 < diff2 ? num1 : num2; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * m ^ 3). +* Space complexity : O(m). 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/1701-1800/1800. Maximum Ascending Subarray Sum.md b/1701-1800/1800. Maximum Ascending Subarray Sum.md new file mode 100644 index 0000000..5908683 --- /dev/null +++ b/1701-1800/1800. Maximum Ascending Subarray Sum.md @@ -0,0 +1,80 @@ +# 1800. Maximum Ascending Subarray Sum + +- Difficulty: Easy. +- Related Topics: Array. +- Similar Questions: Find Good Days to Rob the Bank, Maximum Number of Books You Can Take, Count Strictly Increasing Subarrays. + +## Problem + +Given an array of positive integers `nums`, return the **maximum possible sum of an **ascending** subarray in **`nums`. + +A subarray is defined as a contiguous sequence of numbers in an array. + +A subarray `[numsl, numsl+1, ..., numsr-1, numsr]` is **ascending** if for all `i` where `l <= i < r`, `numsi < numsi+1`. Note that a subarray of size `1` is **ascending**. + +  +Example 1: + +``` +Input: nums = [10,20,30,5,10,50] +Output: 65 +Explanation: [5,10,50] is the ascending subarray with the maximum sum of 65. +``` + +Example 2: + +``` +Input: nums = [10,20,30,40,50] +Output: 150 +Explanation: [10,20,30,40,50] is the ascending subarray with the maximum sum of 150. +``` + +Example 3: + +``` +Input: nums = [12,17,15,13,10,11,12] +Output: 33 +Explanation: [10,11,12] is the ascending subarray with the maximum sum of 33. +``` + +  +**Constraints:** + + + +- `1 <= nums.length <= 100` + +- `1 <= nums[i] <= 100` + + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @return {number} + */ +var maxAscendingSum = function(nums) { + var maxSum = nums[0]; + var currSum = nums[0]; + for (var i = 1; i < nums.length; i++) { + if (nums[i - 1] < nums[i]) { + currSum += nums[i]; + } else { + maxSum = Math.max(maxSum, currSum); + currSum = nums[i]; + } + } + return Math.max(maxSum, currSum); +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/1801-1900/1814. Count Nice Pairs in an Array.md b/1801-1900/1814. Count Nice Pairs in an Array.md new file mode 100644 index 0000000..d9d3b28 --- /dev/null +++ b/1801-1900/1814. Count Nice Pairs in an Array.md @@ -0,0 +1,83 @@ +# 1814. Count Nice Pairs in an Array + +- Difficulty: Medium. +- Related Topics: Array, Hash Table, Math, Counting. +- Similar Questions: Number of Pairs of Interchangeable Rectangles, Count Number of Bad Pairs, Number of Pairs Satisfying Inequality. + +## Problem + +You are given an array `nums` that consists of non-negative integers. Let us define `rev(x)` as the reverse of the non-negative integer `x`. For example, `rev(123) = 321`, and `rev(120) = 21`. A pair of indices `(i, j)` is **nice** if it satisfies all of the following conditions: + + + +- `0 <= i < j < nums.length` + +- `nums[i] + rev(nums[j]) == nums[j] + rev(nums[i])` + + +Return **the number of nice pairs of indices**. Since that number can be too large, return it **modulo** `109 + 7`. + +  +Example 1: + +``` +Input: nums = [42,11,1,97] +Output: 2 +Explanation: The two pairs are: + - (0,3) : 42 + rev(97) = 42 + 79 = 121, 97 + rev(42) = 97 + 24 = 121. + - (1,2) : 11 + rev(1) = 11 + 1 = 12, 1 + rev(11) = 1 + 11 = 12. +``` + +Example 2: + +``` +Input: nums = [13,10,35,24,76] +Output: 4 +``` + +  +**Constraints:** + + + +- `1 <= nums.length <= 105` + +- `0 <= nums[i] <= 109` + + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @return {number} + */ +var countNicePairs = function(nums) { + var diffArray = nums.map(num => { + var rev = Number(String(num).split('').reverse().join('')); + return num - rev; + }).sort((a, b) => a - b); + var tmp = 0; + var res = 0; + var mod = Math.pow(10, 9) + 7; + for (var i = 0; i < diffArray.length; i++) { + tmp += 1; + if (diffArray[i + 1] !== diffArray[i]) { + res += tmp * (tmp - 1) / 2; + res %= mod; + tmp = 0; + } + } + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * log(n)). +* Space complexity : O(n). diff --git a/1801-1900/1822. Sign of the Product of an Array.md b/1801-1900/1822. Sign of the Product of an Array.md new file mode 100644 index 0000000..88ca104 --- /dev/null +++ b/1801-1900/1822. Sign of the Product of an Array.md @@ -0,0 +1,83 @@ +# 1822. Sign of the Product of an Array + +- Difficulty: Easy. +- Related Topics: Array, Math. +- Similar Questions: . + +## Problem + +There is a function `signFunc(x)` that returns: + + + +- `1` if `x` is positive. + +- `-1` if `x` is negative. + +- `0` if `x` is equal to `0`. + + +You are given an integer array `nums`. Let `product` be the product of all values in the array `nums`. + +Return `signFunc(product)`. + +  +Example 1: + +``` +Input: nums = [-1,-2,-3,-4,3,2,1] +Output: 1 +Explanation: The product of all values in the array is 144, and signFunc(144) = 1 +``` + +Example 2: + +``` +Input: nums = [1,5,0,2,-3] +Output: 0 +Explanation: The product of all values in the array is 0, and signFunc(0) = 0 +``` + +Example 3: + +``` +Input: nums = [-1,1,-1,1,-1] +Output: -1 +Explanation: The product of all values in the array is -1, and signFunc(-1) = -1 +``` + +  +**Constraints:** + + + +- `1 <= nums.length <= 1000` + +- `-100 <= nums[i] <= 100` + + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @return {number} + */ +var arraySign = function(nums) { + var res = 1; + for (var i = 0; i < nums.length; i++) { + res *= nums[i] > 0 ? 1 : (nums[i] === 0 ? 0 : -1); + } + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/1801-1900/1824. Minimum Sideway Jumps.md b/1801-1900/1824. Minimum Sideway Jumps.md new file mode 100644 index 0000000..acb852f --- /dev/null +++ b/1801-1900/1824. Minimum Sideway Jumps.md @@ -0,0 +1,109 @@ +# 1824. Minimum Sideway Jumps + +- Difficulty: Medium. +- Related Topics: Array, Dynamic Programming, Greedy. +- Similar Questions: Frog Jump. + +## Problem + +There is a **3 lane road** of length `n` that consists of `n + 1` **points** labeled from `0` to `n`. A frog **starts** at point `0` in the **second **lane** **and wants to jump to point `n`. However, there could be obstacles along the way. + +You are given an array `obstacles` of length `n + 1` where each `obstacles[i]` (**ranging from 0 to 3**) describes an obstacle on the lane `obstacles[i]` at point `i`. If `obstacles[i] == 0`, there are no obstacles at point `i`. There will be **at most one** obstacle in the 3 lanes at each point. + + + +- For example, if `obstacles[2] == 1`, then there is an obstacle on lane 1 at point 2. + + +The frog can only travel from point `i` to point `i + 1` on the same lane if there is not an obstacle on the lane at point `i + 1`. To avoid obstacles, the frog can also perform a **side jump** to jump to **another** lane (even if they are not adjacent) at the **same** point if there is no obstacle on the new lane. + + + +- For example, the frog can jump from lane 3 at point 3 to lane 1 at point 3. + + +Return** the **minimum number of side jumps** the frog needs to reach **any lane** at point n starting from lane `2` at point 0.** + +**Note:** There will be no obstacles on points `0` and `n`. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2021/03/25/ic234-q3-ex1.png) + +``` +Input: obstacles = [0,1,2,3,0] +Output: 2 +Explanation: The optimal solution is shown by the arrows above. There are 2 side jumps (red arrows). +Note that the frog can jump over obstacles only when making side jumps (as shown at point 2). +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2021/03/25/ic234-q3-ex2.png) + +``` +Input: obstacles = [0,1,1,3,3,0] +Output: 0 +Explanation: There are no obstacles on lane 2. No side jumps are required. +``` + +Example 3: + +![](https://assets.leetcode.com/uploads/2021/03/25/ic234-q3-ex3.png) + +``` +Input: obstacles = [0,2,1,0,3,0] +Output: 2 +Explanation: The optimal solution is shown by the arrows above. There are 2 side jumps. +``` + +  +**Constraints:** + + + +- `obstacles.length == n + 1` + +- `1 <= n <= 5 * 105` + +- `0 <= obstacles[i] <= 3` + +- `obstacles[0] == obstacles[n] == 0` + + + +## Solution + +```javascript +/** + * @param {number[]} obstacles + * @return {number} + */ +var minSideJumps = function(obstacles) { + return helper(obstacles, 0, 2); +}; + +var helper = function(obstacles, i, lane) { + if (i === obstacles.length) return 0; + if (obstacles[i + 1] !== lane) return helper(obstacles, i + 1, lane); + var nextIndex = -1; + for (var j = i; j < obstacles.length; j++) { + if (obstacles[j] !== lane && obstacles[j] !== 0) { + nextIndex = j; + break; + } + } + if (nextIndex === -1) return 1; + return 1 + helper(obstacles, nextIndex, 6 - lane - obstacles[nextIndex]); +}; +``` + +**Explain:** + +Greedy. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/1801-1900/1834. Single-Threaded CPU.md b/1801-1900/1834. Single-Threaded CPU.md new file mode 100644 index 0000000..218500d --- /dev/null +++ b/1801-1900/1834. Single-Threaded CPU.md @@ -0,0 +1,113 @@ +# 1834. Single-Threaded CPU + +- Difficulty: Medium. +- Related Topics: Array, Sorting, Heap (Priority Queue). +- Similar Questions: Parallel Courses III, Minimum Time to Complete All Tasks. + +## Problem + +You are given `n`​​​​​​ tasks labeled from `0` to `n - 1` represented by a 2D integer array `tasks`, where `tasks[i] = [enqueueTimei, processingTimei]` means that the `i​​​​​​th`​​​​ task will be available to process at `enqueueTimei` and will take `processingTimei` to finish processing. + +You have a single-threaded CPU that can process **at most one** task at a time and will act in the following way: + + + +- If the CPU is idle and there are no available tasks to process, the CPU remains idle. + +- If the CPU is idle and there are available tasks, the CPU will choose the one with the **shortest processing time**. If multiple tasks have the same shortest processing time, it will choose the task with the smallest index. + +- Once a task is started, the CPU will **process the entire task** without stopping. + +- The CPU can finish a task then start a new one instantly. + + +Return **the order in which the CPU will process the tasks.** + +  +Example 1: + +``` +Input: tasks = [[1,2],[2,4],[3,2],[4,1]] +Output: [0,2,3,1] +Explanation: The events go as follows: +- At time = 1, task 0 is available to process. Available tasks = {0}. +- Also at time = 1, the idle CPU starts processing task 0. Available tasks = {}. +- At time = 2, task 1 is available to process. Available tasks = {1}. +- At time = 3, task 2 is available to process. Available tasks = {1, 2}. +- Also at time = 3, the CPU finishes task 0 and starts processing task 2 as it is the shortest. Available tasks = {1}. +- At time = 4, task 3 is available to process. Available tasks = {1, 3}. +- At time = 5, the CPU finishes task 2 and starts processing task 3 as it is the shortest. Available tasks = {1}. +- At time = 6, the CPU finishes task 3 and starts processing task 1. Available tasks = {}. +- At time = 10, the CPU finishes task 1 and becomes idle. +``` + +Example 2: + +``` +Input: tasks = [[7,10],[7,12],[7,5],[7,4],[7,2]] +Output: [4,3,2,0,1] +Explanation: The events go as follows: +- At time = 7, all the tasks become available. Available tasks = {0,1,2,3,4}. +- Also at time = 7, the idle CPU starts processing task 4. Available tasks = {0,1,2,3}. +- At time = 9, the CPU finishes task 4 and starts processing task 3. Available tasks = {0,1,2}. +- At time = 13, the CPU finishes task 3 and starts processing task 2. Available tasks = {0,1}. +- At time = 18, the CPU finishes task 2 and starts processing task 0. Available tasks = {1}. +- At time = 28, the CPU finishes task 0 and starts processing task 1. Available tasks = {}. +- At time = 40, the CPU finishes task 1 and becomes idle. +``` + +  +**Constraints:** + + + +- `tasks.length == n` + +- `1 <= n <= 105` + +- `1 <= enqueueTimei, processingTimei <= 109` + + + +## Solution + +```javascript +/** + * @param {number[][]} tasks + * @return {number[]} + */ +var getOrder = function(tasks) { + var arr = tasks.map((task, i) => [task[0], task[1], i]).sort((a, b) => a[0] - b[0]); + + var queue = new MinPriorityQueue(); + var i = 0; + var res = []; + var lastTime = 0; + while (i < arr.length || queue.size()) { + if (!queue.size() && arr[i][0] > lastTime) { + lastTime = arr[i][0]; + } + + while (arr[i] && arr[i][0] <= lastTime) { + var priority = arr[i][1] + (arr[i][2] / Math.pow(10, `${arr.length}`.length)); + queue.enqueue(arr[i], priority); + i++; + } + + var task = queue.dequeue().element; + res.push(task[2]); + lastTime += task[1]; + } + + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/1801-1900/1838. Frequency of the Most Frequent Element.md b/1801-1900/1838. Frequency of the Most Frequent Element.md new file mode 100644 index 0000000..ce38834 --- /dev/null +++ b/1801-1900/1838. Frequency of the Most Frequent Element.md @@ -0,0 +1,111 @@ +# 1838. Frequency of the Most Frequent Element + +- Difficulty: Medium. +- Related Topics: Array, Binary Search, Greedy, Sliding Window, Sorting, Prefix Sum. +- Similar Questions: Find All Lonely Numbers in the Array, Longest Nice Subarray. + +## Problem + +The **frequency** of an element is the number of times it occurs in an array. + +You are given an integer array ```nums``` and an integer ```k```. In one operation, you can choose an index of ```nums``` and increment the element at that index by ```1```. + +Return **the **maximum possible frequency** of an element after performing **at most** **```k```** operations**. + +  +Example 1: + +``` +Input: nums = [1,2,4], k = 5 +Output: 3 +Explanation: Increment the first element three times and the second element two times to make nums = [4,4,4]. +4 has a frequency of 3. +``` + +Example 2: + +``` +Input: nums = [1,4,8,13], k = 5 +Output: 2 +Explanation: There are multiple optimal solutions: +- Increment the first element three times to make nums = [4,4,8,13]. 4 has a frequency of 2. +- Increment the second element four times to make nums = [1,8,8,13]. 8 has a frequency of 2. +- Increment the third element five times to make nums = [1,4,13,13]. 13 has a frequency of 2. +``` + +Example 3: + +``` +Input: nums = [3,9,6], k = 2 +Output: 1 +``` + +  +**Constraints:** + + + +- ```1 <= nums.length <= 105``` + +- ```1 <= nums[i] <= 105``` + +- ```1 <= k <= 105``` + + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var maxFrequency = function(nums, k) { + nums.sort((a, b) => a - b); + + var sums = Array(nums.length); + nums.forEach((num, i) => sums[i] = (sums[i - 1] || 0) + num); + + var max = 0; + for (var i = 0; i < nums.length; i++) { + var frequency = i + 1 - binarySearch(nums, sums, i, k); + max = Math.max(max, frequency); + } + + return max; +}; + +var binarySearch = function(nums, sums, i, k) { + var left = 0; + var right = i; + var getValue = (j) => { + return nums[i] * (i - j + 1) - (sums[i] - sums[j] + nums[j]); + }; + while (left <= right) { + var mid = left + Math.floor((right - left) / 2); + var midValue = getValue(mid); + if (midValue === k) { + return mid; + } else if (midValue > k) { + left = mid + 1; + } else { + if (mid === left) return mid; + right = mid; + } + } + return i; +}; +``` + +**Explain:** + +1. sort the array of nums by ascending order +2. calculate prefix sum array +3. for every nums[i], binary search possible index in [0, i], + which can use k operates, to make every num in [index, i] equals nums[i] + +**Complexity:** + +* Time complexity : O(nlog(n)). +* Space complexity : O(n). diff --git a/1801-1900/1845. Seat Reservation Manager.md b/1801-1900/1845. Seat Reservation Manager.md new file mode 100644 index 0000000..bbfdb6d --- /dev/null +++ b/1801-1900/1845. Seat Reservation Manager.md @@ -0,0 +1,111 @@ +# 1845. Seat Reservation Manager + +- Difficulty: Medium. +- Related Topics: Design, Heap (Priority Queue). +- Similar Questions: Design Phone Directory, Design a Number Container System. + +## Problem + +Design a system that manages the reservation state of `n` seats that are numbered from `1` to `n`. + +Implement the `SeatManager` class: + + + +- `SeatManager(int n)` Initializes a `SeatManager` object that will manage `n` seats numbered from `1` to `n`. All seats are initially available. + +- `int reserve()` Fetches the **smallest-numbered** unreserved seat, reserves it, and returns its number. + +- `void unreserve(int seatNumber)` Unreserves the seat with the given `seatNumber`. + + +  +Example 1: + +``` +Input +["SeatManager", "reserve", "reserve", "unreserve", "reserve", "reserve", "reserve", "reserve", "unreserve"] +[[5], [], [], [2], [], [], [], [], [5]] +Output +[null, 1, 2, null, 2, 3, 4, 5, null] + +Explanation +SeatManager seatManager = new SeatManager(5); // Initializes a SeatManager with 5 seats. +seatManager.reserve(); // All seats are available, so return the lowest numbered seat, which is 1. +seatManager.reserve(); // The available seats are [2,3,4,5], so return the lowest of them, which is 2. +seatManager.unreserve(2); // Unreserve seat 2, so now the available seats are [2,3,4,5]. +seatManager.reserve(); // The available seats are [2,3,4,5], so return the lowest of them, which is 2. +seatManager.reserve(); // The available seats are [3,4,5], so return the lowest of them, which is 3. +seatManager.reserve(); // The available seats are [4,5], so return the lowest of them, which is 4. +seatManager.reserve(); // The only available seat is seat 5, so return 5. +seatManager.unreserve(5); // Unreserve seat 5, so now the available seats are [5]. +``` + +  +**Constraints:** + + + +- `1 <= n <= 105` + +- `1 <= seatNumber <= n` + +- For each call to `reserve`, it is guaranteed that there will be at least one unreserved seat. + +- For each call to `unreserve`, it is guaranteed that `seatNumber` will be reserved. + +- At most `105` calls **in total** will be made to `reserve` and `unreserve`. + + + +## Solution + +```javascript +/** + * @param {number} n + */ +var SeatManager = function(n) { + this.queue = new MinPriorityQueue(); + this.index = 1; +}; + +/** + * @return {number} + */ +SeatManager.prototype.reserve = function() { + if (this.queue.size()) { + return this.queue.dequeue().element; + } + return this.index++; +}; + +/** + * @param {number} seatNumber + * @return {void} + */ +SeatManager.prototype.unreserve = function(seatNumber) { + if (seatNumber === this.index - 1) { + this.index--; + return; + } + this.queue.enqueue(seatNumber, seatNumber); +}; + +/** + * Your SeatManager object will be instantiated and called as such: + * var obj = new SeatManager(n) + * var param_1 = obj.reserve() + * obj.unreserve(seatNumber) + */ +``` + +**Explain:** + +The `index` is the start of unreserved seats number. + +The `queue` is a min priority queue about unreserved seats before `index` + +**Complexity:** + +* Time complexity : O(m * log(n)). +* Space complexity : O(n). diff --git a/1801-1900/1846. Maximum Element After Decreasing and Rearranging.md b/1801-1900/1846. Maximum Element After Decreasing and Rearranging.md new file mode 100644 index 0000000..3ae75af --- /dev/null +++ b/1801-1900/1846. Maximum Element After Decreasing and Rearranging.md @@ -0,0 +1,98 @@ +# 1846. Maximum Element After Decreasing and Rearranging + +- Difficulty: Medium. +- Related Topics: Array, Greedy, Sorting. +- Similar Questions: . + +## Problem + +You are given an array of positive integers `arr`. Perform some operations (possibly none) on `arr` so that it satisfies these conditions: + + + +- The value of the **first** element in `arr` must be `1`. + +- The absolute difference between any 2 adjacent elements must be **less than or equal to **`1`. In other words, `abs(arr[i] - arr[i - 1]) <= 1` for each `i` where `1 <= i < arr.length` (**0-indexed**). `abs(x)` is the absolute value of `x`. + + +There are 2 types of operations that you can perform any number of times: + + + +- **Decrease** the value of any element of `arr` to a **smaller positive integer**. + +- **Rearrange** the elements of `arr` to be in any order. + + +Return **the **maximum** possible value of an element in **`arr`** after performing the operations to satisfy the conditions**. + +  +Example 1: + +``` +Input: arr = [2,2,1,2,1] +Output: 2 +Explanation: +We can satisfy the conditions by rearranging arr so it becomes [1,2,2,2,1]. +The largest element in arr is 2. +``` + +Example 2: + +``` +Input: arr = [100,1,1000] +Output: 3 +Explanation: +One possible way to satisfy the conditions is by doing the following: +1. Rearrange arr so it becomes [1,100,1000]. +2. Decrease the value of the second element to 2. +3. Decrease the value of the third element to 3. +Now arr = [1,2,3], which satisfies the conditions. +The largest element in arr is 3. +``` + +Example 3: + +``` +Input: arr = [1,2,3,4,5] +Output: 5 +Explanation: The array already satisfies the conditions, and the largest element is 5. +``` + +  +**Constraints:** + + + +- `1 <= arr.length <= 105` + +- `1 <= arr[i] <= 109` + + + +## Solution + +```javascript +/** + * @param {number[]} arr + * @return {number} + */ +var maximumElementAfterDecrementingAndRearranging = function(arr) { + arr.sort((a, b) => a - b); + arr[0] = 1; + for (var i = 1 ; i < arr.length; i++) { + if (arr[i] - arr[i - 1] <= 1) continue; + arr[i] = arr[i - 1] + 1; + } + return arr[arr.length - 1]; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * log(n)). +* Space complexity : O(1). diff --git a/1801-1900/1851. Minimum Interval to Include Each Query.md b/1801-1900/1851. Minimum Interval to Include Each Query.md new file mode 100644 index 0000000..10228d2 --- /dev/null +++ b/1801-1900/1851. Minimum Interval to Include Each Query.md @@ -0,0 +1,87 @@ +# 1851. Minimum Interval to Include Each Query + +- Difficulty: Hard. +- Related Topics: Array, Binary Search, Line Sweep, Sorting, Heap (Priority Queue). +- Similar Questions: Number of Flowers in Full Bloom. + +## Problem + +You are given a 2D integer array `intervals`, where `intervals[i] = [lefti, righti]` describes the `ith` interval starting at `lefti` and ending at `righti` **(inclusive)**. The **size** of an interval is defined as the number of integers it contains, or more formally `righti - lefti + 1`. + +You are also given an integer array `queries`. The answer to the `jth` query is the **size of the smallest interval** `i` such that `lefti <= queries[j] <= righti`. If no such interval exists, the answer is `-1`. + +Return **an array containing the answers to the queries**. + +  +Example 1: + +``` +Input: intervals = [[1,4],[2,4],[3,6],[4,4]], queries = [2,3,4,5] +Output: [3,3,1,4] +Explanation: The queries are processed as follows: +- Query = 2: The interval [2,4] is the smallest interval containing 2. The answer is 4 - 2 + 1 = 3. +- Query = 3: The interval [2,4] is the smallest interval containing 3. The answer is 4 - 2 + 1 = 3. +- Query = 4: The interval [4,4] is the smallest interval containing 4. The answer is 4 - 4 + 1 = 1. +- Query = 5: The interval [3,6] is the smallest interval containing 5. The answer is 6 - 3 + 1 = 4. +``` + +Example 2: + +``` +Input: intervals = [[2,3],[2,5],[1,8],[20,25]], queries = [2,19,5,22] +Output: [2,-1,4,6] +Explanation: The queries are processed as follows: +- Query = 2: The interval [2,3] is the smallest interval containing 2. The answer is 3 - 2 + 1 = 2. +- Query = 19: None of the intervals contain 19. The answer is -1. +- Query = 5: The interval [2,5] is the smallest interval containing 5. The answer is 5 - 2 + 1 = 4. +- Query = 22: The interval [20,25] is the smallest interval containing 22. The answer is 25 - 20 + 1 = 6. +``` + +  +**Constraints:** + + + +- `1 <= intervals.length <= 105` + +- `1 <= queries.length <= 105` + +- `intervals[i].length == 2` + +- `1 <= lefti <= righti <= 107` + +- `1 <= queries[j] <= 107` + + + +## Solution + +```javascript +/** + * @param {number[][]} intervals + * @param {number[]} queries + * @return {number[]} + */ +var minInterval = function(intervals, queries) { + var starts = intervals.sort((a, b) => a[0] - b[0]); + var nums = queries.map((num, i) => [num, i]).sort((a, b) => a[0] - b[0]); + var queue = new MinPriorityQueue(); + var res = Array(queries.length); + var j = 0; + for (var i = 0; i < nums.length; i++) { + while (starts[j] && starts[j][0] <= nums[i][0]) queue.enqueue(starts[j], starts[j][1] - starts[j++][0] + 1); + while (queue.size() && queue.front().element[1] < nums[i][0]) queue.dequeue(); + res[nums[i][1]] = queue.size() ? queue.front().priority : -1; + } + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(nlog(n) + mlog(m) + mlog(n)). +* Space complexity : O(n + m). diff --git a/1801-1900/1870. Minimum Speed to Arrive on Time.md b/1801-1900/1870. Minimum Speed to Arrive on Time.md new file mode 100644 index 0000000..dd419de --- /dev/null +++ b/1801-1900/1870. Minimum Speed to Arrive on Time.md @@ -0,0 +1,115 @@ +# 1870. Minimum Speed to Arrive on Time + +- Difficulty: Medium. +- Related Topics: Array, Binary Search. +- Similar Questions: Maximum Candies Allocated to K Children, Minimum Skips to Arrive at Meeting On Time, Minimum Time to Complete Trips, The Latest Time to Catch a Bus, Minimize Maximum of Array. + +## Problem + +You are given a floating-point number `hour`, representing the amount of time you have to reach the office. To commute to the office, you must take `n` trains in sequential order. You are also given an integer array `dist` of length `n`, where `dist[i]` describes the distance (in kilometers) of the `ith` train ride. + +Each train can only depart at an integer hour, so you may need to wait in between each train ride. + + + +- For example, if the `1st` train ride takes `1.5` hours, you must wait for an additional `0.5` hours before you can depart on the `2nd` train ride at the 2 hour mark. + + +Return **the **minimum positive integer** speed **(in kilometers per hour)** that all the trains must travel at for you to reach the office on time, or **`-1`** if it is impossible to be on time**. + +Tests are generated such that the answer will not exceed `107` and `hour` will have **at most two digits after the decimal point**. + +  +Example 1: + +``` +Input: dist = [1,3,2], hour = 6 +Output: 1 +Explanation: At speed 1: +- The first train ride takes 1/1 = 1 hour. +- Since we are already at an integer hour, we depart immediately at the 1 hour mark. The second train takes 3/1 = 3 hours. +- Since we are already at an integer hour, we depart immediately at the 4 hour mark. The third train takes 2/1 = 2 hours. +- You will arrive at exactly the 6 hour mark. +``` + +Example 2: + +``` +Input: dist = [1,3,2], hour = 2.7 +Output: 3 +Explanation: At speed 3: +- The first train ride takes 1/3 = 0.33333 hours. +- Since we are not at an integer hour, we wait until the 1 hour mark to depart. The second train ride takes 3/3 = 1 hour. +- Since we are already at an integer hour, we depart immediately at the 2 hour mark. The third train takes 2/3 = 0.66667 hours. +- You will arrive at the 2.66667 hour mark. +``` + +Example 3: + +``` +Input: dist = [1,3,2], hour = 1.9 +Output: -1 +Explanation: It is impossible because the earliest the third train can depart is at the 2 hour mark. +``` + +  +**Constraints:** + + + +- `n == dist.length` + +- `1 <= n <= 105` + +- `1 <= dist[i] <= 105` + +- `1 <= hour <= 109` + +- There will be at most two digits after the decimal point in `hour`. + + + +## Solution + +```javascript +/** + * @param {number[]} dist + * @param {number} hour + * @return {number} + */ +var minSpeedOnTime = function(dist, hour) { + return search(dist, hour, 1, Math.pow(10, 7)); +}; + +var search = function(dist, hour, left, right) { + while (left <= right) { + const mid = left + Math.floor((right - left) / 2); + if (getTime(dist, mid) > hour) { + left = mid + 1; + } else { + if (left === right) return left; + right = mid; + } + } + return -1; +}; + +var getTime = function(dist, speed) { + var res = 0; + for (var i = 0; i < dist.length; i++) { + var num = dist[i] / speed; + if (i !== dist.length - 1) num = Math.ceil(num); + res += num; + } + return res; +}; +``` + +**Explain:** + +Binary search. + +**Complexity:** + +* Time complexity : O(n * log(K)). +* Space complexity : O(n). diff --git a/1801-1900/1877. Minimize Maximum Pair Sum in Array.md b/1801-1900/1877. Minimize Maximum Pair Sum in Array.md new file mode 100644 index 0000000..f0b7666 --- /dev/null +++ b/1801-1900/1877. Minimize Maximum Pair Sum in Array.md @@ -0,0 +1,84 @@ +# 1877. Minimize Maximum Pair Sum in Array + +- Difficulty: Medium. +- Related Topics: Array, Two Pointers, Greedy, Sorting. +- Similar Questions: . + +## Problem + +The **pair sum** of a pair `(a,b)` is equal to `a + b`. The **maximum pair sum** is the largest **pair sum** in a list of pairs. + + + +- For example, if we have pairs `(1,5)`, `(2,3)`, and `(4,4)`, the **maximum pair sum** would be `max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8`. + + +Given an array `nums` of **even** length `n`, pair up the elements of `nums` into `n / 2` pairs such that: + + + +- Each element of `nums` is in **exactly one** pair, and + +- The **maximum pair sum **is **minimized**. + + +Return **the minimized **maximum pair sum** after optimally pairing up the elements**. + +  +Example 1: + +``` +Input: nums = [3,5,2,3] +Output: 7 +Explanation: The elements can be paired up into pairs (3,3) and (5,2). +The maximum pair sum is max(3+3, 5+2) = max(6, 7) = 7. +``` + +Example 2: + +``` +Input: nums = [3,5,4,2,4,6] +Output: 8 +Explanation: The elements can be paired up into pairs (3,5), (4,4), and (6,2). +The maximum pair sum is max(3+5, 4+4, 6+2) = max(8, 8, 8) = 8. +``` + +  +**Constraints:** + + + +- `n == nums.length` + +- `2 <= n <= 105` + +- `n` is **even**. + +- `1 <= nums[i] <= 105` + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @return {number} + */ +var minPairSum = function(nums) { + nums.sort((a, b) => a - b); + var res = 0; + for (var i = 0; i < nums.length / 2; i++) { + res = Math.max(res, nums[i] + nums[nums.length - i - 1]); + } + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * log(n)). +* Space complexity : O(1). 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/1887. Reduction Operations to Make the Array Elements Equal.md b/1801-1900/1887. Reduction Operations to Make the Array Elements Equal.md new file mode 100644 index 0000000..ce1b688 --- /dev/null +++ b/1801-1900/1887. Reduction Operations to Make the Array Elements Equal.md @@ -0,0 +1,99 @@ +# 1887. Reduction Operations to Make the Array Elements Equal + +- Difficulty: Medium. +- Related Topics: Array, Sorting. +- Similar Questions: . + +## Problem + +Given an integer array `nums`, your goal is to make all elements in `nums` equal. To complete one operation, follow these steps: + + + +- Find the **largest** value in `nums`. Let its index be `i` (**0-indexed**) and its value be `largest`. If there are multiple elements with the largest value, pick the smallest `i`. + +- Find the **next largest** value in `nums` **strictly smaller** than `largest`. Let its value be `nextLargest`. + +- Reduce `nums[i]` to `nextLargest`. + + +Return **the number of operations to make all elements in **`nums`** equal**. + +  +Example 1: + +``` +Input: nums = [5,1,3] +Output: 3 +Explanation: It takes 3 operations to make all elements in nums equal: +1. largest = 5 at index 0. nextLargest = 3. Reduce nums[0] to 3. nums = [3,1,3]. +2. largest = 3 at index 0. nextLargest = 1. Reduce nums[0] to 1. nums = [1,1,3]. +3. largest = 3 at index 2. nextLargest = 1. Reduce nums[2] to 1. nums = [1,1,1]. +``` + +Example 2: + +``` +Input: nums = [1,1,1] +Output: 0 +Explanation: All elements in nums are already equal. +``` + +Example 3: + +``` +Input: nums = [1,1,2,2,3] +Output: 4 +Explanation: It takes 4 operations to make all elements in nums equal: +1. largest = 3 at index 4. nextLargest = 2. Reduce nums[4] to 2. nums = [1,1,2,2,2]. +2. largest = 2 at index 2. nextLargest = 1. Reduce nums[2] to 1. nums = [1,1,1,2,2]. +3. largest = 2 at index 3. nextLargest = 1. Reduce nums[3] to 1. nums = [1,1,1,1,2]. +4. largest = 2 at index 4. nextLargest = 1. Reduce nums[4] to 1. nums = [1,1,1,1,1]. +``` + +  +**Constraints:** + + + +- `1 <= nums.length <= 5 * 104` + +- `1 <= nums[i] <= 5 * 104` + + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @return {number} + */ +var reductionOperations = function(nums) { + nums.sort((a, b) => a - b); + var uniqueNums = []; + for (var i = 0; i < nums.length; i++) { + if (nums[i] === nums[i - 1]) { + uniqueNums[uniqueNums.length - 1]++; + } else { + uniqueNums.push(1); + } + } + var res = 0; + while (uniqueNums.length > 1) { + var last = uniqueNums.pop(); + res += last; + uniqueNums[uniqueNums.length - 1] += last; + } + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * log(n)). +* Space complexity : O(n). 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/1921. Eliminate Maximum Number of Monsters.md b/1901-2000/1921. Eliminate Maximum Number of Monsters.md new file mode 100644 index 0000000..57e47ea --- /dev/null +++ b/1901-2000/1921. Eliminate Maximum Number of Monsters.md @@ -0,0 +1,91 @@ +# 1921. Eliminate Maximum Number of Monsters + +- Difficulty: Medium. +- Related Topics: Array, Greedy, Sorting. +- Similar Questions: Minimum Health to Beat Game, Minimum Time to Kill All Monsters. + +## Problem + +You are playing a video game where you are defending your city from a group of `n` monsters. You are given a **0-indexed** integer array `dist` of size `n`, where `dist[i]` is the **initial distance** in kilometers of the `ith` monster from the city. + +The monsters walk toward the city at a **constant** speed. The speed of each monster is given to you in an integer array `speed` of size `n`, where `speed[i]` is the speed of the `ith` monster in kilometers per minute. + +You have a weapon that, once fully charged, can eliminate a **single** monster. However, the weapon takes **one minute** to charge. The weapon is fully charged at the very start. + +You lose when any monster reaches your city. If a monster reaches the city at the exact moment the weapon is fully charged, it counts as a **loss**, and the game ends before you can use your weapon. + +Return **the **maximum** number of monsters that you can eliminate before you lose, or **`n`** if you can eliminate all the monsters before they reach the city.** + +  +Example 1: + +``` +Input: dist = [1,3,4], speed = [1,1,1] +Output: 3 +Explanation: +In the beginning, the distances of the monsters are [1,3,4]. You eliminate the first monster. +After a minute, the distances of the monsters are [X,2,3]. You eliminate the second monster. +After a minute, the distances of the monsters are [X,X,2]. You eliminate the thrid monster. +All 3 monsters can be eliminated. +``` + +Example 2: + +``` +Input: dist = [1,1,2,3], speed = [1,1,1,1] +Output: 1 +Explanation: +In the beginning, the distances of the monsters are [1,1,2,3]. You eliminate the first monster. +After a minute, the distances of the monsters are [X,0,1,2], so you lose. +You can only eliminate 1 monster. +``` + +Example 3: + +``` +Input: dist = [3,2,4], speed = [5,3,2] +Output: 1 +Explanation: +In the beginning, the distances of the monsters are [3,2,4]. You eliminate the first monster. +After a minute, the distances of the monsters are [X,0,2], so you lose. +You can only eliminate 1 monster. +``` + +  +**Constraints:** + + + +- `n == dist.length == speed.length` + +- `1 <= n <= 105` + +- `1 <= dist[i], speed[i] <= 105` + + + +## Solution + +```javascript +/** + * @param {number[]} dist + * @param {number[]} speed + * @return {number} + */ +var eliminateMaximum = function(dist, speed) { + var times = dist.map((d, i) => d / speed[i]).sort((a, b) => a - b); + for (var i = 0; i < times.length; i++) { + if (times[i] <= i) return i; + } + return dist.length; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * log(n)). +* Space complexity : O(n). diff --git a/1901-2000/1930. Unique Length-3 Palindromic Subsequences.md b/1901-2000/1930. Unique Length-3 Palindromic Subsequences.md new file mode 100644 index 0000000..d228dae --- /dev/null +++ b/1901-2000/1930. Unique Length-3 Palindromic Subsequences.md @@ -0,0 +1,99 @@ +# 1930. Unique Length-3 Palindromic Subsequences + +- Difficulty: Medium. +- Related Topics: Hash Table, String, Prefix Sum. +- Similar Questions: Count Palindromic Subsequences. + +## Problem + +Given a string `s`, return **the number of **unique palindromes of length three** that are a **subsequence** of **`s`. + +Note that even if there are multiple ways to obtain the same subsequence, it is still only counted **once**. + +A **palindrome** is a string that reads the same forwards and backwards. + +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"`. + + +  +Example 1: + +``` +Input: s = "aabca" +Output: 3 +Explanation: The 3 palindromic subsequences of length 3 are: +- "aba" (subsequence of "aabca") +- "aaa" (subsequence of "aabca") +- "aca" (subsequence of "aabca") +``` + +Example 2: + +``` +Input: s = "adc" +Output: 0 +Explanation: There are no palindromic subsequences of length 3 in "adc". +``` + +Example 3: + +``` +Input: s = "bbcbaba" +Output: 4 +Explanation: The 4 palindromic subsequences of length 3 are: +- "bbb" (subsequence of "bbcbaba") +- "bcb" (subsequence of "bbcbaba") +- "bab" (subsequence of "bbcbaba") +- "aba" (subsequence of "bbcbaba") +``` + +  +**Constraints:** + + + +- `3 <= s.length <= 105` + +- `s` consists of only lowercase English letters. + + + +## Solution + +```javascript +/** + * @param {string} s + * @return {number} + */ +var countPalindromicSubsequence = function(s) { + var a = 'a'.charCodeAt(0); + var res = 0; + for (var i = 0; i < 26; i++) { + var char = String.fromCharCode(i + a); + var first = s.indexOf(char); + var last = s.lastIndexOf(char); + if (last - first < 2) continue; + var map = {}; + for (var j = first + 1; j < last; j++) { + if (!map[s[j]]) { + res += 1; + map[s[j]] = true; + } + } + } + return res; +}; +``` + +**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/1942. The Number of the Smallest Unoccupied Chair.md b/1901-2000/1942. The Number of the Smallest Unoccupied Chair.md new file mode 100644 index 0000000..3bb93b7 --- /dev/null +++ b/1901-2000/1942. The Number of the Smallest Unoccupied Chair.md @@ -0,0 +1,133 @@ +# 1942. The Number of the Smallest Unoccupied Chair + +- Difficulty: Medium. +- Related Topics: Array, Heap (Priority Queue), Ordered Set. +- Similar Questions: . + +## Problem + +There is a party where `n` friends numbered from `0` to `n - 1` are attending. There is an **infinite** number of chairs in this party that are numbered from `0` to `infinity`. When a friend arrives at the party, they sit on the unoccupied chair with the **smallest number**. + + + +- For example, if chairs `0`, `1`, and `5` are occupied when a friend comes, they will sit on chair number `2`. + + +When a friend leaves the party, their chair becomes unoccupied at the moment they leave. If another friend arrives at that same moment, they can sit in that chair. + +You are given a **0-indexed** 2D integer array `times` where `times[i] = [arrivali, leavingi]`, indicating the arrival and leaving times of the `ith` friend respectively, and an integer `targetFriend`. All arrival times are **distinct**. + +Return** the **chair number** that the friend numbered **`targetFriend`** will sit on**. + +  +Example 1: + +``` +Input: times = [[1,4],[2,3],[4,6]], targetFriend = 1 +Output: 1 +Explanation: +- Friend 0 arrives at time 1 and sits on chair 0. +- Friend 1 arrives at time 2 and sits on chair 1. +- Friend 1 leaves at time 3 and chair 1 becomes empty. +- Friend 0 leaves at time 4 and chair 0 becomes empty. +- Friend 2 arrives at time 4 and sits on chair 0. +Since friend 1 sat on chair 1, we return 1. +``` + +Example 2: + +``` +Input: times = [[3,10],[1,5],[2,6]], targetFriend = 0 +Output: 2 +Explanation: +- Friend 1 arrives at time 1 and sits on chair 0. +- Friend 2 arrives at time 2 and sits on chair 1. +- Friend 0 arrives at time 3 and sits on chair 2. +- Friend 1 leaves at time 5 and chair 0 becomes empty. +- Friend 2 leaves at time 6 and chair 1 becomes empty. +- Friend 0 leaves at time 10 and chair 2 becomes empty. +Since friend 0 sat on chair 2, we return 2. +``` + +  +**Constraints:** + + + +- `n == times.length` + +- `2 <= n <= 104` + +- `times[i].length == 2` + +- `1 <= arrivali < leavingi <= 105` + +- `0 <= targetFriend <= n - 1` + +- Each `arrivali` time is **distinct**. + + + +## Solution + +```javascript +/** + * @param {number[][]} times + * @param {number} targetFriend + * @return {number} + */ +var smallestChair = function(times, targetFriend) { + var emptyChairs = new Set(); + var max = -1; + var list = times.reduce((arr, item, i) => { + arr.push({ i, type: 1, time: item[0] }); + arr.push({ i, type: 2, time: item[1] }); + return arr; + }, []).sort((a, b) => { + // be careful if someone's arrival time equals the other's leave time + // make sure we process leave one first + if (a.time === b.time) { + return b.type - a.type; + } + return a.time - b.time; + }); + var map = {}; + for (var i = 0; i < list.length; i++) { + var item = list[i]; + if (item.type === 1) { + // someone arrival + if (emptyChairs.size) { + // found empty chair someone left before + map[item.i] = findMin(emptyChairs); + emptyChairs.delete(map[item.i]); + } else { + // go to the last chair + map[item.i] = max + 1; + max = map[item.i]; + } + if (item.i === targetFriend) { + break; + } + } else { + // someone leave + emptyChairs.add(map[item.i]); + } + } + return map[targetFriend]; +}; + +// should replace set with min heap +// so that time complexity could be O(nlog(n)) +var findMin = function(list) { + return Array.from(list).sort((a, b) => a - b)[0]; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n^2). +* 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/1970. Last Day Where You Can Still Cross.md b/1901-2000/1970. Last Day Where You Can Still Cross.md new file mode 100644 index 0000000..348b8ba --- /dev/null +++ b/1901-2000/1970. Last Day Where You Can Still Cross.md @@ -0,0 +1,137 @@ +# 1970. Last Day Where You Can Still Cross + +- Difficulty: Hard. +- Related Topics: Array, Binary Search, Depth-First Search, Breadth-First Search, Union Find, Matrix. +- Similar Questions: Bricks Falling When Hit, Escape the Spreading Fire. + +## Problem + +There is a **1-based** binary matrix where `0` represents land and `1` represents water. You are given integers `row` and `col` representing the number of rows and columns in the matrix, respectively. + +Initially on day `0`, the **entire** matrix is **land**. However, each day a new cell becomes flooded with **water**. You are given a **1-based** 2D array `cells`, where `cells[i] = [ri, ci]` represents that on the `ith` day, the cell on the `rith` row and `cith` column (**1-based** coordinates) will be covered with **water** (i.e., changed to `1`). + +You want to find the **last** day that it is possible to walk from the **top** to the **bottom** by only walking on land cells. You can start from **any** cell in the top row and end at **any** cell in the bottom row. You can only travel in the** four** cardinal directions (left, right, up, and down). + +Return **the **last** day where it is possible to walk from the **top** to the **bottom** by only walking on land cells**. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2021/07/27/1.png) + +``` +Input: row = 2, col = 2, cells = [[1,1],[2,1],[1,2],[2,2]] +Output: 2 +Explanation: The above image depicts how the matrix changes each day starting from day 0. +The last day where it is possible to cross from top to bottom is on day 2. +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2021/07/27/2.png) + +``` +Input: row = 2, col = 2, cells = [[1,1],[1,2],[2,1],[2,2]] +Output: 1 +Explanation: The above image depicts how the matrix changes each day starting from day 0. +The last day where it is possible to cross from top to bottom is on day 1. +``` + +Example 3: + +![](https://assets.leetcode.com/uploads/2021/07/27/3.png) + +``` +Input: row = 3, col = 3, cells = [[1,2],[2,1],[3,3],[2,2],[1,1],[1,3],[2,3],[3,2],[3,1]] +Output: 3 +Explanation: The above image depicts how the matrix changes each day starting from day 0. +The last day where it is possible to cross from top to bottom is on day 3. +``` + +  +**Constraints:** + + + +- `2 <= row, col <= 2 * 104` + +- `4 <= row * col <= 2 * 104` + +- `cells.length == row * col` + +- `1 <= ri <= row` + +- `1 <= ci <= col` + +- All the values of `cells` are **unique**. + + + +## Solution + +```javascript +/** + * @param {number} row + * @param {number} col + * @param {number[][]} cells + * @return {number} + */ +var latestDayToCross = function(row, col, cells) { + var left = 0; + var right = cells.length - 1; + while (left < right) { + var mid = left + Math.ceil((right - left) / 2); + if (canCross(row, col, cells, mid)) { + left = mid; + } else { + right = mid - 1; + } + } + return left + 1; +}; + +var canCross = function(row, col, cells, day) { + var grid = Array(row).fill(0).map(() => Array(col).fill(0)); + for (var i = 0; i <= day; i++) { + grid[cells[i][0] - 1][cells[i][1] - 1] = 1; + } + var queue = []; + for (var i = 0; i < col; i++) { + if (grid[0][i] === 0) { + queue.push([0, i]); + grid[0][i] = 2; + } + } + while (queue.length !== 0) { + var [r, c] = queue.shift(); + if (r === row - 1) return true; + if (grid[r - 1] && grid[r - 1][c] === 0) { + queue.push([r - 1, c]); + grid[r - 1][c] = 2; + } + if (grid[r + 1] && grid[r + 1][c] === 0) { + queue.push([r + 1, c]); + grid[r + 1][c] = 2; + } + if (grid[r][c - 1] === 0) { + queue.push([r, c - 1]); + grid[r][c - 1] = 2; + } + if (grid[r][c + 1] === 0) { + queue.push([r, c + 1]); + grid[r][c + 1] = 2; + } + } + return false; +}; +``` + +**Explain:** + +1. check if nth day can walk through all the land from top to bottom, use BFS (Breadth first search), for each land, check top/bottom/left/right four direction can cross or not. +2. if nth day can cross, the last day should be in `n ~ last`, otherwise `0 ~ n - 1`, so that we can use binary search to find the answer. + +**Complexity:** + +* Time complexity : O(row * col * log(row * col)). +* Space complexity : O(row * col). 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/1980. Find Unique Binary String.md b/1901-2000/1980. Find Unique Binary String.md new file mode 100644 index 0000000..e0e41ca --- /dev/null +++ b/1901-2000/1980. Find Unique Binary String.md @@ -0,0 +1,79 @@ +# 1980. Find Unique Binary String + +- Difficulty: Medium. +- Related Topics: Array, String, Backtracking. +- Similar Questions: Missing Number, Find All Numbers Disappeared in an Array, Random Pick with Blacklist. + +## Problem + +Given an array of strings `nums` containing `n` **unique** binary strings each of length `n`, return **a binary string of length **`n`** that **does not appear** in **`nums`**. If there are multiple answers, you may return **any** of them**. + +  +Example 1: + +``` +Input: nums = ["01","10"] +Output: "11" +Explanation: "11" does not appear in nums. "00" would also be correct. +``` + +Example 2: + +``` +Input: nums = ["00","01"] +Output: "11" +Explanation: "11" does not appear in nums. "10" would also be correct. +``` + +Example 3: + +``` +Input: nums = ["111","011","001"] +Output: "101" +Explanation: "101" does not appear in nums. "000", "010", "100", and "110" would also be correct. +``` + +  +**Constraints:** + + + +- `n == nums.length` + +- `1 <= n <= 16` + +- `nums[i].length == n` + +- `nums[i] `is either `'0'` or `'1'`. + +- All the strings of `nums` are **unique**. + + + +## Solution + +```javascript +/** + * @param {string[]} nums + * @return {string} + */ +var findDifferentBinaryString = function(nums) { + var str = ''; + for (var i = 0; i <= nums.length; i++) { + str = i.toString(2); + str = '0'.repeat(nums.length - str.length) + str; + if (!nums.includes(str)) { + return str; + } + } +}; +``` + +**Explain:** + +Since array `nums` only contains `n` numbers, if we got `n + 1` numbers, there mush have at lease one number not in that array. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). 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/2009. Minimum Number of Operations to Make Array Continuous.md b/2001-2100/2009. Minimum Number of Operations to Make Array Continuous.md new file mode 100644 index 0000000..3c88147 --- /dev/null +++ b/2001-2100/2009. Minimum Number of Operations to Make Array Continuous.md @@ -0,0 +1,98 @@ +# 2009. Minimum Number of Operations to Make Array Continuous + +- Difficulty: Hard. +- Related Topics: Array, Binary Search. +- Similar Questions: Longest Repeating Character Replacement, Continuous Subarray Sum, Moving Stones Until Consecutive II, Minimum One Bit Operations to Make Integers Zero, Minimum Adjacent Swaps for K Consecutive Ones. + +## Problem + +You are given an integer array `nums`. In one operation, you can replace **any** element in `nums` with **any** integer. + +`nums` is considered **continuous** if both of the following conditions are fulfilled: + + + +- All elements in `nums` are **unique**. + +- The difference between the **maximum** element and the **minimum** element in `nums` equals `nums.length - 1`. + + +For example, `nums = [4, 2, 5, 3]` is **continuous**, but `nums = [1, 2, 3, 5, 6]` is **not continuous**. + +Return **the **minimum** number of operations to make **`nums`** ******continuous****. + +  +Example 1: + +``` +Input: nums = [4,2,5,3] +Output: 0 +Explanation: nums is already continuous. +``` + +Example 2: + +``` +Input: nums = [1,2,3,5,6] +Output: 1 +Explanation: One possible solution is to change the last element to 4. +The resulting array is [1,2,3,5,4], which is continuous. +``` + +Example 3: + +``` +Input: nums = [1,10,100,1000] +Output: 3 +Explanation: One possible solution is to: +- Change the second element to 2. +- Change the third element to 3. +- Change the fourth element to 4. +The resulting array is [1,2,3,4], which is continuous. +``` + +  +**Constraints:** + + + +- `1 <= nums.length <= 105` + +- `1 <= nums[i] <= 109` + + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @return {number} + */ +var minOperations = function(nums) { + nums.sort((a, b) => a - b); + + var uniqueNums = []; + for (var i = 0; i < nums.length; i++) { + if (nums[i] !== nums[i - 1]) uniqueNums.push(nums[i]); + } + + var left = 0; + var maxUniqueNumsInRange = 0; + for (var right = 0; right < uniqueNums.length; right++) { + while (uniqueNums[right] - uniqueNums[left] >= nums.length) left++; + maxUniqueNumsInRange = Math.max(maxUniqueNumsInRange, right - left + 1); + } + + return nums.length - maxUniqueNumsInRange; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * log(n)). +* Space complexity : O(n). diff --git a/2001-2100/2024. Maximize the Confusion of an Exam.md b/2001-2100/2024. Maximize the Confusion of an Exam.md new file mode 100644 index 0000000..ea054e7 --- /dev/null +++ b/2001-2100/2024. Maximize the Confusion of an Exam.md @@ -0,0 +1,106 @@ +# 2024. Maximize the Confusion of an Exam + +- Difficulty: Medium. +- Related Topics: String, Binary Search, Sliding Window, Prefix Sum. +- Similar Questions: Longest Substring with At Most K Distinct Characters, Longest Repeating Character Replacement, Max Consecutive Ones III, Minimum Number of Days to Make m Bouquets, Longest Nice Subarray. + +## Problem + +A teacher is writing a test with `n` true/false questions, with `'T'` denoting true and `'F'` denoting false. He wants to confuse the students by **maximizing** the number of **consecutive** questions with the **same** answer (multiple trues or multiple falses in a row). + +You are given a string `answerKey`, where `answerKey[i]` is the original answer to the `ith` question. In addition, you are given an integer `k`, the maximum number of times you may perform the following operation: + + + +- Change the answer key for any question to `'T'` or `'F'` (i.e., set `answerKey[i]` to `'T'` or `'F'`). + + +Return **the **maximum** number of consecutive** `'T'`s or `'F'`s **in the answer key after performing the operation at most** `k` **times**. + +  +Example 1: + +``` +Input: answerKey = "TTFF", k = 2 +Output: 4 +Explanation: We can replace both the 'F's with 'T's to make answerKey = "TTTT". +There are four consecutive 'T's. +``` + +Example 2: + +``` +Input: answerKey = "TFFT", k = 1 +Output: 3 +Explanation: We can replace the first 'T' with an 'F' to make answerKey = "FFFT". +Alternatively, we can replace the second 'T' with an 'F' to make answerKey = "TFFF". +In both cases, there are three consecutive 'F's. +``` + +Example 3: + +``` +Input: answerKey = "TTFTTFTT", k = 1 +Output: 5 +Explanation: We can replace the first 'F' to make answerKey = "TTTTTFTT" +Alternatively, we can replace the second 'F' to make answerKey = "TTFTTTTT". +In both cases, there are five consecutive 'T's. +``` + +  +**Constraints:** + + + +- `n == answerKey.length` + +- `1 <= n <= 5 * 104` + +- `answerKey[i]` is either `'T'` or `'F'` + +- `1 <= k <= n` + + + +## Solution + +```javascript +/** + * @param {string} answerKey + * @param {number} k + * @return {number} + */ +var maxConsecutiveAnswers = function(answerKey, k) { + var max = 1; + var numF = answerKey[0] === 'F' ? 1 : 0; + var numT = answerKey[0] === 'T' ? 1 : 0; + var left = 0; + var right = 0; + while (left <= right && right <= answerKey.length - 1) { + if (Math.min(numF, numT) <= k) { + max = Math.max(max, right - left + 1); + right += 1; + answerKey[right] === 'T' ? numT++ : numF++; + } else { + answerKey[left] === 'T' ? numT-- : numF--; + left += 1; + } + } + return max; +}; +``` + +**Explain:** + +Sliding window. + +If we slice a sub string from the answer string, we could either change `T` to `F` or `F` to `T` to make this sub string consecutive. + +Because we can only change `k` times, which means `min(num(T), num(F))` should less or equal than `k`. + +If that sub string is valid, we could move `right` index forward and update the max length of consecutive sub string, otherwise we move `left` index forward. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/2001-2100/2038. Remove Colored Pieces if Both Neighbors are the Same Color.md b/2001-2100/2038. Remove Colored Pieces if Both Neighbors are the Same Color.md new file mode 100644 index 0000000..57b8113 --- /dev/null +++ b/2001-2100/2038. Remove Colored Pieces if Both Neighbors are the Same Color.md @@ -0,0 +1,116 @@ +# 2038. Remove Colored Pieces if Both Neighbors are the Same Color + +- Difficulty: Medium. +- Related Topics: Math, String, Greedy, Game Theory. +- Similar Questions: Longest Subarray With Maximum Bitwise AND. + +## Problem + +There are `n` pieces arranged in a line, and each piece is colored either by `'A'` or by `'B'`. You are given a string `colors` of length `n` where `colors[i]` is the color of the `ith` piece. + +Alice and Bob are playing a game where they take **alternating turns** removing pieces from the line. In this game, Alice moves** first**. + + + +- Alice is only allowed to remove a piece colored `'A'` if **both its neighbors** are also colored `'A'`. She is **not allowed** to remove pieces that are colored `'B'`. + +- Bob is only allowed to remove a piece colored `'B'` if **both its neighbors** are also colored `'B'`. He is **not allowed** to remove pieces that are colored `'A'`. + +- Alice and Bob **cannot** remove pieces from the edge of the line. + +- If a player cannot make a move on their turn, that player **loses** and the other player **wins**. + + +Assuming Alice and Bob play optimally, return `true`** if Alice wins, or return **`false`** if Bob wins**. + +  +Example 1: + +``` +Input: colors = "AAABABB" +Output: true +Explanation: +AAABABB -> AABABB +Alice moves first. +She removes the second 'A' from the left since that is the only 'A' whose neighbors are both 'A'. + +Now it's Bob's turn. +Bob cannot make a move on his turn since there are no 'B's whose neighbors are both 'B'. +Thus, Alice wins, so return true. +``` + +Example 2: + +``` +Input: colors = "AA" +Output: false +Explanation: +Alice has her turn first. +There are only two 'A's and both are on the edge of the line, so she cannot move on her turn. +Thus, Bob wins, so return false. +``` + +Example 3: + +``` +Input: colors = "ABBBBBBBAAA" +Output: false +Explanation: +ABBBBBBBAAA -> ABBBBBBBAA +Alice moves first. +Her only option is to remove the second to last 'A' from the right. + +ABBBBBBBAA -> ABBBBBBAA +Next is Bob's turn. +He has many options for which 'B' piece to remove. He can pick any. + +On Alice's second turn, she has no more pieces that she can remove. +Thus, Bob wins, so return false. +``` + +  +**Constraints:** + + + +- `1 <= colors.length <= 105` + +- `colors` consists of only the letters `'A'` and `'B'` + + + +## Solution + +```javascript +/** + * @param {string} colors + * @return {boolean} + */ +var winnerOfGame = function(colors) { + var i = 0; + var a = 0; + var b = 0; + while (i < colors.length) { + var j = i; + while (colors[j] === colors[i]) j++; + if (j - i >= 3) { + if (colors[i] === 'A') { + a += j - i - 2; + } else { + b += j - i - 2; + } + } + i = j; + } + return a > b; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/2001-2100/2050. Parallel Courses III.md b/2001-2100/2050. Parallel Courses III.md new file mode 100644 index 0000000..48393c2 --- /dev/null +++ b/2001-2100/2050. Parallel Courses III.md @@ -0,0 +1,122 @@ +# 2050. Parallel Courses III + +- Difficulty: Hard. +- Related Topics: Array, Dynamic Programming, Graph, Topological Sort. +- Similar Questions: Course Schedule III, Parallel Courses, Single-Threaded CPU, Process Tasks Using Servers, Maximum Employees to Be Invited to a Meeting. + +## Problem + +You are given an integer `n`, which indicates that there are `n` courses labeled from `1` to `n`. You are also given a 2D integer array `relations` where `relations[j] = [prevCoursej, nextCoursej]` denotes that course `prevCoursej` has to be completed **before** course `nextCoursej` (prerequisite relationship). Furthermore, you are given a **0-indexed** integer array `time` where `time[i]` denotes how many **months** it takes to complete the `(i+1)th` course. + +You must find the **minimum** number of months needed to complete all the courses following these rules: + + + +- You may start taking a course at **any time** if the prerequisites are met. + +- **Any number of courses** can be taken at the **same time**. + + +Return **the **minimum** number of months needed to complete all the courses**. + +**Note:** The test cases are generated such that it is possible to complete every course (i.e., the graph is a directed acyclic graph). + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2021/10/07/ex1.png) + + +``` +Input: n = 3, relations = [[1,3],[2,3]], time = [3,2,5] +Output: 8 +Explanation: The figure above represents the given graph and the time required to complete each course. +We start course 1 and course 2 simultaneously at month 0. +Course 1 takes 3 months and course 2 takes 2 months to complete respectively. +Thus, the earliest time we can start course 3 is at month 3, and the total time required is 3 + 5 = 8 months. +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2021/10/07/ex2.png) + + +``` +Input: n = 5, relations = [[1,5],[2,5],[3,5],[3,4],[4,5]], time = [1,2,3,4,5] +Output: 12 +Explanation: The figure above represents the given graph and the time required to complete each course. +You can start courses 1, 2, and 3 at month 0. +You can complete them after 1, 2, and 3 months respectively. +Course 4 can be taken only after course 3 is completed, i.e., after 3 months. It is completed after 3 + 4 = 7 months. +Course 5 can be taken only after courses 1, 2, 3, and 4 have been completed, i.e., after max(1,2,3,7) = 7 months. +Thus, the minimum time needed to complete all the courses is 7 + 5 = 12 months. +``` + +  +**Constraints:** + + + +- `1 <= n <= 5 * 104` + +- `0 <= relations.length <= min(n * (n - 1) / 2, 5 * 104)` + +- `relations[j].length == 2` + +- `1 <= prevCoursej, nextCoursej <= n` + +- `prevCoursej != nextCoursej` + +- All the pairs `[prevCoursej, nextCoursej]` are **unique**. + +- `time.length == n` + +- `1 <= time[i] <= 104` + +- The given graph is a directed acyclic graph. + + + +## Solution + +```javascript +/** + * @param {number} n + * @param {number[][]} relations + * @param {number[]} time + * @return {number} + */ +var minimumTime = function(n, relations, time) { + var graph = Array(n).fill(0).map(() => []); + for (var i = 0; i < relations.length; i++) { + var [a, b] = relations[i]; + graph[a - 1].push(b - 1); + } + + var max = 0; + var dp = Array(n); + for (var i = 0; i < n; i++) { + max = Math.max(max, dfs(i, graph, time, dp)); + } + return max; +}; + +var dfs = function(i, graph, time, dp) { + if (dp[i] !== undefined) return dp[i]; + var max = 0; + for (var j = 0; j < graph[i].length; j++) { + max = Math.max(max, dfs(graph[i][j], graph, time, dp)); + } + dp[i] = max + time[i]; + return dp[i]; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n + m). +* Space complexity : O(n + m). 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/209. Minimum Size Subarray Sum.md b/201-300/209. Minimum Size Subarray Sum.md new file mode 100644 index 0000000..bd3e94d --- /dev/null +++ b/201-300/209. Minimum Size Subarray Sum.md @@ -0,0 +1,83 @@ +# 209. Minimum Size Subarray Sum + +- Difficulty: Medium. +- Related Topics: Array, Binary Search, Sliding Window, Prefix Sum. +- Similar Questions: Minimum Window Substring, Maximum Size Subarray Sum Equals k, Maximum Length of Repeated Subarray, Minimum Operations to Reduce X to Zero, K Radius Subarray Averages, Maximum Product After K Increments. + +## Problem + +Given an array of positive integers `nums` and a positive integer `target`, return **the **minimal length** of a ****subarray**** whose sum is greater than or equal to** `target`. If there is no such subarray, return `0` instead. + +  +Example 1: + +``` +Input: target = 7, nums = [2,3,1,2,4,3] +Output: 2 +Explanation: The subarray [4,3] has the minimal length under the problem constraint. +``` + +Example 2: + +``` +Input: target = 4, nums = [1,4,4] +Output: 1 +``` + +Example 3: + +``` +Input: target = 11, nums = [1,1,1,1,1,1,1,1] +Output: 0 +``` + +  +**Constraints:** + + + +- `1 <= target <= 109` + +- `1 <= nums.length <= 105` + +- `1 <= nums[i] <= 104` + + +  +**Follow up:** If you have figured out the `O(n)` solution, try coding another solution of which the time complexity is `O(n log(n))`. + +## Solution + +```javascript +/** + * @param {number} target + * @param {number[]} nums + * @return {number} + */ +var minSubArrayLen = function(target, nums) { + var left = 0; + var right = 0; + var sum = nums[0]; + var min = Number.MAX_SAFE_INTEGER; + while (right < nums.length && left <= right) { + if (sum < target) { + right++; + sum += nums[right]; + } else { + min = Math.min(min, right - left + 1); + sum -= nums[left]; + left++; + } + } + return min === Number.MAX_SAFE_INTEGER ? 0 : min; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). 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/213. House Robber II.md b/201-300/213. House Robber II.md new file mode 100644 index 0000000..3ab1d22 --- /dev/null +++ b/201-300/213. House Robber II.md @@ -0,0 +1,74 @@ +# 213. House Robber II + +- Difficulty: Medium. +- Related Topics: Array, Dynamic Programming. +- Similar Questions: House Robber, Paint House, Paint Fence, House Robber III, Non-negative Integers without Consecutive Ones, Coin Path. + +## Problem + +You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are **arranged in a circle.** That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and **it will automatically contact the police if two adjacent houses were broken into on the same night**. + +Given an integer array `nums` representing the amount of money of each house, return **the maximum amount of money you can rob tonight **without alerting the police****. + +  +Example 1: + +``` +Input: nums = [2,3,2] +Output: 3 +Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses. +``` + +Example 2: + +``` +Input: nums = [1,2,3,1] +Output: 4 +Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). +Total amount you can rob = 1 + 3 = 4. +``` + +Example 3: + +``` +Input: nums = [1,2,3] +Output: 3 +``` + +  +**Constraints:** + + + +- `1 <= nums.length <= 100` + +- `0 <= nums[i] <= 1000` + + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @return {number} + */ +var rob = function(nums) { + var arr1 = Array(nums.length); // do not rob the first house + var arr2 = Array(nums.length); // rob the first house + for (var i = nums.length - 1; i > 0; i--) { + arr1[i] = Math.max(nums[i] + (arr1[i + 2] || 0), arr1[i + 1] || 0); + arr2[i] = i === nums.length - 1 ? 0 : Math.max(nums[i] + (arr2[i + 2] || 0), arr2[i + 1] || 0); + } + return Math.max(nums[0] + (arr2[2] || 0), arr1[1] || 0); +}; +``` + +**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/229. Majority Element II.md b/201-300/229. Majority Element II.md new file mode 100644 index 0000000..a787a16 --- /dev/null +++ b/201-300/229. Majority Element II.md @@ -0,0 +1,94 @@ +# 229. Majority Element II + +- Difficulty: Medium. +- Related Topics: Array, Hash Table, Sorting, Counting. +- Similar Questions: Majority Element, Check If a Number Is Majority Element in a Sorted Array, Most Frequent Even Element. + +## Problem + +Given an integer array of size `n`, find all elements that appear more than `⌊ n/3 ⌋` times. + +  +Example 1: + +``` +Input: nums = [3,2,3] +Output: [3] +``` + +Example 2: + +``` +Input: nums = [1] +Output: [1] +``` + +Example 3: + +``` +Input: nums = [1,2] +Output: [1,2] +``` + +  +**Constraints:** + + + +- `1 <= nums.length <= 5 * 104` + +- `-109 <= nums[i] <= 109` + + +  +**Follow up:** Could you solve the problem in linear time and in `O(1)` space? + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @return {number[]} + */ +var majorityElement = function(nums) { + var num1 = Number.MAX_SAFE_INTEGER; + var count1 = 0; + var num2 = Number.MAX_SAFE_INTEGER; + var count2 = 0; + for (var i = 0; i < nums.length; i++) { + if (nums[i] === num1) { + count1 += 1; + } else if (nums[i] === num2) { + count2 += 1; + } else if (count1 === 0) { + num1 = nums[i]; + count1 += 1; + } else if (count2 === 0) { + num2 = nums[i]; + count2 += 1; + } else { + count1 -= 1; + count2 -= 1; + } + } + var realCount1 = 0; + var realCount2 = 0; + for (var i = 0; i < nums.length; i++) { + if (nums[i] === num1) realCount1++; + if (nums[i] === num2) realCount2++; + } + return (realCount1 > nums.length / 3) && (realCount2 > nums.length / 3) + ? [num1, num2] + : ((realCount1 > nums.length / 3) ? [num1] : ((realCount2 > nums.length / 3) ? [num2] : [])) +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/201-300/230. Kth Smallest Element in a BST.md b/201-300/230. Kth Smallest Element in a BST.md new file mode 100644 index 0000000..3784178 --- /dev/null +++ b/201-300/230. Kth Smallest Element in a BST.md @@ -0,0 +1,86 @@ +# 230. Kth Smallest Element in a BST + +- Difficulty: Medium. +- Related Topics: Tree, Depth-First Search, Binary Search Tree, Binary Tree. +- Similar Questions: Binary Tree Inorder Traversal, Second Minimum Node In a Binary Tree. + +## Problem + +Given the `root` of a binary search tree, and an integer `k`, return **the** `kth` **smallest value (**1-indexed**) of all the values of the nodes in the tree**. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2021/01/28/kthtree1.jpg) + +``` +Input: root = [3,1,4,null,2], k = 1 +Output: 1 +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2021/01/28/kthtree2.jpg) + +``` +Input: root = [5,3,6,2,4,null,null,1], k = 3 +Output: 3 +``` + +  +**Constraints:** + + + +- The number of nodes in the tree is `n`. + +- `1 <= k <= n <= 104` + +- `0 <= Node.val <= 104` + + +  +**Follow up:** If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize? + + +## 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} k + * @return {number} + */ +var kthSmallest = function(root, k) { + var queue = [root]; + var num = 0; + while (queue.length) { + var node = queue.pop(); + node.right && queue.push(node.right); + if (node.left) { + queue.push(new TreeNode(node.val)); + queue.push(node.left); + } else { + num++; + if (num === k) return node.val; + } + } +}; +``` + +**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/239. Sliding Window Maximum.md b/201-300/239. Sliding Window Maximum.md new file mode 100644 index 0000000..f774391 --- /dev/null +++ b/201-300/239. Sliding Window Maximum.md @@ -0,0 +1,78 @@ +# 239. Sliding Window Maximum + +- Difficulty: Hard. +- Related Topics: Array, Queue, Sliding Window, Heap (Priority Queue), Monotonic Queue. +- Similar Questions: Minimum Window Substring, Min Stack, Longest Substring with At Most Two Distinct Characters, Paint House II, Jump Game VI, Maximum Number of Robots Within Budget, Maximum Tastiness of Candy Basket, Maximal Score After Applying K Operations. + +## Problem + +You are given an array of integers `nums`, there is a sliding window of size `k` which is moving from the very left of the array to the very right. You can only see the `k` numbers in the window. Each time the sliding window moves right by one position. + +Return **the max sliding window**. + +  +Example 1: + +``` +Input: nums = [1,3,-1,-3,5,3,6,7], k = 3 +Output: [3,3,5,5,6,7] +Explanation: +Window position Max +--------------- ----- +[1 3 -1] -3 5 3 6 7 3 + 1 [3 -1 -3] 5 3 6 7 3 + 1 3 [-1 -3 5] 3 6 7 5 + 1 3 -1 [-3 5 3] 6 7 5 + 1 3 -1 -3 [5 3 6] 7 6 + 1 3 -1 -3 5 [3 6 7] 7 +``` + +Example 2: + +``` +Input: nums = [1], k = 1 +Output: [1] +``` + +  +**Constraints:** + + + +- `1 <= nums.length <= 105` + +- `-104 <= nums[i] <= 104` + +- `1 <= k <= nums.length` + + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @param {number} k + * @return {number[]} + */ +var maxSlidingWindow = function(nums, k) { + var arr = []; + var res = []; + for (var i = 0; i < nums.length; i++) { + while (arr.length && i - arr[0] >= k) arr.shift(); + while (arr.length && nums[i] > nums[arr[arr.length - 1]]) arr.pop(); + arr.push(i); + if (i >= k - 1) res.push(nums[arr[0]]); + } + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/201-300/258. Add Digits.md b/201-300/258. Add Digits.md index d606c02..635bdf1 100644 --- a/201-300/258. Add Digits.md +++ b/201-300/258. Add Digits.md @@ -22,6 +22,32 @@ Could you do it without any loop/recursion in O(1) runtime? ## Solution +```javascript +/** + * @param {number} num + * @return {number} + */ +var addDigits = function(num) { + var res = 0; + while (num) { + res += num % 10; + num = Math.floor(num / 10); + } + return res < 10 ? res : addDigits(res); +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). + +## Solution + ```javascript /** * @param {number} num diff --git a/201-300/260. Single Number III.md b/201-300/260. Single Number III.md new file mode 100644 index 0000000..9b05ec4 --- /dev/null +++ b/201-300/260. Single Number III.md @@ -0,0 +1,78 @@ +# 260. Single Number III + +- Difficulty: Medium. +- Related Topics: Array, Bit Manipulation. +- Similar Questions: Single Number, Single Number II, Find The Original Array of Prefix Xor. + +## Problem + +Given an integer array `nums`, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in **any order**. + +You must write an algorithm that runs in linear runtime complexity and uses only constant extra space. + +  +Example 1: + +``` +Input: nums = [1,2,1,3,2,5] +Output: [3,5] +Explanation: [5, 3] is also a valid answer. +``` + +Example 2: + +``` +Input: nums = [-1,0] +Output: [-1,0] +``` + +Example 3: + +``` +Input: nums = [0,1] +Output: [1,0] +``` + +  +**Constraints:** + + + +- `2 <= nums.length <= 3 * 104` + +- `-231 <= nums[i] <= 231 - 1` + +- Each integer in `nums` will appear twice, only two integers will appear once. + + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @return {number[]} + */ +var singleNumber = function(nums) { + var num = nums.reduce((s, n) => s ^ n, 0); + var lastBitNum = num & -num; + var res = [0, 0]; + for (var i = 0; i < nums.length; i++) { + if (nums[i] & lastBitNum) { + res[0] ^= nums[i]; + } else { + res[1] ^= nums[i]; + } + } + return res; +}; +``` + +**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/287. Find the Duplicate Number.md b/201-300/287. Find the Duplicate Number.md new file mode 100644 index 0000000..4fdfbfc --- /dev/null +++ b/201-300/287. Find the Duplicate Number.md @@ -0,0 +1,93 @@ +# 287. Find the Duplicate Number + +- Difficulty: Medium. +- Related Topics: Array, Two Pointers, Binary Search, Bit Manipulation. +- Similar Questions: First Missing Positive, Single Number, Linked List Cycle II, Missing Number, Set Mismatch. + +## Problem + +Given an array of integers `nums` containing `n + 1` integers where each integer is in the range `[1, n]` inclusive. + +There is only **one repeated number** in `nums`, return **this repeated number**. + +You must solve the problem **without** modifying the array `nums` and uses only constant extra space. + +  +Example 1: + +``` +Input: nums = [1,3,4,2,2] +Output: 2 +``` + +Example 2: + +``` +Input: nums = [3,1,3,4,2] +Output: 3 +``` + +  +**Constraints:** + + + +- `1 <= n <= 105` + +- `nums.length == n + 1` + +- `1 <= nums[i] <= n` + +- All the integers in `nums` appear only **once** except for **precisely one integer** which appears **two or more** times. + + +  +**Follow up:** + + + +- How can we prove that at least one duplicate number must exist in `nums`? + +- Can you solve the problem in linear runtime complexity? + + + +## Solution 1 + +```javascript +/** + * @param {number[]} nums + * @return {number} + */ +var findDuplicate = function(nums) { + var left = 0; + var right = nums.length - 1; + while (left < right) { + var mid = left + Math.floor((right - left) / 2); + var num = getNum(nums, mid); + if (num <= mid) { + left = mid + 1; + } else { + right = mid; + } + } + return left; +}; + +var getNum = function(nums, n) { + var num = 0; + for (var i = 0; i < nums.length; i++) { + if (nums[i] <= n) num++; + } + return num; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * log(n)). +* Space complexity : O(1). 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/295. Find Median from Data Stream.md b/201-300/295. Find Median from Data Stream.md new file mode 100644 index 0000000..af4c123 --- /dev/null +++ b/201-300/295. Find Median from Data Stream.md @@ -0,0 +1,131 @@ +# 295. Find Median from Data Stream + +- Difficulty: Hard. +- Related Topics: Two Pointers, Design, Sorting, Heap (Priority Queue), Data Stream. +- Similar Questions: Sliding Window Median, Finding MK Average, Sequentially Ordinal Rank Tracker. + +## Problem + +The **median** is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values. + + + +- For example, for `arr = [2,3,4]`, the median is `3`. + +- For example, for `arr = [2,3]`, the median is `(2 + 3) / 2 = 2.5`. + + +Implement the MedianFinder class: + + + +- `MedianFinder()` initializes the `MedianFinder` object. + +- `void addNum(int num)` adds the integer `num` from the data stream to the data structure. + +- `double findMedian()` returns the median of all elements so far. Answers within `10-5` of the actual answer will be accepted. + + +  +Example 1: + +``` +Input +["MedianFinder", "addNum", "addNum", "findMedian", "addNum", "findMedian"] +[[], [1], [2], [], [3], []] +Output +[null, null, null, 1.5, null, 2.0] + +Explanation +MedianFinder medianFinder = new MedianFinder(); +medianFinder.addNum(1); // arr = [1] +medianFinder.addNum(2); // arr = [1, 2] +medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2) +medianFinder.addNum(3); // arr[1, 2, 3] +medianFinder.findMedian(); // return 2.0 +``` + +  +**Constraints:** + + + +- `-105 <= num <= 105` + +- There will be at least one element in the data structure before calling `findMedian`. + +- At most `5 * 104` calls will be made to `addNum` and `findMedian`. + + +  +**Follow up:** + + + +- If all integer numbers from the stream are in the range `[0, 100]`, how would you optimize your solution? + +- If `99%` of all integer numbers from the stream are in the range `[0, 100]`, how would you optimize your solution? + + + +## Solution + +```javascript +var MedianFinder = function() { + this.arr = []; +}; + +/** + * @param {number} num + * @return {void} + */ +MedianFinder.prototype.addNum = function(num) { + if (!this.arr.length) { + this.arr.push(num); + return; + } + var left = 0; + var right = this.arr.length - 1; + while (left <= right) { + if (left === right) { + this.arr.splice(this.arr[left] >= num ? left : (left + 1), 0, num); + return; + } + var mid = left + Math.floor((right - left) / 2); + if (this.arr[mid] === num) { + left = mid; + right = mid; + } else if (this.arr[mid] > num) { + right = mid; + } else { + left = mid + 1; + } + } +}; + +/** + * @return {number} + */ +MedianFinder.prototype.findMedian = function() { + return this.arr.length % 2 + ? this.arr[(this.arr.length - 1) / 2] + : (this.arr[this.arr.length / 2] + this.arr[this.arr.length / 2 - 1]) / 2; + +}; + +/** + * Your MedianFinder object will be instantiated and called as such: + * var obj = new MedianFinder() + * obj.addNum(num) + * var param_2 = obj.findMedian() + */ +``` + +**Explain:** + +Binary search. + +**Complexity:** + +* Time complexity : O(n * log(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/2124. Check if All A's Appears Before All B's.md b/2101-2200/2124. Check if All A's Appears Before All B's.md new file mode 100644 index 0000000..6c58929 --- /dev/null +++ b/2101-2200/2124. Check if All A's Appears Before All B's.md @@ -0,0 +1,76 @@ +# 2124. Check if All A's Appears Before All B's + +- Difficulty: Easy. +- Related Topics: String. +- Similar Questions: Minimum Deletions to Make String Balanced, Check if Array Is Sorted and Rotated, Check if Numbers Are Ascending in a Sentence. + +## Problem + +Given a string `s` consisting of **only** the characters `'a'` and `'b'`, return `true` **if **every** **`'a'` **appears before **every** **`'b'`** in the string**. Otherwise, return `false`. + +  +Example 1: + +``` +Input: s = "aaabbb" +Output: true +Explanation: +The 'a's are at indices 0, 1, and 2, while the 'b's are at indices 3, 4, and 5. +Hence, every 'a' appears before every 'b' and we return true. +``` + +Example 2: + +``` +Input: s = "abab" +Output: false +Explanation: +There is an 'a' at index 2 and a 'b' at index 1. +Hence, not every 'a' appears before every 'b' and we return false. +``` + +Example 3: + +``` +Input: s = "bbb" +Output: true +Explanation: +There are no 'a's, hence, every 'a' appears before every 'b' and we return true. +``` + +  +**Constraints:** + + + +- `1 <= s.length <= 100` + +- `s[i]` is either `'a'` or `'b'`. + + + +## Solution + +```javascript +/** + * @param {string} s + * @return {boolean} + */ +var checkString = function(s) { + var hasB = false; + for (var i = 0; i < s.length; i++) { + if (s[i] === 'a' && hasB) return false; + hasB = s[i] === 'b'; + } + return true; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). 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/2130. Maximum Twin Sum of a Linked List.md b/2101-2200/2130. Maximum Twin Sum of a Linked List.md new file mode 100644 index 0000000..4665f07 --- /dev/null +++ b/2101-2200/2130. Maximum Twin Sum of a Linked List.md @@ -0,0 +1,116 @@ +# 2130. Maximum Twin Sum of a Linked List + +- Difficulty: Medium. +- Related Topics: Linked List, Two Pointers, Stack. +- Similar Questions: Reverse Linked List, Palindrome Linked List, Middle of the Linked List. + +## Problem + +In a linked list of size `n`, where `n` is **even**, the `ith` node (**0-indexed**) of the linked list is known as the **twin** of the `(n-1-i)th` node, if `0 <= i <= (n / 2) - 1`. + + + +- For example, if `n = 4`, then node `0` is the twin of node `3`, and node `1` is the twin of node `2`. These are the only nodes with twins for `n = 4`. + + +The **twin sum **is defined as the sum of a node and its twin. + +Given the `head` of a linked list with even length, return **the **maximum twin sum** of the linked list**. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2021/12/03/eg1drawio.png) + +``` +Input: head = [5,4,2,1] +Output: 6 +Explanation: +Nodes 0 and 1 are the twins of nodes 3 and 2, respectively. All have twin sum = 6. +There are no other nodes with twins in the linked list. +Thus, the maximum twin sum of the linked list is 6. +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2021/12/03/eg2drawio.png) + +``` +Input: head = [4,2,2,3] +Output: 7 +Explanation: +The nodes with twins present in this linked list are: +- Node 0 is the twin of node 3 having a twin sum of 4 + 3 = 7. +- Node 1 is the twin of node 2 having a twin sum of 2 + 2 = 4. +Thus, the maximum twin sum of the linked list is max(7, 4) = 7. +``` + +Example 3: + +![](https://assets.leetcode.com/uploads/2021/12/03/eg3drawio.png) + +``` +Input: head = [1,100000] +Output: 100001 +Explanation: +There is only one node with a twin in the linked list having twin sum of 1 + 100000 = 100001. +``` + +  +**Constraints:** + + + +- The number of nodes in the list is an **even** integer 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 pairSum = function(head) { + var num = 0; + var node = head; + while (node) { + num++; + node = node.next; + } + + var stack = []; + var sum = 0; + var i = 0; + while (i < num) { + if (i < num / 2) { + stack.push(head.val); + } else { + sum = Math.max(sum, head.val + stack.pop()); + } + i += 1; + head = head.next; + } + + return sum; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/2101-2200/2140. Solving Questions With Brainpower.md b/2101-2200/2140. Solving Questions With Brainpower.md new file mode 100644 index 0000000..b4c795e --- /dev/null +++ b/2101-2200/2140. Solving Questions With Brainpower.md @@ -0,0 +1,93 @@ +# 2140. Solving Questions With Brainpower + +- Difficulty: Medium. +- Related Topics: Array, Dynamic Programming. +- Similar Questions: House Robber, Frog Jump. + +## Problem + +You are given a **0-indexed** 2D integer array `questions` where `questions[i] = [pointsi, brainpoweri]`. + +The array describes the questions of an exam, where you have to process the questions **in order** (i.e., starting from question `0`) and make a decision whether to **solve** or **skip** each question. Solving question `i` will **earn** you `pointsi` points but you will be **unable** to solve each of the next `brainpoweri` questions. If you skip question `i`, you get to make the decision on the next question. + + + For example, given `questions = [[3, 2], [4, 3], [4, 4], [2, 5]]`: + + + +- If question `0` is solved, you will earn `3` points but you will be unable to solve questions `1` and `2`. + +- If instead, question `0` is skipped and question `1` is solved, you will earn `4` points but you will be unable to solve questions `2` and `3`. + + + + +Return **the **maximum** points you can earn for the exam**. + +  +Example 1: + +``` +Input: questions = [[3,2],[4,3],[4,4],[2,5]] +Output: 5 +Explanation: The maximum points can be earned by solving questions 0 and 3. +- Solve question 0: Earn 3 points, will be unable to solve the next 2 questions +- Unable to solve questions 1 and 2 +- Solve question 3: Earn 2 points +Total points earned: 3 + 2 = 5. There is no other way to earn 5 or more points. +``` + +Example 2: + +``` +Input: questions = [[1,1],[2,2],[3,3],[4,4],[5,5]] +Output: 7 +Explanation: The maximum points can be earned by solving questions 1 and 4. +- Skip question 0 +- Solve question 1: Earn 2 points, will be unable to solve the next 2 questions +- Unable to solve questions 2 and 3 +- Solve question 4: Earn 5 points +Total points earned: 2 + 5 = 7. There is no other way to earn 7 or more points. +``` + +  +**Constraints:** + + + +- `1 <= questions.length <= 105` + +- `questions[i].length == 2` + +- `1 <= pointsi, brainpoweri <= 105` + + + +## Solution + +```javascript +/** + * @param {number[][]} questions + * @return {number} + */ +var mostPoints = function(questions) { + var dp = Array(questions.length); + for (var i = questions.length - 1; i >= 0; i--) { + var [points, brainpower] = questions[i]; + dp[i] = Math.max( + points + (dp[i + brainpower + 1] || 0), + dp[i + 1] || 0, + ); + } + return dp[0]; +}; +``` + +**Explain:** + +Dynamic-programming. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/2101-2200/2147. Number of Ways to Divide a Long Corridor.md b/2101-2200/2147. Number of Ways to Divide a Long Corridor.md new file mode 100644 index 0000000..1b49581 --- /dev/null +++ b/2101-2200/2147. Number of Ways to Divide a Long Corridor.md @@ -0,0 +1,103 @@ +# 2147. Number of Ways to Divide a Long Corridor + +- Difficulty: Hard. +- Related Topics: Math, String, Dynamic Programming. +- Similar Questions: Decode Ways II, Minimum Cost to Cut a Stick, Ways to Split Array Into Three Subarrays. + +## Problem + +Along a long library corridor, there is a line of seats and decorative plants. You are given a **0-indexed** string `corridor` of length `n` consisting of letters `'S'` and `'P'` where each `'S'` represents a seat and each `'P'` represents a plant. + +One room divider has **already** been installed to the left of index `0`, and **another** to the right of index `n - 1`. Additional room dividers can be installed. For each position between indices `i - 1` and `i` (`1 <= i <= n - 1`), at most one divider can be installed. + +Divide the corridor into non-overlapping sections, where each section has **exactly two seats** with any number of plants. There may be multiple ways to perform the division. Two ways are **different** if there is a position with a room divider installed in the first way but not in the second way. + +Return **the number of ways to divide the corridor**. Since the answer may be very large, return it **modulo** `109 + 7`. If there is no way, return `0`. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2021/12/04/1.png) + +``` +Input: corridor = "SSPPSPS" +Output: 3 +Explanation: There are 3 different ways to divide the corridor. +The black bars in the above image indicate the two room dividers already installed. +Note that in each of the ways, each section has exactly two seats. +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2021/12/04/2.png) + +``` +Input: corridor = "PPSPSP" +Output: 1 +Explanation: There is only 1 way to divide the corridor, by not installing any additional dividers. +Installing any would create some section that does not have exactly two seats. +``` + +Example 3: + +![](https://assets.leetcode.com/uploads/2021/12/12/3.png) + +``` +Input: corridor = "S" +Output: 0 +Explanation: There is no way to divide the corridor because there will always be a section that does not have exactly two seats. +``` + +  +**Constraints:** + + + +- `n == corridor.length` + +- `1 <= n <= 105` + +- `corridor[i]` is either `'S'` or `'P'`. + + + +## Solution + +```javascript +/** + * @param {string} corridor + * @return {number} + */ +var numberOfWays = function(corridor) { + var num = BigInt(1); + var mod = BigInt(Math.pow(10, 9) + 7); + var seatNum = 0; + var plantNum = 0; + for (var i = 0; i < corridor.length; i++) { + if (corridor[i] === 'S') { + if (seatNum === 2) { + num *= BigInt(plantNum + 1); + num %= mod; + seatNum = 1; + plantNum = 0; + } else { + seatNum += 1; + } + } else { + if (seatNum === 2) { + plantNum += 1; + } + } + } + return seatNum === 2 ? Number(num) : 0; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* 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/2101-2200/2192. All Ancestors of a Node in a Directed Acyclic Graph.md b/2101-2200/2192. All Ancestors of a Node in a Directed Acyclic Graph.md new file mode 100644 index 0000000..df38d6e --- /dev/null +++ b/2101-2200/2192. All Ancestors of a Node in a Directed Acyclic Graph.md @@ -0,0 +1,112 @@ +# 2192. All Ancestors of a Node in a Directed Acyclic Graph + +- Difficulty: Medium. +- Related Topics: Depth-First Search, Breadth-First Search, Graph, Topological Sort. +- Similar Questions: Number of Restricted Paths From First to Last Node. + +## Problem + +You are given a positive integer `n` representing the number of nodes of a **Directed Acyclic Graph** (DAG). The nodes are numbered from `0` to `n - 1` (**inclusive**). + +You are also given a 2D integer array `edges`, where `edges[i] = [fromi, toi]` denotes that there is a **unidirectional** edge from `fromi` to `toi` in the graph. + +Return **a list** `answer`**, where **`answer[i]`** is the **list of ancestors** of the** `ith` **node, sorted in **ascending order****. + +A node `u` is an **ancestor** of another node `v` if `u` can reach `v` via a set of edges. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2019/12/12/e1.png) + +``` +Input: n = 8, edgeList = [[0,3],[0,4],[1,3],[2,4],[2,7],[3,5],[3,6],[3,7],[4,6]] +Output: [[],[],[],[0,1],[0,2],[0,1,3],[0,1,2,3,4],[0,1,2,3]] +Explanation: +The above diagram represents the input graph. +- Nodes 0, 1, and 2 do not have any ancestors. +- Node 3 has two ancestors 0 and 1. +- Node 4 has two ancestors 0 and 2. +- Node 5 has three ancestors 0, 1, and 3. +- Node 6 has five ancestors 0, 1, 2, 3, and 4. +- Node 7 has four ancestors 0, 1, 2, and 3. +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2019/12/12/e2.png) + +``` +Input: n = 5, edgeList = [[0,1],[0,2],[0,3],[0,4],[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]] +Output: [[],[0],[0,1],[0,1,2],[0,1,2,3]] +Explanation: +The above diagram represents the input graph. +- Node 0 does not have any ancestor. +- Node 1 has one ancestor 0. +- Node 2 has two ancestors 0 and 1. +- Node 3 has three ancestors 0, 1, and 2. +- Node 4 has four ancestors 0, 1, 2, and 3. +``` + +  +**Constraints:** + + + +- `1 <= n <= 1000` + +- `0 <= edges.length <= min(2000, n * (n - 1) / 2)` + +- `edges[i].length == 2` + +- `0 <= fromi, toi <= n - 1` + +- `fromi != toi` + +- There are no duplicate edges. + +- The graph is **directed** and **acyclic**. + + + +## Solution + +```javascript +/** + * @param {number} n + * @param {number[][]} edges + * @return {number[][]} + */ +var getAncestors = function(n, edges) { + const parentMap = Array(n).fill(0).map(() => []); + const ancestorMap = Array(n); + for (var i = 0; i < edges.length; i++) { + parentMap[edges[i][1]].push(edges[i][0]); + } + for (var i = 0; i < n; i++) { + find(i, parentMap, ancestorMap); + } + return ancestorMap.map(item => item.sort((a, b) => a - b)); +}; + +var find = function(i, parentMap, ancestorMap) { + if (!ancestorMap[i]) { + var res = []; + var arr = parentMap[i]; + for (var j = 0; j < arr.length; j++) { + res.push(arr[j], ...find(arr[j], parentMap, ancestorMap)); + } + ancestorMap[i] = Array.from(new Set(res)); + } + return ancestorMap[i]; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/2101-2200/2196. Create Binary Tree From Descriptions.md b/2101-2200/2196. Create Binary Tree From Descriptions.md new file mode 100644 index 0000000..0472fc2 --- /dev/null +++ b/2101-2200/2196. Create Binary Tree From Descriptions.md @@ -0,0 +1,103 @@ +# 2196. Create Binary Tree From Descriptions + +- Difficulty: Medium. +- Related Topics: Array, Hash Table, Tree, Depth-First Search, Breadth-First Search, Binary Tree. +- Similar Questions: Convert Sorted List to Binary Search Tree, Number Of Ways To Reconstruct A Tree. + +## Problem + +You are given a 2D integer array `descriptions` where `descriptions[i] = [parenti, childi, isLefti]` indicates that `parenti` is the **parent** of `childi` in a **binary** tree of **unique** values. Furthermore, + + + +- If `isLefti == 1`, then `childi` is the left child of `parenti`. + +- If `isLefti == 0`, then `childi` is the right child of `parenti`. + + +Construct the binary tree described by `descriptions` and return **its **root****. + +The test cases will be generated such that the binary tree is **valid**. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2022/02/09/example1drawio.png) + +``` +Input: descriptions = [[20,15,1],[20,17,0],[50,20,1],[50,80,0],[80,19,1]] +Output: [50,20,80,15,17,19] +Explanation: The root node is the node with value 50 since it has no parent. +The resulting binary tree is shown in the diagram. +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2022/02/09/example2drawio.png) + +``` +Input: descriptions = [[1,2,1],[2,3,0],[3,4,1]] +Output: [1,2,null,null,3,4] +Explanation: The root node is the node with value 1 since it has no parent. +The resulting binary tree is shown in the diagram. +``` + +  +**Constraints:** + + + +- `1 <= descriptions.length <= 104` + +- `descriptions[i].length == 3` + +- `1 <= parenti, childi <= 105` + +- `0 <= isLefti <= 1` + +- The binary tree described by `descriptions` is valid. + + + +## 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 {number[][]} descriptions + * @return {TreeNode} + */ +var createBinaryTree = function(descriptions) { + var nodeMap = {}; + var hasNoParentMap = {}; + for (var i = 0; i < descriptions.length; i++) { + var [parent, child, isLeft] = descriptions[i]; + if (hasNoParentMap[parent] === undefined) hasNoParentMap[parent] = true; + hasNoParentMap[child] = false; + if (!nodeMap[parent]) nodeMap[parent] = new TreeNode(parent); + if (!nodeMap[child]) nodeMap[child] = new TreeNode(child); + if (isLeft) { + nodeMap[parent].left = nodeMap[child]; + } else { + nodeMap[parent].right = nodeMap[child]; + } + } + return nodeMap[Object.keys(hasNoParentMap).filter(key => hasNoParentMap[key])[0]]; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/2201-2300/2215. Find the Difference of Two Arrays.md b/2201-2300/2215. Find the Difference of Two Arrays.md new file mode 100644 index 0000000..656036a --- /dev/null +++ b/2201-2300/2215. Find the Difference of Two Arrays.md @@ -0,0 +1,90 @@ +# 2215. Find the Difference of Two Arrays + +- Difficulty: Easy. +- Related Topics: Array, Hash Table. +- Similar Questions: Intersection of Two Arrays, Intersection of Two Arrays II, Intersection of Multiple Arrays. + +## Problem + +Given two **0-indexed** integer arrays `nums1` and `nums2`, return **a list** `answer` **of size** `2` **where:** + + + +- `answer[0]` **is a list of all **distinct** integers in** `nums1` **which are **not** present in** `nums2`**.** + +- `answer[1]` **is a list of all **distinct** integers in** `nums2` **which are **not** present in** `nums1`. + + +**Note** that the integers in the lists may be returned in **any** order. + +  +Example 1: + +``` +Input: nums1 = [1,2,3], nums2 = [2,4,6] +Output: [[1,3],[4,6]] +Explanation: +For nums1, nums1[1] = 2 is present at index 0 of nums2, whereas nums1[0] = 1 and nums1[2] = 3 are not present in nums2. Therefore, answer[0] = [1,3]. +For nums2, nums2[0] = 2 is present at index 1 of nums1, whereas nums2[1] = 4 and nums2[2] = 6 are not present in nums2. Therefore, answer[1] = [4,6]. +``` + +Example 2: + +``` +Input: nums1 = [1,2,3,3], nums2 = [1,1,2,2] +Output: [[3],[]] +Explanation: +For nums1, nums1[2] and nums1[3] are not present in nums2. Since nums1[2] == nums1[3], their value is only included once and answer[0] = [3]. +Every integer in nums2 is present in nums1. Therefore, answer[1] = []. +``` + +  +**Constraints:** + + + +- `1 <= nums1.length, nums2.length <= 1000` + +- `-1000 <= nums1[i], nums2[i] <= 1000` + + + +## Solution + +```javascript +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number[][]} + */ +var findDifference = function(nums1, nums2) { + var map = {}; + for (var i = 0; i < nums1.length; i++) { + map[nums1[i]] = (map[nums1[i]] || 0) | 1; + } + for (var i = 0; i < nums2.length; i++) { + map[nums2[i]] = (map[nums2[i]] || 0) | 2; + } + var res = [new Set(), new Set()]; + for (var i = 0; i < nums1.length; i++) { + if (!(map[nums1[i]] & 2)) { + res[0].add(nums1[i]); + } + } + for (var i = 0; i < nums2.length; i++) { + if (!(map[nums2[i]] & 1)) { + res[1].add(nums2[i]); + } + } + return res.map(item => Array.from(item)); +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/2201-2300/2244. Minimum Rounds to Complete All Tasks.md b/2201-2300/2244. Minimum Rounds to Complete All Tasks.md new file mode 100644 index 0000000..caf22be --- /dev/null +++ b/2201-2300/2244. Minimum Rounds to Complete All Tasks.md @@ -0,0 +1,76 @@ +# 2244. Minimum Rounds to Complete All Tasks + +- Difficulty: Medium. +- Related Topics: Array, Hash Table, Greedy, Counting. +- Similar Questions: Climbing Stairs, Odd String Difference. + +## Problem + +You are given a **0-indexed** integer array `tasks`, where `tasks[i]` represents the difficulty level of a task. In each round, you can complete either 2 or 3 tasks of the **same difficulty level**. + +Return **the **minimum** rounds required to complete all the tasks, or **`-1`** if it is not possible to complete all the tasks.** + +  +Example 1: + +``` +Input: tasks = [2,2,3,3,2,4,4,4,4,4] +Output: 4 +Explanation: To complete all the tasks, a possible plan is: +- In the first round, you complete 3 tasks of difficulty level 2. +- In the second round, you complete 2 tasks of difficulty level 3. +- In the third round, you complete 3 tasks of difficulty level 4. +- In the fourth round, you complete 2 tasks of difficulty level 4. +It can be shown that all the tasks cannot be completed in fewer than 4 rounds, so the answer is 4. +``` + +Example 2: + +``` +Input: tasks = [2,3,3] +Output: -1 +Explanation: There is only 1 task of difficulty level 2, but in each round, you can only complete either 2 or 3 tasks of the same difficulty level. Hence, you cannot complete all the tasks, and the answer is -1. +``` + +  +**Constraints:** + + + +- `1 <= tasks.length <= 105` + +- `1 <= tasks[i] <= 109` + + + +## Solution + +```javascript +/** + * @param {number[]} tasks + * @return {number} + */ +var minimumRounds = function(tasks) { + var map = {}; + for (var i = 0; i < tasks.length; i++) { + if (!map[tasks[i]]) map[tasks[i]] = 0; + map[tasks[i]]++; + } + var keys = Object.keys(map); + var res = 0; + for (var j = 0; j < keys.length; j++) { + if (map[keys[j]] === 1) return -1; + res += Math.ceil(map[keys[j]] / 3); + } + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/2201-2300/2251. Number of Flowers in Full Bloom.md b/2201-2300/2251. Number of Flowers in Full Bloom.md new file mode 100644 index 0000000..1d20357 --- /dev/null +++ b/2201-2300/2251. Number of Flowers in Full Bloom.md @@ -0,0 +1,102 @@ +# 2251. Number of Flowers in Full Bloom + +- Difficulty: Hard. +- Related Topics: Array, Hash Table, Binary Search, Sorting, Prefix Sum, Ordered Set. +- Similar Questions: Meeting Rooms II, Minimum Interval to Include Each Query. + +## Problem + +You are given a **0-indexed** 2D integer array `flowers`, where `flowers[i] = [starti, endi]` means the `ith` flower will be in **full bloom** from `starti` to `endi` (**inclusive**). You are also given a **0-indexed** integer array `people` of size `n`, where `people[i]` is the time that the `ith` person will arrive to see the flowers. + +Return **an integer array **`answer`** of size **`n`**, where **`answer[i]`** is the **number** of flowers that are in full bloom when the **`ith`** person arrives.** + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2022/03/02/ex1new.jpg) + +``` +Input: flowers = [[1,6],[3,7],[9,12],[4,13]], poeple = [2,3,7,11] +Output: [1,2,2,2] +Explanation: The figure above shows the times when the flowers are in full bloom and when the people arrive. +For each person, we return the number of flowers in full bloom during their arrival. +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2022/03/02/ex2new.jpg) + +``` +Input: flowers = [[1,10],[3,3]], poeple = [3,3,2] +Output: [2,2,1] +Explanation: The figure above shows the times when the flowers are in full bloom and when the people arrive. +For each person, we return the number of flowers in full bloom during their arrival. +``` + +  +**Constraints:** + + + +- `1 <= flowers.length <= 5 * 104` + +- `flowers[i].length == 2` + +- `1 <= starti <= endi <= 109` + +- `1 <= people.length <= 5 * 104` + +- `1 <= people[i] <= 109` + + + +## Solution + +```javascript +/** + * @param {number[][]} flowers + * @param {number[]} people + * @return {number[]} + */ +var fullBloomFlowers = function(flowers, people) { + var flowersSortByStart = flowers.map(flower => flower[0]).sort((a, b) => a - b); + var flowersSortByEnd = flowers.map(flower => flower[1]).sort((a, b) => a - b); + var peopleTimesSort = Array.from(people).sort((a, b) => a - b); + var map = {}; + var startIndex = 0; + var endIndex = 0; + for (var i = 0; i < peopleTimesSort.length; i++) { + var time = peopleTimesSort[i]; + // number of flowers started before or in time + startIndex = findStartIndex(flowersSortByStart, time, startIndex); + // number of flowers ended before time + endIndex = findEndIndex(flowersSortByEnd, time, endIndex); + // full bloom flower number = flower started number - flower ended number + map[time] = startIndex - endIndex; + } + return people.map((time) => map[time]); +}; + +var findStartIndex = function(times, time, from) { + for (var i = from; i <= times.length; i++) { + if (times[i] <= time) continue; + return i; + } +}; + +var findEndIndex = function(times, time, from) { + for (var i = from; i <= times.length; i++) { + if (times[i] < time) continue; + return i; + } +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(nlog(n) + mlog(m) + n + m). +* Space complexity : O(n + m). diff --git a/2201-2300/2264. Largest 3-Same-Digit Number in String.md b/2201-2300/2264. Largest 3-Same-Digit Number in String.md new file mode 100644 index 0000000..15223fd --- /dev/null +++ b/2201-2300/2264. Largest 3-Same-Digit Number in String.md @@ -0,0 +1,97 @@ +# 2264. Largest 3-Same-Digit Number in String + +- Difficulty: Easy. +- Related Topics: String. +- Similar Questions: Largest Odd Number in String. + +## Problem + +You are given a string `num` representing a large integer. An integer is **good** if it meets the following conditions: + + + +- It is a **substring** of `num` with length `3`. + +- It consists of only one unique digit. + + +Return **the **maximum good **integer as a **string** or an empty string **`""`** if no such integer exists**. + +Note: + + + +- A **substring** is a contiguous sequence of characters within a string. + +- There may be **leading zeroes** in `num` or a good integer. + + +  +Example 1: + +``` +Input: num = "6777133339" +Output: "777" +Explanation: There are two distinct good integers: "777" and "333". +"777" is the largest, so we return "777". +``` + +Example 2: + +``` +Input: num = "2300019" +Output: "000" +Explanation: "000" is the only good integer. +``` + +Example 3: + +``` +Input: num = "42352338" +Output: "" +Explanation: No substring of length 3 consists of only one unique digit. Therefore, there are no good integers. +``` + +  +**Constraints:** + + + +- `3 <= num.length <= 1000` + +- `num` only consists of digits. + + + +## Solution + +```javascript +/** + * @param {string} num + * @return {string} + */ +var largestGoodInteger = function(num) { + var maxDigit = ''; + var digitLength = 0; + for (var i = 0; i < num.length; i++) { + if (num[i] === num[i - 1]) { + digitLength += 1; + if (digitLength >= 3 && num[i] > maxDigit) { + maxDigit = num[i]; + } + } else { + digitLength = 1; + } + } + return maxDigit.repeat(3); +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/2201-2300/2265. Count Nodes Equal to Average of Subtree.md b/2201-2300/2265. Count Nodes Equal to Average of Subtree.md new file mode 100644 index 0000000..39fe715 --- /dev/null +++ b/2201-2300/2265. Count Nodes Equal to Average of Subtree.md @@ -0,0 +1,94 @@ +# 2265. Count Nodes Equal to Average of Subtree + +- Difficulty: Medium. +- Related Topics: Tree, Depth-First Search, Binary Tree. +- Similar Questions: Maximum Average Subtree, Insufficient Nodes in Root to Leaf Paths, Count Nodes Equal to Sum of Descendants. + +## Problem + +Given the `root` of a binary tree, return **the number of nodes where the value of the node is equal to the **average** of the values in its **subtree****. + +**Note:** + + + +- The **average** of `n` elements is the **sum** of the `n` elements divided by `n` and **rounded down** to the nearest integer. + +- A **subtree** of `root` is a tree consisting of `root` and all of its descendants. + + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2022/03/15/image-20220315203925-1.png) + +``` +Input: root = [4,8,5,0,1,null,6] +Output: 5 +Explanation: +For the node with value 4: The average of its subtree is (4 + 8 + 5 + 0 + 1 + 6) / 6 = 24 / 6 = 4. +For the node with value 5: The average of its subtree is (5 + 6) / 2 = 11 / 2 = 5. +For the node with value 0: The average of its subtree is 0 / 1 = 0. +For the node with value 1: The average of its subtree is 1 / 1 = 1. +For the node with value 6: The average of its subtree is 6 / 1 = 6. +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2022/03/26/image-20220326133920-1.png) + +``` +Input: root = [1] +Output: 1 +Explanation: For the node with value 1: The average of its subtree is 1 / 1 = 1. +``` + +  +**Constraints:** + + + +- The number of nodes in the tree is in the range `[1, 1000]`. + +- `0 <= 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 {number} + */ +var averageOfSubtree = function(root) { + return helper(root).res; +}; + +var helper = function(root) { + if (!root) return { sum: 0, num: 0, res: 0 }; + var left = helper(root.left); + var right = helper(root.right); + var sum = left.sum + right.sum + root.val; + var num = left.num + right.num + 1; + var res = left.res + right.res + (Math.floor(sum / num) === root.val ? 1 : 0); + return { sum, num, res }; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/2201-2300/2289. Steps to Make Array Non-decreasing.md b/2201-2300/2289. Steps to Make Array Non-decreasing.md new file mode 100644 index 0000000..a56ad68 --- /dev/null +++ b/2201-2300/2289. Steps to Make Array Non-decreasing.md @@ -0,0 +1,72 @@ +# 2289. Steps to Make Array Non-decreasing + +- Difficulty: Medium. +- Related Topics: Array, Linked List, Stack, Monotonic Stack. +- Similar Questions: Remove One Element to Make the Array Strictly Increasing. + +## Problem + +You are given a **0-indexed** integer array `nums`. In one step, **remove** all elements `nums[i]` where `nums[i - 1] > nums[i]` for all `0 < i < nums.length`. + +Return **the number of steps performed until **`nums`** becomes a **non-decreasing** array**. + +  +Example 1: + +``` +Input: nums = [5,3,4,4,7,3,6,11,8,5,11] +Output: 3 +Explanation: The following are the steps performed: +- Step 1: [5,3,4,4,7,3,6,11,8,5,11] becomes [5,4,4,7,6,11,11] +- Step 2: [5,4,4,7,6,11,11] becomes [5,4,7,11,11] +- Step 3: [5,4,7,11,11] becomes [5,7,11,11] +[5,7,11,11] is a non-decreasing array. Therefore, we return 3. +``` + +Example 2: + +``` +Input: nums = [4,5,7,7,13] +Output: 0 +Explanation: nums is already a non-decreasing array. Therefore, we return 0. +``` + +  +**Constraints:** + + + +- `1 <= nums.length <= 105` + +- `1 <= nums[i] <= 109` + + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @return {number} + */ +var totalSteps = function(nums) { + var dp = Array(nums.length).fill(0); + var stack = []; + for (var i = nums.length - 1; i >= 0; i--) { + while (stack.length && nums[i] > nums[stack[stack.length - 1]]) { + dp[i] = Math.max(dp[i] + 1, dp[stack.pop()]); + } + stack.push(i); + } + return Math.max(...dp); +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/2301-2400/2305. Fair Distribution of Cookies.md b/2301-2400/2305. Fair Distribution of Cookies.md new file mode 100644 index 0000000..ea4382e --- /dev/null +++ b/2301-2400/2305. Fair Distribution of Cookies.md @@ -0,0 +1,90 @@ +# 2305. Fair Distribution of Cookies + +- Difficulty: Medium. +- Related Topics: Array, Dynamic Programming, Backtracking, Bit Manipulation, Bitmask. +- Similar Questions: Split Array Largest Sum, Split Array with Equal Sum, Partition to K Equal Sum Subsets, Minimum XOR Sum of Two Arrays, The Number of Good Subsets, Minimum Number of Work Sessions to Finish the Tasks, Partition Array Into Two Arrays to Minimize Sum Difference, Maximum Rows Covered by Columns, Distribute Money to Maximum Children. + +## Problem + +You are given an integer array `cookies`, where `cookies[i]` denotes the number of cookies in the `ith` bag. You are also given an integer `k` that denotes the number of children to distribute **all** the bags of cookies to. All the cookies in the same bag must go to the same child and cannot be split up. + +The **unfairness** of a distribution is defined as the **maximum** **total** cookies obtained by a single child in the distribution. + +Return **the **minimum** unfairness of all distributions**. + +  +Example 1: + +``` +Input: cookies = [8,15,10,20,8], k = 2 +Output: 31 +Explanation: One optimal distribution is [8,15,8] and [10,20] +- The 1st child receives [8,15,8] which has a total of 8 + 15 + 8 = 31 cookies. +- The 2nd child receives [10,20] which has a total of 10 + 20 = 30 cookies. +The unfairness of the distribution is max(31,30) = 31. +It can be shown that there is no distribution with an unfairness less than 31. +``` + +Example 2: + +``` +Input: cookies = [6,1,3,2,2,4,1,2], k = 3 +Output: 7 +Explanation: One optimal distribution is [6,1], [3,2,2], and [4,1,2] +- The 1st child receives [6,1] which has a total of 6 + 1 = 7 cookies. +- The 2nd child receives [3,2,2] which has a total of 3 + 2 + 2 = 7 cookies. +- The 3rd child receives [4,1,2] which has a total of 4 + 1 + 2 = 7 cookies. +The unfairness of the distribution is max(7,7,7) = 7. +It can be shown that there is no distribution with an unfairness less than 7. +``` + +  +**Constraints:** + + + +- `2 <= cookies.length <= 8` + +- `1 <= cookies[i] <= 105` + +- `2 <= k <= cookies.length` + + + +## Solution + +```javascript +/** + * @param {number[]} cookies + * @param {number} k + * @return {number} + */ +var distributeCookies = function(cookies, k) { + var arr = Array(k).fill(0); + return helper(cookies, k, 0, 0, arr); +}; + +var helper = function(cookies, k, i, n, map) { + var min = Number.MAX_SAFE_INTEGER; + if (i === cookies.length && n === k) return Math.max(...map); + if (cookies.length - i < k - n) return min; + for (var j = 0; j < k; j++) { + map[j] += cookies[i]; + min = Math.min( + min, + helper(cookies, k, i + 1, map[j] === cookies[i] ? n + 1 : n, map), + ); + map[j] -= cookies[i]; + } + return min; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n ^ k). +* Space complexity : O(k). diff --git a/2301-2400/2320. Count Number of Ways to Place Houses.md b/2301-2400/2320. Count Number of Ways to Place Houses.md new file mode 100644 index 0000000..925bae6 --- /dev/null +++ b/2301-2400/2320. Count Number of Ways to Place Houses.md @@ -0,0 +1,77 @@ +# 2320. Count Number of Ways to Place Houses + +- Difficulty: Medium. +- Related Topics: Dynamic Programming. +- Similar Questions: Climbing Stairs, House Robber. + +## Problem + +There is a street with `n * 2` **plots**, where there are `n` plots on each side of the street. The plots on each side are numbered from `1` to `n`. On each plot, a house can be placed. + +Return **the number of ways houses can be placed such that no two houses are adjacent to each other on the same side of the street**. Since the answer may be very large, return it **modulo** `109 + 7`. + +Note that if a house is placed on the `ith` plot on one side of the street, a house can also be placed on the `ith` plot on the other side of the street. + +  +Example 1: + +``` +Input: n = 1 +Output: 4 +Explanation: +Possible arrangements: +1. All plots are empty. +2. A house is placed on one side of the street. +3. A house is placed on the other side of the street. +4. Two houses are placed, one on each side of the street. +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2022/05/12/arrangements.png) + +``` +Input: n = 2 +Output: 9 +Explanation: The 9 possible arrangements are shown in the diagram above. +``` + +  +**Constraints:** + + + +- `1 <= n <= 104` + + + +## Solution + +```javascript +/** + * @param {number} n + * @return {number} + */ +var countHousePlacements = function(n) { + var lastHasHouse = 0; + var lastNoHouse = 1; + var mod = Math.pow(10, 9) + 7; + var tmp = 0; + for (var i = 0; i < n; i++) { + tmp = (lastHasHouse + lastNoHouse) % mod; + lastHasHouse = lastNoHouse; + lastNoHouse = tmp; + } + tmp = (lastHasHouse + lastNoHouse) % mod; + return Number((BigInt(tmp) * BigInt(tmp)) % BigInt(mod)); +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). 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/2369. Check if There is a Valid Partition For The Array.md b/2301-2400/2369. Check if There is a Valid Partition For The Array.md new file mode 100644 index 0000000..3fcc90e --- /dev/null +++ b/2301-2400/2369. Check if There is a Valid Partition For The Array.md @@ -0,0 +1,79 @@ +# 2369. Check if There is a Valid Partition For The Array + +- Difficulty: Medium. +- Related Topics: Array, Dynamic Programming. +- Similar Questions: . + +## Problem + +You are given a **0-indexed** integer array `nums`. You have to partition the array into one or more **contiguous** subarrays. + +We call a partition of the array **valid** if each of the obtained subarrays satisfies **one** of the following conditions: + + + +- The subarray consists of **exactly** `2` equal elements. For example, the subarray `[2,2]` is good. + +- The subarray consists of **exactly** `3` equal elements. For example, the subarray `[4,4,4]` is good. + +- The subarray consists of **exactly** `3` consecutive increasing elements, that is, the difference between adjacent elements is `1`. For example, the subarray `[3,4,5]` is good, but the subarray `[1,3,5]` is not. + + +Return `true`** if the array has **at least** one valid partition**. Otherwise, return `false`. + +  +Example 1: + +``` +Input: nums = [4,4,4,5,6] +Output: true +Explanation: The array can be partitioned into the subarrays [4,4] and [4,5,6]. +This partition is valid, so we return true. +``` + +Example 2: + +``` +Input: nums = [1,1,1,2] +Output: false +Explanation: There is no valid partition for this array. +``` + +  +**Constraints:** + + + +- `2 <= nums.length <= 105` + +- `1 <= nums[i] <= 106` + + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @return {boolean} + */ +var validPartition = function(nums) { + var dp = Array(nums.length + 1); + dp[nums.length] = true; + for (var i = nums.length - 1; i >= 0; i--) { + dp[i] = (nums[i] === nums[i + 1] && dp[i + 2]) + || (nums[i] === nums[i + 1] && nums[i + 1] === nums[i + 2] && dp[i + 3]) + || (nums[i] + 1 === nums[i + 1] && nums[i + 1] + 1 === nums[i + 2] && dp[i + 3]); + } + return dp[0]; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(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/2384. Largest Palindromic Number.md b/2301-2400/2384. Largest Palindromic Number.md new file mode 100644 index 0000000..4259174 --- /dev/null +++ b/2301-2400/2384. Largest Palindromic Number.md @@ -0,0 +1,92 @@ +# 2384. Largest Palindromic Number + +- Difficulty: Medium. +- Related Topics: Hash Table, String, Greedy. +- Similar Questions: Longest Palindrome. + +## Problem + +You are given a string `num` consisting of digits only. + +Return **the **largest palindromic** integer (in the form of a string) that can be formed using digits taken from **`num`. It should not contain **leading zeroes**. + +**Notes:** + + + +- You do **not** need to use all the digits of `num`, but you must use **at least** one digit. + +- The digits can be reordered. + + +  +Example 1: + +``` +Input: num = "444947137" +Output: "7449447" +Explanation: +Use the digits "4449477" from "444947137" to form the palindromic integer "7449447". +It can be shown that "7449447" is the largest palindromic integer that can be formed. +``` + +Example 2: + +``` +Input: num = "00009" +Output: "9" +Explanation: +It can be shown that "9" is the largest palindromic integer that can be formed. +Note that the integer returned should not contain leading zeroes. +``` + +  +**Constraints:** + + + +- `1 <= num.length <= 105` + +- `num` consists of digits. + + + +## Solution + +```javascript +/** + * @param {string} num + * @return {string} + */ +var largestPalindromic = function(num) { + var map = Array(10).fill(0); + for (var i = 0; i < num.length; i++) { + map[+num[i]]++; + } + var res = ''; + for (var j = map.length - 1; j >= 0; j--) { + if (map[j] <= 1 || (j === 0 && res.length === 0)) continue; + res = res.slice(0, res.length / 2) + + String(j).repeat(map[j] % 2 ? (map[j] - 1) : map[j]) + + res.slice(res.length / 2); + map[j] = map[j] % 2 ? 1 : 0; + } + for (var k = map.length - 1; k >= 0; k--) { + if (map[k] === 0) continue; + res = res.slice(0, res.length / 2) + + String(k) + + res.slice(res.length / 2); + break; + } + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). 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/2391. Minimum Amount of Time to Collect Garbage.md b/2301-2400/2391. Minimum Amount of Time to Collect Garbage.md new file mode 100644 index 0000000..3ac713a --- /dev/null +++ b/2301-2400/2391. Minimum Amount of Time to Collect Garbage.md @@ -0,0 +1,129 @@ +# 2391. Minimum Amount of Time to Collect Garbage + +- Difficulty: Medium. +- Related Topics: Array, String, Prefix Sum. +- Similar Questions: . + +## Problem + +You are given a **0-indexed** array of strings `garbage` where `garbage[i]` represents the assortment of garbage at the `ith` house. `garbage[i]` consists only of the characters `'M'`, `'P'` and `'G'` representing one unit of metal, paper and glass garbage respectively. Picking up **one** unit of any type of garbage takes `1` minute. + +You are also given a **0-indexed** integer array `travel` where `travel[i]` is the number of minutes needed to go from house `i` to house `i + 1`. + +There are three garbage trucks in the city, each responsible for picking up one type of garbage. Each garbage truck starts at house `0` and must visit each house **in order**; however, they do **not** need to visit every house. + +Only **one** garbage truck may be used at any given moment. While one truck is driving or picking up garbage, the other two trucks **cannot** do anything. + +Return** the **minimum** number of minutes needed to pick up all the garbage.** + +  +Example 1: + +``` +Input: garbage = ["G","P","GP","GG"], travel = [2,4,3] +Output: 21 +Explanation: +The paper garbage truck: +1. Travels from house 0 to house 1 +2. Collects the paper garbage at house 1 +3. Travels from house 1 to house 2 +4. Collects the paper garbage at house 2 +Altogether, it takes 8 minutes to pick up all the paper garbage. +The glass garbage truck: +1. Collects the glass garbage at house 0 +2. Travels from house 0 to house 1 +3. Travels from house 1 to house 2 +4. Collects the glass garbage at house 2 +5. Travels from house 2 to house 3 +6. Collects the glass garbage at house 3 +Altogether, it takes 13 minutes to pick up all the glass garbage. +Since there is no metal garbage, we do not need to consider the metal garbage truck. +Therefore, it takes a total of 8 + 13 = 21 minutes to collect all the garbage. +``` + +Example 2: + +``` +Input: garbage = ["MMM","PGM","GP"], travel = [3,10] +Output: 37 +Explanation: +The metal garbage truck takes 7 minutes to pick up all the metal garbage. +The paper garbage truck takes 15 minutes to pick up all the paper garbage. +The glass garbage truck takes 15 minutes to pick up all the glass garbage. +It takes a total of 7 + 15 + 15 = 37 minutes to collect all the garbage. +``` + +  +**Constraints:** + + + +- `2 <= garbage.length <= 105` + +- `garbage[i]` consists of only the letters `'M'`, `'P'`, and `'G'`. + +- `1 <= garbage[i].length <= 10` + +- `travel.length == garbage.length - 1` + +- `1 <= travel[i] <= 100` + + + +## Solution + +```javascript +/** + * @param {string[]} garbage + * @param {number[]} travel + * @return {number} + */ +var garbageCollection = function(garbage, travel) { + var res = 0; + var m = 0; + var p = 0; + var g = 0; + for (var i = 0; i < garbage.length; i++) { + const num = count(garbage[i]); + m += (travel[i - 1] || 0); + p += (travel[i - 1] || 0); + g += (travel[i - 1] || 0); + if (num.m) { + res += m + num.m; + m = 0; + } + if (num.p) { + res += p + num.p; + p = 0; + } + if (num.g) { + res += g + num.g; + g = 0; + } + } + return res; +}; + +var count = function(str) { + var res = { m: 0, p: 0, g: 0 }; + for (var i = 0; i < str.length; i++) { + if (str[i] === 'M') { + res.m++; + } else if (str[i] === 'P') { + res.p++; + } else { + res.g++; + } + } + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * m). +* Space complexity : O(1). 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/2301-2400/2400. Number of Ways to Reach a Position After Exactly k Steps.md b/2301-2400/2400. Number of Ways to Reach a Position After Exactly k Steps.md new file mode 100644 index 0000000..a80b43a --- /dev/null +++ b/2301-2400/2400. Number of Ways to Reach a Position After Exactly k Steps.md @@ -0,0 +1,78 @@ +# 2400. Number of Ways to Reach a Position After Exactly k Steps + +- Difficulty: Medium. +- Related Topics: Math, Dynamic Programming, Combinatorics. +- Similar Questions: Unique Paths, Climbing Stairs, Reach a Number, Reaching Points, Number of Ways to Stay in the Same Place After Some Steps. + +## Problem + +You are given two **positive** integers `startPos` and `endPos`. Initially, you are standing at position `startPos` on an **infinite** number line. With one step, you can move either one position to the left, or one position to the right. + +Given a positive integer `k`, return **the number of **different** ways to reach the position **`endPos`** starting from **`startPos`**, such that you perform **exactly** **`k`** steps**. Since the answer may be very large, return it **modulo** `109 + 7`. + +Two ways are considered different if the order of the steps made is not exactly the same. + +**Note** that the number line includes negative integers. + +  +Example 1: + +``` +Input: startPos = 1, endPos = 2, k = 3 +Output: 3 +Explanation: We can reach position 2 from 1 in exactly 3 steps in three ways: +- 1 -> 2 -> 3 -> 2. +- 1 -> 2 -> 1 -> 2. +- 1 -> 0 -> 1 -> 2. +It can be proven that no other way is possible, so we return 3. +``` + +Example 2: + +``` +Input: startPos = 2, endPos = 5, k = 10 +Output: 0 +Explanation: It is impossible to reach position 5 from position 2 in exactly 10 steps. +``` + +  +**Constraints:** + + + +- `1 <= startPos, endPos, k <= 1000` + + + +## Solution + +```javascript +/** + * @param {number} startPos + * @param {number} endPos + * @param {number} k + * @return {number} + */ +var numberOfWays = function(startPos, endPos, k, dp = {}) { + if (startPos === endPos && k === 0) return 1; + if (k === 0) return 0; + if (Math.abs(startPos - endPos) > k) return 0; + if (!dp[startPos]) dp[startPos] = {}; + if (dp[startPos][k] === undefined) { + dp[startPos][k] = ( + numberOfWays(startPos + 1, endPos, k - 1, dp) + + numberOfWays(startPos - 1, endPos, k - 1, dp) + ) % (Math.pow(10, 9) + 7); + } + return dp[startPos][k]; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(k ^ 2). +* Space complexity : O(k ^ 2). diff --git a/2401-2500/2409. Count Days Spent Together.md b/2401-2500/2409. Count Days Spent Together.md new file mode 100644 index 0000000..0287d30 --- /dev/null +++ b/2401-2500/2409. Count Days Spent Together.md @@ -0,0 +1,96 @@ +# 2409. Count Days Spent Together + +- Difficulty: Easy. +- Related Topics: Math, String. +- Similar Questions: Number of Days Between Two Dates, Minimum Number of Operations to Convert Time. + +## Problem + +Alice and Bob are traveling to Rome for separate business meetings. + +You are given 4 strings ```arriveAlice```, ```leaveAlice```, ```arriveBob```, and ```leaveBob```. Alice will be in the city from the dates ```arriveAlice``` to ```leaveAlice``` (**inclusive**), while Bob will be in the city from the dates ```arriveBob``` to ```leaveBob``` (**inclusive**). Each will be a 5-character string in the format ```"MM-DD"```, corresponding to the month and day of the date. + +Return** the total number of days that Alice and Bob are in Rome together.** + +You can assume that all dates occur in the **same** calendar year, which is **not** a leap year. Note that the number of days per month can be represented as: ```[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]```. + +  +Example 1: + +``` +Input: arriveAlice = "08-15", leaveAlice = "08-18", arriveBob = "08-16", leaveBob = "08-19" +Output: 3 +Explanation: Alice will be in Rome from August 15 to August 18. Bob will be in Rome from August 16 to August 19. They are both in Rome together on August 16th, 17th, and 18th, so the answer is 3. +``` + +Example 2: + +``` +Input: arriveAlice = "10-01", leaveAlice = "10-31", arriveBob = "11-01", leaveBob = "12-31" +Output: 0 +Explanation: There is no day when Alice and Bob are in Rome together, so we return 0. +``` + +  +**Constraints:** + + + +- All dates are provided in the format ```"MM-DD"```. + +- Alice and Bob's arrival dates are **earlier than or equal to** their leaving dates. + +- The given dates are valid dates of a **non-leap** year. + + + +## Solution + +```javascript +/** + * @param {string} arriveAlice + * @param {string} leaveAlice + * @param {string} arriveBob + * @param {string} leaveBob + * @return {number} + */ +var countDaysTogether = function(arriveAlice, leaveAlice, arriveBob, leaveBob) { + var daysOfMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + var aliceDate = [ + arriveAlice.split('-').map(item => Number(item)), + leaveAlice.split('-').map(item => Number(item)), + ]; + var bobDate = [ + arriveBob.split('-').map(item => Number(item)), + leaveBob.split('-').map(item => Number(item)), + ]; + var togetherDate = [ + (aliceDate[0][0] * 100 + aliceDate[0][1]) > (bobDate[0][0] * 100 + bobDate[0][1]) + ? aliceDate[0] + : bobDate[0], + (aliceDate[1][0] * 100 + aliceDate[1][1]) < (bobDate[1][0] * 100 + bobDate[1][1]) + ? aliceDate[1] + : bobDate[1], + ]; + if (togetherDate[0][0] === togetherDate[1][0]) { + return Math.max(togetherDate[1][1] - togetherDate[0][1] + 1, 0); + } + if (togetherDate[0][0] > togetherDate[1][0]) { + return 0; + } + return (daysOfMonth[togetherDate[0][0] - 1] - togetherDate[0][1] + 1) + + Array(togetherDate[1][0] - togetherDate[0][0] - 1).fill(0) + .map((_, i) => daysOfMonth[i + togetherDate[0][0]]) + .reduce((sum, i) => sum + i, 0) + + togetherDate[1][1]; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(1). +* Space complexity : O(1). diff --git a/2401-2500/2413. Smallest Even Multiple.md b/2401-2500/2413. Smallest Even Multiple.md new file mode 100644 index 0000000..9daa7f4 --- /dev/null +++ b/2401-2500/2413. Smallest Even Multiple.md @@ -0,0 +1,55 @@ +# 2413. Smallest Even Multiple + +- Difficulty: Easy. +- Related Topics: Math, Number Theory. +- Similar Questions: Greatest Common Divisor of Strings, Three Divisors, Find Greatest Common Divisor of Array, Convert the Temperature, Minimum Cuts to Divide a Circle. + +## Problem + +Given a **positive** integer ```n```, return **the smallest positive integer that is a multiple of **both** **```2```** and **```n```. +  +Example 1: + +``` +Input: n = 5 +Output: 10 +Explanation: The smallest multiple of both 5 and 2 is 10. +``` + +Example 2: + +``` +Input: n = 6 +Output: 6 +Explanation: The smallest multiple of both 6 and 2 is 6. Note that a number is a multiple of itself. +``` + +  +**Constraints:** + + + +- ```1 <= n <= 150``` + + + +## Solution + +```javascript +/** + * @param {number} n + * @return {number} + */ +var smallestEvenMultiple = function(n) { + return n % 2 === 0 ? n : n * 2; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/2401-2500/2433. Find The Original Array of Prefix Xor.md b/2401-2500/2433. Find The Original Array of Prefix Xor.md new file mode 100644 index 0000000..2d95aac --- /dev/null +++ b/2401-2500/2433. Find The Original Array of Prefix Xor.md @@ -0,0 +1,76 @@ +# 2433. Find The Original Array of Prefix Xor + +- Difficulty: Medium. +- Related Topics: Array, Bit Manipulation. +- Similar Questions: Single Number III, Count Triplets That Can Form Two Arrays of Equal XOR, Decode XORed Array. + +## Problem + +You are given an **integer** array `pref` of size `n`. Find and return **the array **`arr`** of size **`n`** that satisfies**: + + + +- `pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i]`. + + +Note that `^` denotes the **bitwise-xor** operation. + +It can be proven that the answer is **unique**. + +  +Example 1: + +``` +Input: pref = [5,2,0,3,1] +Output: [5,7,2,3,2] +Explanation: From the array [5,7,2,3,2] we have the following: +- pref[0] = 5. +- pref[1] = 5 ^ 7 = 2. +- pref[2] = 5 ^ 7 ^ 2 = 0. +- pref[3] = 5 ^ 7 ^ 2 ^ 3 = 3. +- pref[4] = 5 ^ 7 ^ 2 ^ 3 ^ 2 = 1. +``` + +Example 2: + +``` +Input: pref = [13] +Output: [13] +Explanation: We have pref[0] = arr[0] = 13. +``` + +  +**Constraints:** + + + +- `1 <= pref.length <= 105` + +- `0 <= pref[i] <= 106` + + + +## Solution + +```javascript +/** + * @param {number[]} pref + * @return {number[]} + */ +var findArray = function(pref) { + return pref.map((num, i) => { + return i === 0 + ? num + : (num ^ pref[i - 1]); + }); +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). 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/2454. Next Greater Element IV.md b/2401-2500/2454. Next Greater Element IV.md new file mode 100644 index 0000000..406a172 --- /dev/null +++ b/2401-2500/2454. Next Greater Element IV.md @@ -0,0 +1,99 @@ +# 2454. Next Greater Element IV + +- Difficulty: Hard. +- Related Topics: Array, Binary Search, Stack, Sorting, Heap (Priority Queue), Monotonic Stack. +- Similar Questions: Next Greater Element I, Replace Elements with Greatest Element on Right Side, Apply Operations to Maximize Score. + +## Problem + +You are given a **0-indexed** array of non-negative integers `nums`. For each integer in `nums`, you must find its respective **second greater** integer. + +The **second greater** integer of `nums[i]` is `nums[j]` such that: + + + +- `j > i` + +- `nums[j] > nums[i]` + +- There exists **exactly one** index `k` such that `nums[k] > nums[i]` and `i < k < j`. + + +If there is no such `nums[j]`, the second greater integer is considered to be `-1`. + + + +- For example, in the array `[1, 2, 4, 3]`, the second greater integer of `1` is `4`, `2` is `3`, and that of `3` and `4` is `-1`. + + +Return** an integer array **`answer`**, where **`answer[i]`** is the second greater integer of **`nums[i]`**.** + +  +Example 1: + +``` +Input: nums = [2,4,0,9,6] +Output: [9,6,6,-1,-1] +Explanation: +0th index: 4 is the first integer greater than 2, and 9 is the second integer greater than 2, to the right of 2. +1st index: 9 is the first, and 6 is the second integer greater than 4, to the right of 4. +2nd index: 9 is the first, and 6 is the second integer greater than 0, to the right of 0. +3rd index: There is no integer greater than 9 to its right, so the second greater integer is considered to be -1. +4th index: There is no integer greater than 6 to its right, so the second greater integer is considered to be -1. +Thus, we return [9,6,6,-1,-1]. +``` + +Example 2: + +``` +Input: nums = [3,3] +Output: [-1,-1] +Explanation: +We return [-1,-1] since neither integer has any integer greater than it. +``` + +  +**Constraints:** + + + +- `1 <= nums.length <= 105` + +- `0 <= nums[i] <= 109` + + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @return {number[]} + */ +var secondGreaterElement = function(nums) { + var res = Array(nums.length).fill(-1); + var stack1 = []; // first greater integer + var stack2 = []; // second greater integer + for (var i = 0; i < nums.length; i++) { + while (stack2.length && nums[i] > nums[stack2[stack2.length - 1]]) { + res[stack2.pop()] = nums[i]; + } + var tempArr = []; + while (stack1.length && nums[i] > nums[stack1[stack1.length - 1]]) { + tempArr.unshift(stack1.pop()); + } + stack2.push(...tempArr); + stack1.push(i); + } + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). 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/2466. Count Ways To Build Good Strings.md b/2401-2500/2466. Count Ways To Build Good Strings.md new file mode 100644 index 0000000..548acef --- /dev/null +++ b/2401-2500/2466. Count Ways To Build Good Strings.md @@ -0,0 +1,94 @@ +# 2466. Count Ways To Build Good Strings + +- Difficulty: Medium. +- Related Topics: Dynamic Programming. +- Similar Questions: Climbing Stairs. + +## Problem + +Given the integers `zero`, `one`, `low`, and `high`, we can construct a string by starting with an empty string, and then at each step perform either of the following: + + + +- Append the character `'0'` `zero` times. + +- Append the character `'1'` `one` times. + + +This can be performed any number of times. + +A **good** string is a string constructed by the above process having a **length** between `low` and `high` (**inclusive**). + +Return **the number of **different** good strings that can be constructed satisfying these properties.** Since the answer can be large, return it **modulo** `109 + 7`. + +  +Example 1: + +``` +Input: low = 3, high = 3, zero = 1, one = 1 +Output: 8 +Explanation: +One possible valid good string is "011". +It can be constructed as follows: "" -> "0" -> "01" -> "011". +All binary strings from "000" to "111" are good strings in this example. +``` + +Example 2: + +``` +Input: low = 2, high = 3, zero = 1, one = 2 +Output: 5 +Explanation: The good strings are "00", "11", "000", "110", and "011". +``` + +  +**Constraints:** + + + +- `1 <= low <= high <= 105` + +- `1 <= zero, one <= low` + + + +## Solution + +```javascript +/** + * @param {number} low + * @param {number} high + * @param {number} zero + * @param {number} one + * @return {number} + */ +var countGoodStrings = function(low, high, zero, one) { + var mod = Math.pow(10, 9) + 7; + var dp = new Array(high + 1).fill(0); + dp[0] = 1; + for (var i = Math.min(zero, one); i <= high; i++) { + if (i >= zero) { + dp[i] = (dp[i] + dp[i - zero]) % mod; + } + if (i >= one) { + dp[i] = (dp[i] + dp[i - one]) % mod; + } + } + var res = 0; + for (var i = low; i <= high; i++) { + res = (res + dp[i]) % mod; + } + return res; +}; +``` + +**Explain:** + +`dp[i]` means, for string length `i`, has `dp[i]` kinds of different good strings. + +`dp[i] = dp[i - zero] + dp[i - one]` + +**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/2501-2600/2551. Put Marbles in Bags.md b/2501-2600/2551. Put Marbles in Bags.md new file mode 100644 index 0000000..2bfb0b3 --- /dev/null +++ b/2501-2600/2551. Put Marbles in Bags.md @@ -0,0 +1,85 @@ +# 2551. Put Marbles in Bags + +- Difficulty: Hard. +- Related Topics: Array, Greedy, Sorting, Heap (Priority Queue). +- Similar Questions: . + +## Problem + +You have `k` bags. You are given a **0-indexed** integer array `weights` where `weights[i]` is the weight of the `ith` marble. You are also given the integer `k.` + +Divide the marbles into the `k` bags according to the following rules: + + + +- No bag is empty. + +- If the `ith` marble and `jth` marble are in a bag, then all marbles with an index between the `ith` and `jth` indices should also be in that same bag. + +- If a bag consists of all the marbles with an index from `i` to `j` inclusively, then the cost of the bag is `weights[i] + weights[j]`. + + +The **score** after distributing the marbles is the sum of the costs of all the `k` bags. + +Return **the **difference** between the **maximum** and **minimum** scores among marble distributions**. + +  +Example 1: + +``` +Input: weights = [1,3,5,1], k = 2 +Output: 4 +Explanation: +The distribution [1],[3,5,1] results in the minimal score of (1+1) + (3+1) = 6. +The distribution [1,3],[5,1], results in the maximal score of (1+3) + (5+1) = 10. +Thus, we return their difference 10 - 6 = 4. +``` + +Example 2: + +``` +Input: weights = [1, 3], k = 2 +Output: 0 +Explanation: The only distribution possible is [1],[3]. +Since both the maximal and minimal score are the same, we return 0. +``` + +  +**Constraints:** + + + +- `1 <= k <= weights.length <= 105` + +- `1 <= weights[i] <= 109` + + + +## Solution + +```javascript +/** + * @param {number[]} weights + * @param {number} k + * @return {number} + */ +var putMarbles = function(weights, k) { + var arr = []; + for (var i = 0; i < weights.length - 1; i++) { + arr.push(weights[i] + weights[i + 1]); + } + arr.sort((a, b) => a - b); + var min = arr.slice(0, k - 1).reduce((sum, num) => sum + num, 0); + var max = arr.slice(arr.length - k + 1).reduce((sum, num) => sum + num, 0); + return max - min; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(nlog(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/2616. Minimize the Maximum Difference of Pairs.md b/2601-2700/2616. Minimize the Maximum Difference of Pairs.md new file mode 100644 index 0000000..5e9fbfe --- /dev/null +++ b/2601-2700/2616. Minimize the Maximum Difference of Pairs.md @@ -0,0 +1,88 @@ +# 2616. Minimize the Maximum Difference of Pairs + +- Difficulty: Medium. +- Related Topics: Array, Binary Search, Greedy. +- Similar Questions: Minimum Absolute Difference, Minimum Difference Between Largest and Smallest Value in Three Moves. + +## Problem + +You are given a **0-indexed** integer array `nums` and an integer `p`. Find `p` pairs of indices of `nums` such that the **maximum** difference amongst all the pairs is **minimized**. Also, ensure no index appears more than once amongst the `p` pairs. + +Note that for a pair of elements at the index `i` and `j`, the difference of this pair is `|nums[i] - nums[j]|`, where `|x|` represents the **absolute** **value** of `x`. + +Return **the **minimum** **maximum** difference among all **`p` **pairs.** We define the maximum of an empty set to be zero. + +  +Example 1: + +``` +Input: nums = [10,1,2,7,1,3], p = 2 +Output: 1 +Explanation: The first pair is formed from the indices 1 and 4, and the second pair is formed from the indices 2 and 5. +The maximum difference is max(|nums[1] - nums[4]|, |nums[2] - nums[5]|) = max(0, 1) = 1. Therefore, we return 1. +``` + +Example 2: + +``` +Input: nums = [4,2,1,2], p = 1 +Output: 0 +Explanation: Let the indices 1 and 3 form a pair. The difference of that pair is |2 - 2| = 0, which is the minimum we can attain. +``` + +  +**Constraints:** + + + +- `1 <= nums.length <= 105` + +- `0 <= nums[i] <= 109` + +- `0 <= p <= (nums.length)/2` + + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @param {number} p + * @return {number} + */ +var minimizeMax = function(nums, p) { + nums.sort((a, b) => a - b); + var left = 0; + var right = nums[nums.length - 1] - nums[0]; + while (left < right) { + var mid = left + Math.floor((right - left) / 2); + if (count(nums, mid) >= p) { + right = mid; + } else { + left = mid + 1; + } + } + return left; +}; + +var count = function(nums, n) { + var num = 0; + for (var i = 0; i < nums.length - 1; i++) { + if (nums[i + 1] - nums[i] <= n) { + i++; + num++; + } + } + return num; +} +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * log(max - min)). +* Space complexity : O(1). diff --git a/2601-2700/2642. Design Graph With Shortest Path Calculator.md b/2601-2700/2642. Design Graph With Shortest Path Calculator.md new file mode 100644 index 0000000..6e89bdc --- /dev/null +++ b/2601-2700/2642. Design Graph With Shortest Path Calculator.md @@ -0,0 +1,124 @@ +# 2642. Design Graph With Shortest Path Calculator + +- Difficulty: Hard. +- Related Topics: Graph, Design, Heap (Priority Queue), Shortest Path. +- Similar Questions: Number of Restricted Paths From First to Last Node, Closest Node to Path in Tree. + +## Problem + +There is a **directed weighted** graph that consists of `n` nodes numbered from `0` to `n - 1`. The edges of the graph are initially represented by the given array `edges` where `edges[i] = [fromi, toi, edgeCosti]` meaning that there is an edge from `fromi` to `toi` with the cost `edgeCosti`. + +Implement the `Graph` class: + + + +- `Graph(int n, int[][] edges)` initializes the object with `n` nodes and the given edges. + +- `addEdge(int[] edge)` adds an edge to the list of edges where `edge = [from, to, edgeCost]`. It is guaranteed that there is no edge between the two nodes before adding this one. + +- `int shortestPath(int node1, int node2)` returns the **minimum** cost of a path from `node1` to `node2`. If no path exists, return `-1`. The cost of a path is the sum of the costs of the edges in the path. + + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2023/01/11/graph3drawio-2.png) + +``` +Input +["Graph", "shortestPath", "shortestPath", "addEdge", "shortestPath"] +[[4, [[0, 2, 5], [0, 1, 2], [1, 2, 1], [3, 0, 3]]], [3, 2], [0, 3], [[1, 3, 4]], [0, 3]] +Output +[null, 6, -1, null, 6] + +Explanation +Graph g = new Graph(4, [[0, 2, 5], [0, 1, 2], [1, 2, 1], [3, 0, 3]]); +g.shortestPath(3, 2); // return 6. The shortest path from 3 to 2 in the first diagram above is 3 -> 0 -> 1 -> 2 with a total cost of 3 + 2 + 1 = 6. +g.shortestPath(0, 3); // return -1. There is no path from 0 to 3. +g.addEdge([1, 3, 4]); // We add an edge from node 1 to node 3, and we get the second diagram above. +g.shortestPath(0, 3); // return 6. The shortest path from 0 to 3 now is 0 -> 1 -> 3 with a total cost of 2 + 4 = 6. +``` + +  +**Constraints:** + + + +- `1 <= n <= 100` + +- `0 <= edges.length <= n * (n - 1)` + +- `edges[i].length == edge.length == 3` + +- `0 <= fromi, toi, from, to, node1, node2 <= n - 1` + +- `1 <= edgeCosti, edgeCost <= 106` + +- There are no repeated edges and no self-loops in the graph at any point. + +- At most `100` calls will be made for `addEdge`. + +- At most `100` calls will be made for `shortestPath`. + + + +## Solution + +```javascript +/** + * @param {number} n + * @param {number[][]} edges + */ +var Graph = function(n, edges) { + var map = Array(n).fill(0).map(() => []); + for (var i = 0; i < edges.length; i++) { + map[edges[i][0]].push([edges[i][1], edges[i][2]]); + } + this.map = map; +}; + +/** + * @param {number[]} edge + * @return {void} + */ +Graph.prototype.addEdge = function(edge) { + this.map[edge[0]].push([edge[1], edge[2]]); +}; + +/** + * @param {number} node1 + * @param {number} node2 + * @return {number} + */ +Graph.prototype.shortestPath = function(node1, node2) { + var visited = {}; + var queue = new MinPriorityQueue(); + queue.enqueue(node1, 0); + while (queue.size()) { + var { element, priority } = queue.dequeue(); + if (element === node2) return priority; + if (visited[element]) continue; + visited[element] = true; + this.map[element].forEach(item => { + queue.enqueue(item[0], item[1] + priority); + }); + } + return -1; +}; + +/** + * Your Graph object will be instantiated and called as such: + * var obj = new Graph(n, edges) + * obj.addEdge(edge) + * var param_2 = obj.shortestPath(node1,node2) + */ +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * log(m)). +* 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/2707. Extra Characters in a String.md b/2701-2800/2707. Extra Characters in a String.md new file mode 100644 index 0000000..ae89fec --- /dev/null +++ b/2701-2800/2707. Extra Characters in a String.md @@ -0,0 +1,83 @@ +# 2707. Extra Characters in a String + +- Difficulty: Medium. +- Related Topics: Array, Hash Table, String, Dynamic Programming, Trie. +- Similar Questions: Word Break. + +## Problem + +You are given a **0-indexed** string `s` and a dictionary of words `dictionary`. You have to break `s` into one or more **non-overlapping** substrings such that each substring is present in `dictionary`. There may be some **extra characters** in `s` which are not present in any of the substrings. + +Return **the **minimum** number of extra characters left over if you break up **`s`** optimally.** + +  +Example 1: + +``` +Input: s = "leetscode", dictionary = ["leet","code","leetcode"] +Output: 1 +Explanation: We can break s in two substrings: "leet" from index 0 to 3 and "code" from index 5 to 8. There is only 1 unused character (at index 4), so we return 1. + +``` + +Example 2: + +``` +Input: s = "sayhelloworld", dictionary = ["hello","world"] +Output: 3 +Explanation: We can break s in two substrings: "hello" from index 3 to 7 and "world" from index 8 to 12. The characters at indices 0, 1, 2 are not used in any substring and thus are considered as extra characters. Hence, we return 3. +``` + +  +**Constraints:** + + + +- `1 <= s.length <= 50` + +- `1 <= dictionary.length <= 50` + +- `1 <= dictionary[i].length <= 50` + +- `dictionary[i]` and `s` consists of only lowercase English letters + +- `dictionary` contains distinct words + + + +## Solution + +```javascript +/** + * @param {string} s + * @param {string[]} dictionary + * @return {number} + */ +var minExtraChar = function(s, dictionary) { + var map = dictionary.reduce((res, item) => { + res[item] = 1; + return res; + }, {}); + var dp = Array(s.length); + for (var i = s.length - 1; i >= 0; i--) { + dp[i] = (dp[i + 1] || 0) + 1; + var str = ''; + for (var j = i; j < s.length; j++) { + str += s[j]; + if (map[str]) { + dp[i] = Math.min(dp[i], dp[j + 1] || 0); + } + } + } + return dp[0]; +}; +``` + +**Explain:** + +Bottom-up dynamic programming. + +**Complexity:** + +* Time complexity : O(n ^ 2). +* Space complexity : O(n). diff --git a/2701-2800/2730. Find the Longest Semi-Repetitive Substring.md b/2701-2800/2730. Find the Longest Semi-Repetitive Substring.md new file mode 100644 index 0000000..3d546d0 --- /dev/null +++ b/2701-2800/2730. Find the Longest Semi-Repetitive Substring.md @@ -0,0 +1,84 @@ +# 2730. Find the Longest Semi-Repetitive Substring + +- Difficulty: Medium. +- Related Topics: String, Sliding Window. +- Similar Questions: . + +## Problem + +You are given a **0-indexed** string `s` that consists of digits from `0` to `9`. + +A string `t` is called a **semi-repetitive** if there is at most one consecutive pair of the same digits inside `t`. For example, `0010`, `002020`, `0123`, `2002`, and `54944` are semi-repetitive while `00101022`, and `1101234883` are not. + +Return **the length of the longest semi-repetitive substring inside** `s`. + +A **substring** is a contiguous **non-empty** sequence of characters within a string. + +  +Example 1: + +``` +Input: s = "52233" +Output: 4 +Explanation: The longest semi-repetitive substring is "5223", which starts at i = 0 and ends at j = 3. +``` + +Example 2: + +``` +Input: s = "5494" +Output: 4 +Explanation: s is a semi-reptitive string, so the answer is 4. +``` + +Example 3: + +``` +Input: s = "1111111" +Output: 2 +Explanation: The longest semi-repetitive substring is "11", which starts at i = 0 and ends at j = 1. +``` + +  +**Constraints:** + + + +- `1 <= s.length <= 50` + +- `'0' <= s[i] <= '9'` + + + +## Solution + +```javascript +/** + * @param {string} s + * @return {number} + */ +var longestSemiRepetitiveSubstring = function(s) { + var max = 1; + var i = 0; + var j = 1; + var last = 0; + while (j < s.length) { + if (s[j] === s[j - 1]) { + if (last) i = last; + last = j; + } + max = Math.max(max, j - i + 1); + j++; + } + return max; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/2701-2800/2742. Painting the Walls.md b/2701-2800/2742. Painting the Walls.md new file mode 100644 index 0000000..dda1c51 --- /dev/null +++ b/2701-2800/2742. Painting the Walls.md @@ -0,0 +1,83 @@ +# 2742. Painting the Walls + +- Difficulty: Hard. +- Related Topics: Array, Dynamic Programming. +- Similar Questions: . + +## Problem + +You are given two **0-indexed** integer arrays, `cost` and `time`, of size `n` representing the costs and the time taken to paint `n` different walls respectively. There are two painters available: + + + +- A** paid painter** that paints the `ith` wall in `time[i]` units of time and takes `cost[i]` units of money. + +- A** free painter** that paints **any** wall in `1` unit of time at a cost of `0`. But the free painter can only be used if the paid painter is already **occupied**. + + +Return **the minimum amount of money required to paint the **`n`** walls.** + +  +Example 1: + +``` +Input: cost = [1,2,3,2], time = [1,2,3,2] +Output: 3 +Explanation: The walls at index 0 and 1 will be painted by the paid painter, and it will take 3 units of time; meanwhile, the free painter will paint the walls at index 2 and 3, free of cost in 2 units of time. Thus, the total cost is 1 + 2 = 3. +``` + +Example 2: + +``` +Input: cost = [2,3,4,2], time = [1,1,1,1] +Output: 4 +Explanation: The walls at index 0 and 3 will be painted by the paid painter, and it will take 2 units of time; meanwhile, the free painter will paint the walls at index 1 and 2, free of cost in 2 units of time. Thus, the total cost is 2 + 2 = 4. +``` + +  +**Constraints:** + + + +- `1 <= cost.length <= 500` + +- `cost.length == time.length` + +- `1 <= cost[i] <= 106` + +- `1 <= time[i] <= 500` + + + +## Solution + +```javascript +/** + * @param {number[]} cost + * @param {number[]} time + * @return {number} + */ +var paintWalls = function(cost, time) { + var dp = Array(cost.length).fill(0).map(() => Array(cost.length + 1)); + return helper(cost, time, 0, cost.length, dp); +}; + +var helper = function(cost, time, i, remains, dp) { + if (remains <= 0) return 0; + if (i === cost.length) return Number.MAX_SAFE_INTEGER; + if (dp[i][remains] !== undefined) return dp[i][remains]; + var paintByPaidPainter = cost[i] + helper(cost, time, i + 1, remains - time[i] - 1, dp); + var paintByFreePainter = helper(cost, time, i + 1, remains, dp); + dp[i][remains] = Math.min(paintByPaidPainter, paintByFreePainter); + return dp[i][remains]; +}; +``` + +**Explain:** + +Top down dp. + +**Complexity:** + +* Time complexity : O(n ^ 2). +* Space complexity : O(n ^ 2). 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/2701-2800/2770. Maximum Number of Jumps to Reach the Last Index.md b/2701-2800/2770. Maximum Number of Jumps to Reach the Last Index.md new file mode 100644 index 0000000..8a552a2 --- /dev/null +++ b/2701-2800/2770. Maximum Number of Jumps to Reach the Last Index.md @@ -0,0 +1,101 @@ +# 2770. Maximum Number of Jumps to Reach the Last Index + +- Difficulty: Medium. +- Related Topics: Array, Dynamic Programming. +- Similar Questions: Jump Game II, Frog Jump, Jump Game III, Jump Game IV, Minimum Jumps to Reach Home, Jump Game VII. + +## Problem + +You are given a **0-indexed** array `nums` of `n` integers and an integer `target`. + +You are initially positioned at index `0`. In one step, you can jump from index `i` to any index `j` such that: + + + +- `0 <= i < j < n` + +- `-target <= nums[j] - nums[i] <= target` + + +Return **the **maximum number of jumps** you can make to reach index** `n - 1`. + +If there is no way to reach index `n - 1`, return `-1`. + +  +Example 1: + +``` +Input: nums = [1,3,6,4,1,2], target = 2 +Output: 3 +Explanation: To go from index 0 to index n - 1 with the maximum number of jumps, you can perform the following jumping sequence: +- Jump from index 0 to index 1. +- Jump from index 1 to index 3. +- Jump from index 3 to index 5. +It can be proven that there is no other jumping sequence that goes from 0 to n - 1 with more than 3 jumps. Hence, the answer is 3. +``` + +Example 2: + +``` +Input: nums = [1,3,6,4,1,2], target = 3 +Output: 5 +Explanation: To go from index 0 to index n - 1 with the maximum number of jumps, you can perform the following jumping sequence: +- Jump from index 0 to index 1. +- Jump from index 1 to index 2. +- Jump from index 2 to index 3. +- Jump from index 3 to index 4. +- Jump from index 4 to index 5. +It can be proven that there is no other jumping sequence that goes from 0 to n - 1 with more than 5 jumps. Hence, the answer is 5. +``` + +Example 3: + +``` +Input: nums = [1,3,6,4,1,2], target = 0 +Output: -1 +Explanation: It can be proven that there is no jumping sequence that goes from 0 to n - 1. Hence, the answer is -1. +``` + +  +**Constraints:** + + + +- `2 <= nums.length == n <= 1000` + +- `-109 <= nums[i] <= 109` + +- `0 <= target <= 2 * 109` + + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +var maximumJumps = function(nums, target) { + var dp = Array(nums.length); + for (var i = nums.length - 1; i >= 0; i--) { + dp[i] = i === nums.length - 1 ? 0 : -1; + for (var j = i + 1; j < nums.length; j++) { + if (Math.abs(nums[j] - nums[i]) <= target && dp[j] !== -1) { + dp[i] = Math.max(dp[i], 1 + dp[j]); + } + } + } + return dp[0]; +}; +``` + +**Explain:** + +Bottom-up dynamic programming. + +**Complexity:** + +* Time complexity : O(n ^ 2). +* Space complexity : O(n). diff --git a/2701-2800/2785. Sort Vowels in a String.md b/2701-2800/2785. Sort Vowels in a String.md new file mode 100644 index 0000000..46e46dc --- /dev/null +++ b/2701-2800/2785. Sort Vowels in a String.md @@ -0,0 +1,86 @@ +# 2785. Sort Vowels in a String + +- Difficulty: Medium. +- Related Topics: String, Sorting. +- Similar Questions: Reverse Vowels of a String. + +## Problem + +Given a **0-indexed** string `s`, **permute** `s` to get a new string `t` such that: + + + +- All consonants remain in their original places. More formally, if there is an index `i` with `0 <= i < s.length` such that `s[i]` is a consonant, then `t[i] = s[i]`. + +- The vowels must be sorted in the **nondecreasing** order of their **ASCII** values. More formally, for pairs of indices `i`, `j` with `0 <= i < j < s.length` such that `s[i]` and `s[j]` are vowels, then `t[i]` must not have a higher ASCII value than `t[j]`. + + +Return **the resulting string**. + +The vowels are `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`, and they can appear in lowercase or uppercase. Consonants comprise all letters that are not vowels. + +  +Example 1: + +``` +Input: s = "lEetcOde" +Output: "lEOtcede" +Explanation: 'E', 'O', and 'e' are the vowels in s; 'l', 't', 'c', and 'd' are all consonants. The vowels are sorted according to their ASCII values, and the consonants remain in the same places. +``` + +Example 2: + +``` +Input: s = "lYmpH" +Output: "lYmpH" +Explanation: There are no vowels in s (all characters in s are consonants), so we return "lYmpH". +``` + +  +**Constraints:** + + + +- `1 <= s.length <= 105` + +- `s` consists only of letters of the English alphabet in **uppercase and lowercase**. + + + +## Solution + +```javascript +/** + * @param {string} s + * @return {string} + */ +var sortVowels = function(s) { + var vowels = s.split('') + .filter(isVowels) + .sort((a, b) => a.charCodeAt(0) - b.charCodeAt(0)); + var res = ''; + var index = 0; + for (var i = 0; i < s.length; i++) { + if (isVowels(s[i])) { + res += vowels[index++]; + } else { + res += s[i]; + } + } + return res; +}; + +var isVowels = function(char) { + var chars = ['a', 'e', 'i', 'o', 'u']; + return chars.includes(char.toLowerCase()) || chars.includes(char.toUpperCase()); +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * log(n)). +* Space complexity : O(n). diff --git a/2701-2800/2790. Maximum Number of Groups With Increasing Length.md b/2701-2800/2790. Maximum Number of Groups With Increasing Length.md new file mode 100644 index 0000000..d876095 --- /dev/null +++ b/2701-2800/2790. Maximum Number of Groups With Increasing Length.md @@ -0,0 +1,103 @@ +# 2790. Maximum Number of Groups With Increasing Length + +- Difficulty: Hard. +- Related Topics: Array, Math, Binary Search, Greedy, Sorting. +- Similar Questions: Group the People Given the Group Size They Belong To. + +## Problem + +You are given a **0-indexed** array `usageLimits` of length `n`. + +Your task is to create **groups** using numbers from `0` to `n - 1`, ensuring that each number, `i`, is used no more than `usageLimits[i]` times in total **across all groups**. You must also satisfy the following conditions: + + + +- Each group must consist of **distinct **numbers, meaning that no duplicate numbers are allowed within a single group. + +- Each group (except the first one) must have a length **strictly greater** than the previous group. + + +Return **an integer denoting the **maximum** number of groups you can create while satisfying these conditions.** + +  +Example 1: + +``` +Input: usageLimits = [1,2,5] +Output: 3 +Explanation: In this example, we can use 0 at most once, 1 at most twice, and 2 at most five times. +One way of creating the maximum number of groups while satisfying the conditions is: +Group 1 contains the number [2]. +Group 2 contains the numbers [1,2]. +Group 3 contains the numbers [0,1,2]. +It can be shown that the maximum number of groups is 3. +So, the output is 3. +``` + +Example 2: + +``` +Input: usageLimits = [2,1,2] +Output: 2 +Explanation: In this example, we can use 0 at most twice, 1 at most once, and 2 at most twice. +One way of creating the maximum number of groups while satisfying the conditions is: +Group 1 contains the number [0]. +Group 2 contains the numbers [1,2]. +It can be shown that the maximum number of groups is 2. +So, the output is 2. +``` + +Example 3: + +``` +Input: usageLimits = [1,1] +Output: 1 +Explanation: In this example, we can use both 0 and 1 at most once. +One way of creating the maximum number of groups while satisfying the conditions is: +Group 1 contains the number [0]. +It can be shown that the maximum number of groups is 1. +So, the output is 1. +``` + +  +**Constraints:** + + + +- `1 <= usageLimits.length <= 105` + +- `1 <= usageLimits[i] <= 109` + + + +## Solution + +```javascript +/** + * @param {number[]} usageLimits + * @return {number} + */ +var maxIncreasingGroups = function(usageLimits) { + var count = 0; + var num = 0; + var minCount = 1; + usageLimits.sort((a, b) => a - b); + for (var i = 0; i < usageLimits.length; i++) { + count += usageLimits[i]; + if (count >= minCount) { + num++; + minCount += num + 1; + } + } + return num; +}; +``` + +**Explain:** + +Math. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/2801-2900/2844. Minimum Operations to Make a Special Number.md b/2801-2900/2844. Minimum Operations to Make a Special Number.md new file mode 100644 index 0000000..0c0d9db --- /dev/null +++ b/2801-2900/2844. Minimum Operations to Make a Special Number.md @@ -0,0 +1,95 @@ +# 2844. Minimum Operations to Make a Special Number + +- Difficulty: Medium. +- Related Topics: . +- Similar Questions: Remove K Digits, Remove Digit From Number to Maximize Result. + +## Problem + +You are given a **0-indexed** string `num` representing a non-negative integer. + +In one operation, you can pick any digit of `num` and delete it. Note that if you delete all the digits of `num`, `num` becomes `0`. + +Return **the **minimum number of operations** required to make** `num` *special*. + +An integer `x` is considered **special** if it is divisible by `25`. + +  +Example 1: + +``` +Input: num = "2245047" +Output: 2 +Explanation: Delete digits num[5] and num[6]. The resulting number is "22450" which is special since it is divisible by 25. +It can be shown that 2 is the minimum number of operations required to get a special number. +``` + +Example 2: + +``` +Input: num = "2908305" +Output: 3 +Explanation: Delete digits num[3], num[4], and num[6]. The resulting number is "2900" which is special since it is divisible by 25. +It can be shown that 3 is the minimum number of operations required to get a special number. +``` + +Example 3: + +``` +Input: num = "10" +Output: 1 +Explanation: Delete digit num[0]. The resulting number is "0" which is special since it is divisible by 25. +It can be shown that 1 is the minimum number of operations required to get a special number. + +``` + +  +**Constraints:** + + + +- `1 <= num.length <= 100` + +- `num` only consists of digits `'0'` through `'9'`. + +- `num` does not contain any leading zeros. + + + +## Solution + +```javascript +/** + * @param {string} num + * @return {number} + */ +var minimumOperations = function(num) { + var min = num.length; + if (num.includes('0')) min = num.length - 1; + var nums = ['25', '50', '75', '00']; + for (var i = 0; i < nums.length; i++) { + var m = 0; + var count = 0; + for (var j = num.length - 1; j >= 0; j--) { + if (num[j] === nums[i][nums[i].length - 1 - m]) { + m++; + if (m === nums[i].length) { + min = Math.min(min, count); + } + } else { + count++; + } + } + } + return min; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/2801-2900/2849. Determine if a Cell Is Reachable at a Given Time.md b/2801-2900/2849. Determine if a Cell Is Reachable at a Given Time.md new file mode 100644 index 0000000..d1d6bcb --- /dev/null +++ b/2801-2900/2849. Determine if a Cell Is Reachable at a Given Time.md @@ -0,0 +1,77 @@ +# 2849. Determine if a Cell Is Reachable at a Given Time + +- Difficulty: Medium. +- Related Topics: Math. +- Similar Questions: Reaching Points. + +## Problem + +You are given four integers `sx`, `sy`, `fx`, `fy`, and a **non-negative** integer `t`. + +In an infinite 2D grid, you start at the cell `(sx, sy)`. Each second, you **must** move to any of its adjacent cells. + +Return `true` **if you can reach cell **`(fx, fy)` **after** exactly**** `t` ****seconds****, **or** `false` **otherwise**. + +A cell's **adjacent cells** are the 8 cells around it that share at least one corner with it. You can visit the same cell several times. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2023/08/05/example2.svg) + +``` +Input: sx = 2, sy = 4, fx = 7, fy = 7, t = 6 +Output: true +Explanation: Starting at cell (2, 4), we can reach cell (7, 7) in exactly 6 seconds by going through the cells depicted in the picture above. +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2023/08/05/example1.svg) + +``` +Input: sx = 3, sy = 1, fx = 7, fy = 3, t = 3 +Output: false +Explanation: Starting at cell (3, 1), it takes at least 4 seconds to reach cell (7, 3) by going through the cells depicted in the picture above. Hence, we cannot reach cell (7, 3) at the third second. +``` + +  +**Constraints:** + + + +- `1 <= sx, sy, fx, fy <= 109` + +- `0 <= t <= 109` + + + +## Solution + +```javascript +/** + * @param {number} sx + * @param {number} sy + * @param {number} fx + * @param {number} fy + * @param {number} t + * @return {boolean} + */ +var isReachableAtTime = function(sx, sy, fx, fy, t) { + const x = Math.abs(sx - fx); + const y = Math.abs(sy - fy); + if (sx === fx && sy === fy && t === 1) { + return false; + } + return Math.max(x, y) <= t; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(1). +* Space complexity : O(1). 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/2801-2900/2870. Minimum Number of Operations to Make Array Empty.md b/2801-2900/2870. Minimum Number of Operations to Make Array Empty.md new file mode 100644 index 0000000..ebf8a41 --- /dev/null +++ b/2801-2900/2870. Minimum Number of Operations to Make Array Empty.md @@ -0,0 +1,87 @@ +# 2870. Minimum Number of Operations to Make Array Empty + +- Difficulty: Medium. +- Related Topics: Array, Hash Table, Greedy, Counting. +- Similar Questions: . + +## Problem + +You are given a **0-indexed** array `nums` consisting of positive integers. + +There are two types of operations that you can apply on the array **any** number of times: + + + +- Choose **two** elements with **equal** values and **delete** them from the array. + +- Choose **three** elements with **equal** values and **delete** them from the array. + + +Return **the **minimum** number of operations required to make the array empty, or **`-1`** if it is not possible**. + +  +Example 1: + +``` +Input: nums = [2,3,3,2,2,4,2,3,4] +Output: 4 +Explanation: We can apply the following operations to make the array empty: +- Apply the first operation on the elements at indices 0 and 3. The resulting array is nums = [3,3,2,4,2,3,4]. +- Apply the first operation on the elements at indices 2 and 4. The resulting array is nums = [3,3,4,3,4]. +- Apply the second operation on the elements at indices 0, 1, and 3. The resulting array is nums = [4,4]. +- Apply the first operation on the elements at indices 0 and 1. The resulting array is nums = []. +It can be shown that we cannot make the array empty in less than 4 operations. +``` + +Example 2: + +``` +Input: nums = [2,1,2,2,3,3] +Output: -1 +Explanation: It is impossible to empty the array. +``` + +  +**Constraints:** + + + +- `2 <= nums.length <= 105` + +- `1 <= nums[i] <= 106` + + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @return {number} + */ +var minOperations = function(nums) { + var map = {}; + for (var i = 0; i < nums.length; i++) { + var num = nums[i]; + map[num] = map[num] || 0; + map[num] += 1; + } + var keys = Object.keys(map); + var res = 0; + for (var j = 0; j < keys.length; j++) { + var num = keys[j]; + if (map[num] === 1) return -1; + res += Math.ceil(map[num] / 3); + } + return res; +}; +``` + +**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/303. Range Sum Query - Immutable.md b/301-400/303. Range Sum Query - Immutable.md new file mode 100644 index 0000000..7ae10b3 --- /dev/null +++ b/301-400/303. Range Sum Query - Immutable.md @@ -0,0 +1,93 @@ +# 303. Range Sum Query - Immutable + +- Difficulty: Easy. +- Related Topics: Array, Design, Prefix Sum. +- Similar Questions: Range Sum Query 2D - Immutable, Range Sum Query - Mutable, Maximum Size Subarray Sum Equals k. + +## Problem + +Given an integer array `nums`, handle multiple queries of the following type: + + + +- Calculate the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** where `left <= right`. + + +Implement the `NumArray` class: + + + +- `NumArray(int[] nums)` Initializes the object with the integer array `nums`. + +- `int sumRange(int left, int right)` Returns the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** (i.e. `nums[left] + nums[left + 1] + ... + nums[right]`). + + +  +Example 1: + +``` +Input +["NumArray", "sumRange", "sumRange", "sumRange"] +[[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]] +Output +[null, 1, -1, -3] + +Explanation +NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]); +numArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1 +numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1 +numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3 +``` + +  +**Constraints:** + + + +- `1 <= nums.length <= 104` + +- `-105 <= nums[i] <= 105` + +- `0 <= left <= right < nums.length` + +- At most `104` calls will be made to `sumRange`. + + + +## Solution + +```javascript +/** + * @param {number[]} nums + */ +var NumArray = function(nums) { + this.leftSum = Array(nums.length); + for (var i = 0; i < nums.length; i++) { + this.leftSum[i] = (this.leftSum[i - 1] || 0) + nums[i]; + } +}; + +/** + * @param {number} left + * @param {number} right + * @return {number} + */ +NumArray.prototype.sumRange = function(left, right) { + return this.leftSum[right] - (this.leftSum[left - 1] || 0); +}; + +/** + * Your NumArray object will be instantiated and called as such: + * var obj = new NumArray(nums) + * var param_1 = obj.sumRange(left,right) + */ +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(1). +* Space complexity : O(n). diff --git a/301-400/304. Range Sum Query 2D - Immutable.md b/301-400/304. Range Sum Query 2D - Immutable.md new file mode 100644 index 0000000..9027f94 --- /dev/null +++ b/301-400/304. Range Sum Query 2D - Immutable.md @@ -0,0 +1,110 @@ +# 304. Range Sum Query 2D - Immutable + +- Difficulty: Medium. +- Related Topics: Array, Design, Matrix, Prefix Sum. +- Similar Questions: Range Sum Query - Immutable, Range Sum Query 2D - Mutable. + +## Problem + +Given a 2D matrix `matrix`, handle multiple queries of the following type: + + + +- Calculate the **sum** of the elements of `matrix` inside the rectangle defined by its **upper left corner** `(row1, col1)` and **lower right corner** `(row2, col2)`. + + +Implement the `NumMatrix` class: + + + +- `NumMatrix(int[][] matrix)` Initializes the object with the integer matrix `matrix`. + +- `int sumRegion(int row1, int col1, int row2, int col2)` Returns the **sum** of the elements of `matrix` inside the rectangle defined by its **upper left corner** `(row1, col1)` and **lower right corner** `(row2, col2)`. + + +You must design an algorithm where `sumRegion` works on `O(1)` time complexity. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2021/03/14/sum-grid.jpg) + +``` +Input +["NumMatrix", "sumRegion", "sumRegion", "sumRegion"] +[[[[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]], [2, 1, 4, 3], [1, 1, 2, 2], [1, 2, 2, 4]] +Output +[null, 8, 11, 12] + +Explanation +NumMatrix numMatrix = new NumMatrix([[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]); +numMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e sum of the red rectangle) +numMatrix.sumRegion(1, 1, 2, 2); // return 11 (i.e sum of the green rectangle) +numMatrix.sumRegion(1, 2, 2, 4); // return 12 (i.e sum of the blue rectangle) +``` + +  +**Constraints:** + + + +- `m == matrix.length` + +- `n == matrix[i].length` + +- `1 <= m, n <= 200` + +- `-104 <= matrix[i][j] <= 104` + +- `0 <= row1 <= row2 < m` + +- `0 <= col1 <= col2 < n` + +- At most `104` calls will be made to `sumRegion`. + + + +## Solution + +```javascript +/** + * @param {number[][]} matrix + */ +var NumMatrix = function(matrix) { + var m = matrix.length; + var n = matrix[0].length; + var cache = Array(m + 1).fill(0).map(() => Array(n + 1).fill(0)); + for (var i = 1; i <= m; i++) { + for (var j = 1; j <= n; j++) { + cache[i][j] = cache[i - 1][j] + cache[i][j - 1] - cache[i - 1][j - 1] + matrix[i - 1][j - 1]; + } + } + this.cache = cache; +}; + +/** + * @param {number} row1 + * @param {number} col1 + * @param {number} row2 + * @param {number} col2 + * @return {number} + */ +NumMatrix.prototype.sumRegion = function(row1, col1, row2, col2) { + return this.cache[row2 + 1][col2 + 1] - this.cache[row2 + 1][col1] - this.cache[row1][col2 + 1] + this.cache[row1][col1]; +}; + +/** + * Your NumMatrix object will be instantiated and called as such: + * var obj = new NumMatrix(matrix) + * var param_1 = obj.sumRegion(row1,col1,row2,col2) + */ +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(1). +* Space complexity : O(n). 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/315. Count of Smaller Numbers After Self.md b/301-400/315. Count of Smaller Numbers After Self.md new file mode 100644 index 0000000..751da67 --- /dev/null +++ b/301-400/315. Count of Smaller Numbers After Self.md @@ -0,0 +1,96 @@ +# 315. Count of Smaller Numbers After Self + +- Difficulty: Hard. +- Related Topics: Array, Binary Search, Divide and Conquer, Binary Indexed Tree, Segment Tree, Merge Sort, Ordered Set. +- Similar Questions: Count of Range Sum, Queue Reconstruction by Height, Reverse Pairs, How Many Numbers Are Smaller Than the Current Number, Count Good Triplets in an Array, Count the Number of K-Big Indices. + +## Problem + +Given an integer array `nums`, return** an integer array **`counts`** where **`counts[i]`** is the number of smaller elements to the right of **`nums[i]`. + +  +Example 1: + +``` +Input: nums = [5,2,6,1] +Output: [2,1,1,0] +Explanation: +To the right of 5 there are 2 smaller elements (2 and 1). +To the right of 2 there is only 1 smaller element (1). +To the right of 6 there is 1 smaller element (1). +To the right of 1 there is 0 smaller element. +``` + +Example 2: + +``` +Input: nums = [-1] +Output: [0] +``` + +Example 3: + +``` +Input: nums = [-1,-1] +Output: [0,0] +``` + +  +**Constraints:** + + + +- `1 <= nums.length <= 105` + +- `-104 <= nums[i] <= 104` + + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @return {number[]} + */ +var countSmaller = function(nums) { + var arr = nums.map((num, i) => [num, i]); + var res = Array(nums.length).fill(0); + mergeSort(arr, res); + return res; +}; + +var mergeSort = function(arr, res) { + if (arr.length === 1) return arr; + var mid = Math.floor(arr.length / 2); + var left = mergeSort(arr.slice(0, mid), res); + var right = mergeSort(arr.slice(mid), res); + return merge(left, right, res); +}; + +var merge = function(left, right, res) { + var arr = []; + var leftIndex = 0; + var rightIndex = 0; + while (leftIndex < left.length || rightIndex < right.length) { + if (!right[rightIndex] || (left[leftIndex] && left[leftIndex][0] > right[rightIndex][0])) { + arr.push(left[leftIndex]); + res[left[leftIndex][1]] += right.length - rightIndex; + leftIndex += 1; + } else { + arr.push(right[rightIndex]); + rightIndex += 1; + } + } + return arr; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * log(n)). +* Space complexity : O(n). diff --git a/301-400/319. Bulb Switcher.md b/301-400/319. Bulb Switcher.md new file mode 100644 index 0000000..b421a04 --- /dev/null +++ b/301-400/319. Bulb Switcher.md @@ -0,0 +1,77 @@ +# 319. Bulb Switcher + +- Difficulty: Medium. +- Related Topics: Math, Brainteaser. +- Similar Questions: Bulb Switcher II, Minimum Number of K Consecutive Bit Flips, Number of Times Binary String Is Prefix-Aligned, Find the Pivot Integer. + +## Problem + +There are `n` bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb. + +On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the `ith` round, you toggle every `i` bulb. For the `nth` round, you only toggle the last bulb. + +Return **the number of bulbs that are on after `n` rounds**. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2020/11/05/bulb.jpg) + +``` +Input: n = 3 +Output: 1 +Explanation: At first, the three bulbs are [off, off, off]. +After the first round, the three bulbs are [on, on, on]. +After the second round, the three bulbs are [on, off, on]. +After the third round, the three bulbs are [on, off, off]. +So you should return 1 because there is only one bulb is on. +``` + +Example 2: + +``` +Input: n = 0 +Output: 0 +``` + +Example 3: + +``` +Input: n = 1 +Output: 1 +``` + +  +**Constraints:** + + + +- `0 <= n <= 109` + + + +## Solution + +```javascript +/** + * @param {number} n + * @return {number} + */ +var bulbSwitch = function(n) { + return Math.floor(Math.sqrt(n)); +}; +``` + +**Explain:** + +For the `k`th bulb, it is switched exactly a number of times that is a divisor of `k`. If `k` has an even number of divisors, then the final state of the `k`th light bulb is dark; if `k` has an odd number of divisors, then the final state of the `k`th light bulb is bright. + + +For `k`, if it has divisor `x`, then there must be divisor `k/x`. Therefore, as long as at that time, divisors appear in "pairs". This means that only when `k` is a "perfect square number", it will have an odd number of divisors, otherwise it must have an even number of divisors. + +Therefore, we only need to find out the number of perfect square numbers in `1 ~ n`, and the answer is `sqrt(n)` + +**Complexity:** + +* Time complexity : O(1). +* Space complexity : O(1). diff --git a/301-400/332. Reconstruct Itinerary.md b/301-400/332. Reconstruct Itinerary.md new file mode 100644 index 0000000..b92e96a --- /dev/null +++ b/301-400/332. Reconstruct Itinerary.md @@ -0,0 +1,95 @@ +# 332. Reconstruct Itinerary + +- Difficulty: Hard. +- Related Topics: Depth-First Search, Graph, Eulerian Circuit. +- Similar Questions: Longest Common Subpath, Valid Arrangement of Pairs. + +## Problem + +You are given a list of airline `tickets` where `tickets[i] = [fromi, toi]` represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it. + +All of the tickets belong to a man who departs from `"JFK"`, thus, the itinerary must begin with `"JFK"`. If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. + + + +- For example, the itinerary `["JFK", "LGA"]` has a smaller lexical order than `["JFK", "LGB"]`. + + +You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2021/03/14/itinerary1-graph.jpg) + +``` +Input: tickets = [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]] +Output: ["JFK","MUC","LHR","SFO","SJC"] +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2021/03/14/itinerary2-graph.jpg) + +``` +Input: tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]] +Output: ["JFK","ATL","JFK","SFO","ATL","SFO"] +Explanation: Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"] but it is larger in lexical order. +``` + +  +**Constraints:** + + + +- `1 <= tickets.length <= 300` + +- `tickets[i].length == 2` + +- `fromi.length == 3` + +- `toi.length == 3` + +- `fromi` and `toi` consist of uppercase English letters. + +- `fromi != toi` + + + +## Solution + +```javascript +/** + * @param {string[][]} tickets + * @return {string[]} + */ +var findItinerary = function(tickets) { + tickets.sort((a, b) => (a[1] === b[1] ? 0 : (a[1] < b[1] ? -1 : 1))); + + var map = {}; + for (var i = 0; i < tickets.length; i++) { + if (!map[tickets[i][0]]) map[tickets[i][0]] = []; + map[tickets[i][0]].push(tickets[i][1]); + } + + var itinerary = []; + dfs('JFK', map, itinerary); + return itinerary.reverse(); +}; + +var dfs = function(airport, map, itinerary) { + while (map[airport]?.length) { + dfs(map[airport].shift(), map, itinerary); + } + itinerary.push(airport); +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * log(n)). +* Space complexity : O(n). diff --git a/301-400/338. Counting Bits.md b/301-400/338. Counting Bits.md new file mode 100644 index 0000000..f04960c --- /dev/null +++ b/301-400/338. Counting Bits.md @@ -0,0 +1,91 @@ +# 338. Counting Bits + +- Difficulty: Easy. +- Related Topics: Dynamic Programming, Bit Manipulation. +- Similar Questions: Number of 1 Bits. + +## Problem + +Given an integer `n`, return **an array **`ans`** of length **`n + 1`** such that for each **`i`** **(`0 <= i <= n`)**, **`ans[i]`** is the **number of ****`1`****'s** in the binary representation of **`i`. + +  +Example 1: + +``` +Input: n = 2 +Output: [0,1,1] +Explanation: +0 --> 0 +1 --> 1 +2 --> 10 +``` + +Example 2: + +``` +Input: n = 5 +Output: [0,1,1,2,1,2] +Explanation: +0 --> 0 +1 --> 1 +2 --> 10 +3 --> 11 +4 --> 100 +5 --> 101 +``` + +  +**Constraints:** + + + +- `0 <= n <= 105` + + +  +**Follow up:** + + + +- It is very easy to come up with a solution with a runtime of `O(n log n)`. Can you do it in linear time `O(n)` and possibly in a single pass? + +- Can you do it without using any built-in function (i.e., like `__builtin_popcount` in C++)? + + + +## Solution + +```javascript +/** + * @param {number} n + * @return {number[]} + */ +var countBits = function(n) { + var res = Array(n + 1); + var num = 2; + var nextNum = 4; + for (var i = 0; i <= n; i++) { + if (i === 0) { + res[i] = 0; + } else if (i === 1) { + res[i] = 1; + } else { + if (i === nextNum) { + num = nextNum; + nextNum *= 2; + } + res[i] = 1 + res[i - num]; + } + } + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/301-400/341. Flatten Nested List Iterator.md b/301-400/341. Flatten Nested List Iterator.md new file mode 100644 index 0000000..b13ab2a --- /dev/null +++ b/301-400/341. Flatten Nested List Iterator.md @@ -0,0 +1,141 @@ +# 341. Flatten Nested List Iterator + +- Difficulty: Medium. +- Related Topics: Stack, Tree, Depth-First Search, Design, Queue, Iterator. +- Similar Questions: Flatten 2D Vector, Zigzag Iterator, Mini Parser, Array Nesting. + +## Problem + +You are given a nested list of integers `nestedList`. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it. + +Implement the `NestedIterator` class: + + + +- `NestedIterator(List nestedList)` Initializes the iterator with the nested list `nestedList`. + +- `int next()` Returns the next integer in the nested list. + +- `boolean hasNext()` Returns `true` if there are still some integers in the nested list and `false` otherwise. + + +Your code will be tested with the following pseudocode: + +``` +initialize iterator with nestedList +res = [] +while iterator.hasNext() + append iterator.next() to the end of res +return res +``` + +If `res` matches the expected flattened list, then your code will be judged as correct. + +  +Example 1: + +``` +Input: nestedList = [[1,1],2,[1,1]] +Output: [1,1,2,1,1] +Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1]. +``` + +Example 2: + +``` +Input: nestedList = [1,[4,[6]]] +Output: [1,4,6] +Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6]. +``` + +  +**Constraints:** + + + +- `1 <= nestedList.length <= 500` + +- The values of the integers in the nested list is in the range `[-106, 106]`. + + + +## Solution + +```javascript +/** + * // This is the interface that allows for creating nested lists. + * // You should not implement it, or speculate about its implementation + * function NestedInteger() { + * + * Return true if this NestedInteger holds a single integer, rather than a nested list. + * @return {boolean} + * this.isInteger = function() { + * ... + * }; + * + * Return the single integer that this NestedInteger holds, if it holds a single integer + * Return null if this NestedInteger holds a nested list + * @return {integer} + * this.getInteger = function() { + * ... + * }; + * + * Return the nested list that this NestedInteger holds, if it holds a nested list + * Return null if this NestedInteger holds a single integer + * @return {NestedInteger[]} + * this.getList = function() { + * ... + * }; + * }; + */ +/** + * @constructor + * @param {NestedInteger[]} nestedList + */ +var NestedIterator = function(nestedList) { + this.index = 0; + this.list = []; + const flatten = (list) => { + for (var item of list) { + if (item.isInteger()) { + this.list.push(item.getInteger()); + } else { + flatten(item.getList()); + } + } + }; + flatten(nestedList); +}; + + +/** + * @this NestedIterator + * @returns {boolean} + */ +NestedIterator.prototype.hasNext = function() { + return this.index < this.list.length; +}; + +/** + * @this NestedIterator + * @returns {integer} + */ +NestedIterator.prototype.next = function() { + return this.list[this.index++]; +}; + +/** + * Your NestedIterator will be called like this: + * var i = new NestedIterator(nestedList), a = []; + * while (i.hasNext()) a.push(i.next()); +*/ +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/301-400/342. Power of Four.md b/301-400/342. Power of Four.md new file mode 100644 index 0000000..a87223f --- /dev/null +++ b/301-400/342. Power of Four.md @@ -0,0 +1,58 @@ +# 342. Power of Four + +- Difficulty: Easy. +- Related Topics: Math, Bit Manipulation, Recursion. +- Similar Questions: Power of Two, Power of Three. + +## Problem + +Given an integer `n`, return **`true` if it is a power of four. Otherwise, return `false`**. + +An integer `n` is a power of four, if there exists an integer `x` such that `n == 4x`. + +  +Example 1: +``` +Input: n = 16 +Output: true +```Example 2: +``` +Input: n = 5 +Output: false +```Example 3: +``` +Input: n = 1 +Output: true +``` +  +**Constraints:** + + + +- `-231 <= n <= 231 - 1` + + +  +**Follow up:** Could you solve it without loops/recursion? + +## Solution + +```javascript +/** + * @param {number} n + * @return {boolean} + */ +var isPowerOfFour = function(n) { + var num = 0b1010101010101010101010101010101; + return n > 0 && (n & (n - 1)) === 0 && (n & num) === n; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(1). +* Space complexity : O(1). diff --git a/301-400/343. Integer Break.md b/301-400/343. Integer Break.md new file mode 100644 index 0000000..25a36dc --- /dev/null +++ b/301-400/343. Integer Break.md @@ -0,0 +1,71 @@ +# 343. Integer Break + +- Difficulty: Medium. +- Related Topics: Math, Dynamic Programming. +- Similar Questions: Maximize Number of Nice Divisors. + +## Problem + +Given an integer `n`, break it into the sum of `k` **positive integers**, where `k >= 2`, and maximize the product of those integers. + +Return **the maximum product you can get**. + +  +Example 1: + +``` +Input: n = 2 +Output: 1 +Explanation: 2 = 1 + 1, 1 × 1 = 1. +``` + +Example 2: + +``` +Input: n = 10 +Output: 36 +Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36. +``` + +  +**Constraints:** + + + +- `2 <= n <= 58` + + + +## Solution + +```javascript +/** + * @param {number} n + * @return {number} + */ +var integerBreak = function(n) { + if (n < 4) return n - 1; + var res = 1; + while (n) { + if (n > 4) { + res *= 3; + n -= 3; + } else if (n <= 4 && n >= 2) { + res *= n; + n = 0; + } else if (n === 1) { + n = 0; + } + } + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). 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/377. Combination Sum IV.md b/301-400/377. Combination Sum IV.md new file mode 100644 index 0000000..d3628cb --- /dev/null +++ b/301-400/377. Combination Sum IV.md @@ -0,0 +1,84 @@ +# 377. Combination Sum IV + +- Difficulty: Medium. +- Related Topics: Array, Dynamic Programming. +- Similar Questions: Combination Sum, Ways to Express an Integer as Sum of Powers. + +## Problem + +Given an array of **distinct** integers `nums` and a target integer `target`, return **the number of possible combinations that add up to** `target`. + +The test cases are generated so that the answer can fit in a **32-bit** integer. + +  +Example 1: + +``` +Input: nums = [1,2,3], target = 4 +Output: 7 +Explanation: +The possible combination ways are: +(1, 1, 1, 1) +(1, 1, 2) +(1, 2, 1) +(1, 3) +(2, 1, 1) +(2, 2) +(3, 1) +Note that different sequences are counted as different combinations. +``` + +Example 2: + +``` +Input: nums = [9], target = 3 +Output: 0 +``` + +  +**Constraints:** + + + +- `1 <= nums.length <= 200` + +- `1 <= nums[i] <= 1000` + +- All the elements of `nums` are **unique**. + +- `1 <= target <= 1000` + + +  +**Follow up:** What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers? + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +var combinationSum4 = function(nums, target, map = {}) { + if (target === 0) return 1; + if (map[target] !== undefined) return map[target]; + var res = 0; + for (var i = 0; i < nums.length; i++) { + if (nums[i] > target) continue; + res += combinationSum4(nums, target - nums[i], map); + } + map[target] = res; + return res; +}; +``` + +**Explain:** + +Top-down dynamic programming. + +**Complexity:** + +* Time complexity : O(target). +* Space complexity : O(target * n). diff --git a/301-400/380. Insert Delete GetRandom O(1).md b/301-400/380. Insert Delete GetRandom O(1).md new file mode 100644 index 0000000..6584e90 --- /dev/null +++ b/301-400/380. Insert Delete GetRandom O(1).md @@ -0,0 +1,122 @@ +# 380. Insert Delete GetRandom O(1) + +- Difficulty: Medium. +- Related Topics: Array, Hash Table, Math, Design, Randomized. +- Similar Questions: Insert Delete GetRandom O(1) - Duplicates allowed. + +## Problem + +Implement the `RandomizedSet` class: + + + +- `RandomizedSet()` Initializes the `RandomizedSet` object. + +- `bool insert(int val)` Inserts an item `val` into the set if not present. Returns `true` if the item was not present, `false` otherwise. + +- `bool remove(int val)` Removes an item `val` from the set if present. Returns `true` if the item was present, `false` otherwise. + +- `int getRandom()` Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the **same probability** of being returned. + + +You must implement the functions of the class such that each function works in **average** `O(1)` time complexity. + +  +Example 1: + +``` +Input +["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom"] +[[], [1], [2], [2], [], [1], [2], []] +Output +[null, true, false, true, 2, true, false, 2] + +Explanation +RandomizedSet randomizedSet = new RandomizedSet(); +randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully. +randomizedSet.remove(2); // Returns false as 2 does not exist in the set. +randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains [1,2]. +randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly. +randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains [2]. +randomizedSet.insert(2); // 2 was already in the set, so return false. +randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2. +``` + +  +**Constraints:** + + + +- `-231 <= val <= 231 - 1` + +- At most `2 * ``105` calls will be made to `insert`, `remove`, and `getRandom`. + +- There will be **at least one** element in the data structure when `getRandom` is called. + + + +## Solution + +```javascript + +var RandomizedSet = function() { + this.map = {}; + this.arr = []; +}; + +/** + * @param {number} val + * @return {boolean} + */ +RandomizedSet.prototype.insert = function(val) { + if (this.map[val] === undefined) { + this.map[val] = this.arr.length; + this.arr.push(val); + return true; + } + return false; +}; + +/** + * @param {number} val + * @return {boolean} + */ +RandomizedSet.prototype.remove = function(val) { + if (this.map[val] !== undefined) { + var delIndex = this.map[val]; + var lastVal = this.arr.pop(); + if (delIndex < this.arr.length) { + this.arr[delIndex] = lastVal; + this.map[lastVal] = delIndex; + } + delete this.map[val]; + return true; + } + return false; +}; + +/** + * @return {number} + */ +RandomizedSet.prototype.getRandom = function() { + const num = Math.floor(Math.random() * this.arr.length); + return this.arr[num]; +}; + +/** + * Your RandomizedSet object will be instantiated and called as such: + * var obj = new RandomizedSet() + * var param_1 = obj.insert(val) + * var param_2 = obj.remove(val) + * var param_3 = obj.getRandom() + */ +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(1). +* Space complexity : O(n). diff --git a/301-400/381. Insert Delete GetRandom O(1) - Duplicates allowed.md b/301-400/381. Insert Delete GetRandom O(1) - Duplicates allowed.md new file mode 100644 index 0000000..01b8bc5 --- /dev/null +++ b/301-400/381. Insert Delete GetRandom O(1) - Duplicates allowed.md @@ -0,0 +1,138 @@ +# 381. Insert Delete GetRandom O(1) - Duplicates allowed + +- Difficulty: Hard. +- Related Topics: Array, Hash Table, Math, Design, Randomized. +- Similar Questions: Insert Delete GetRandom O(1). + +## Problem + +`RandomizedCollection` is a data structure that contains a collection of numbers, possibly duplicates (i.e., a multiset). It should support inserting and removing specific elements and also reporting a random element. + +Implement the `RandomizedCollection` class: + + + +- `RandomizedCollection()` Initializes the empty `RandomizedCollection` object. + +- `bool insert(int val)` Inserts an item `val` into the multiset, even if the item is already present. Returns `true` if the item is not present, `false` otherwise. + +- `bool remove(int val)` Removes an item `val` from the multiset if present. Returns `true` if the item is present, `false` otherwise. Note that if `val` has multiple occurrences in the multiset, we only remove one of them. + +- `int getRandom()` Returns a random element from the current multiset of elements. The probability of each element being returned is **linearly related** to the number of the same values the multiset contains. + + +You must implement the functions of the class such that each function works on **average** `O(1)` time complexity. + +**Note:** The test cases are generated such that `getRandom` will only be called if there is **at least one** item in the `RandomizedCollection`. + +  +Example 1: + +``` +Input +["RandomizedCollection", "insert", "insert", "insert", "getRandom", "remove", "getRandom"] +[[], [1], [1], [2], [], [1], []] +Output +[null, true, false, true, 2, true, 1] + +Explanation +RandomizedCollection randomizedCollection = new RandomizedCollection(); +randomizedCollection.insert(1); // return true since the collection does not contain 1. + // Inserts 1 into the collection. +randomizedCollection.insert(1); // return false since the collection contains 1. + // Inserts another 1 into the collection. Collection now contains [1,1]. +randomizedCollection.insert(2); // return true since the collection does not contain 2. + // Inserts 2 into the collection. Collection now contains [1,1,2]. +randomizedCollection.getRandom(); // getRandom should: + // - return 1 with probability 2/3, or + // - return 2 with probability 1/3. +randomizedCollection.remove(1); // return true since the collection contains 1. + // Removes 1 from the collection. Collection now contains [1,2]. +randomizedCollection.getRandom(); // getRandom should return 1 or 2, both equally likely. +``` + +  +**Constraints:** + + + +- `-231 <= val <= 231 - 1` + +- At most `2 * 105` calls **in total** will be made to `insert`, `remove`, and `getRandom`. + +- There will be **at least one** element in the data structure when `getRandom` is called. + + + +## Solution + +```javascript + +var RandomizedCollection = function() { + this.map = {}; + this.arr = []; +}; + +/** + * @param {number} val + * @return {boolean} + */ +RandomizedCollection.prototype.insert = function(val) { + var notFound = this.map[val] === undefined; + if (notFound) this.map[val] = { arr: [], map: {} }; + this.map[val].map[this.arr.length] = this.map[val].arr.length; + this.map[val].arr.push(this.arr.length); + this.arr.push(val); + return notFound; +}; + +/** + * @param {number} val + * @return {boolean} + */ +RandomizedCollection.prototype.remove = function(val) { + if (this.map[val] === undefined) return false; + var valIndexs = this.map[val].arr; + var delIndex = valIndexs[valIndexs.length - 1]; + var lastValue = this.arr.pop(); + if (valIndexs.length === 1) { + delete this.map[val]; + } else { + valIndexs.pop(); + delete this.map[val].map[delIndex]; + } + if (lastValue !== val) { + var lastValueIndex = this.map[lastValue].map[this.arr.length]; + this.map[lastValue].arr[lastValueIndex] = delIndex; + delete this.map[lastValue].map[this.arr.length]; + this.map[lastValue].map[delIndex] = lastValueIndex; + this.arr[delIndex] = lastValue; + } + return true; +}; + +/** + * @return {number} + */ +RandomizedCollection.prototype.getRandom = function() { + var num = Math.floor(Math.random() * this.arr.length); + return this.arr[num]; +}; + +/** + * Your RandomizedCollection object will be instantiated and called as such: + * var obj = new RandomizedCollection() + * var param_1 = obj.insert(val) + * var param_2 = obj.remove(val) + * var param_3 = obj.getRandom() + */ +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(1). +* Space complexity : O(n). 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/301-400/389. Find the Difference.md b/301-400/389. Find the Difference.md new file mode 100644 index 0000000..1218ec5 --- /dev/null +++ b/301-400/389. Find the Difference.md @@ -0,0 +1,100 @@ +# 389. Find the Difference + +- Difficulty: Easy. +- Related Topics: Hash Table, String, Bit Manipulation, Sorting. +- Similar Questions: Single Number. + +## Problem + +You are given two strings `s` and `t`. + +String `t` is generated by random shuffling string `s` and then add one more letter at a random position. + +Return the letter that was added to `t`. + +  +Example 1: + +``` +Input: s = "abcd", t = "abcde" +Output: "e" +Explanation: 'e' is the letter that was added. +``` + +Example 2: + +``` +Input: s = "", t = "y" +Output: "y" +``` + +  +**Constraints:** + + + +- `0 <= s.length <= 1000` + +- `t.length == s.length + 1` + +- `s` and `t` consist of lowercase English letters. + + + +## Solution 1 + +```javascript +/** + * @param {string} s + * @param {string} t + * @return {character} + */ +var findTheDifference = function(s, t) { + var num = 0; + for (var i = 0; i < t.length; i++) { + num += t[i].charCodeAt(0); + } + for (var j = 0; j < s.length; j++) { + num -= s[j].charCodeAt(0); + } + return String.fromCharCode(num); +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). + +## Solution 2 + +```javascript +/** + * @param {string} s + * @param {string} t + * @return {character} + */ +var findTheDifference = function(s, t) { + var num = 0; + for (var i = 0; i < t.length; i++) { + num ^= t[i].charCodeAt(0); + } + for (var j = 0; j < s.length; j++) { + num ^= s[j].charCodeAt(0); + } + return String.fromCharCode(num); +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/301-400/392. Is Subsequence.md b/301-400/392. Is Subsequence.md new file mode 100644 index 0000000..6c18631 --- /dev/null +++ b/301-400/392. Is Subsequence.md @@ -0,0 +1,64 @@ +# 392. Is Subsequence + +- Difficulty: Easy. +- Related Topics: Two Pointers, String, Dynamic Programming. +- Similar Questions: Number of Matching Subsequences, Shortest Way to Form String, Append Characters to String to Make Subsequence, Make String a Subsequence Using Cyclic Increments. + +## Problem + +Given two strings `s` and `t`, return `true`** if **`s`** is a **subsequence** of **`t`**, or **`false`** otherwise**. + +A **subsequence** of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., `"ace"` is a subsequence of `"abcde"` while `"aec"` is not). + +  +Example 1: +``` +Input: s = "abc", t = "ahbgdc" +Output: true +```Example 2: +``` +Input: s = "axc", t = "ahbgdc" +Output: false +``` +  +**Constraints:** + + + +- `0 <= s.length <= 100` + +- `0 <= t.length <= 104` + +- `s` and `t` consist only of lowercase English letters. + + +  +**Follow up:** Suppose there are lots of incoming `s`, say `s1, s2, ..., sk` where `k >= 109`, and you want to check one by one to see if `t` has its subsequence. In this scenario, how would you change your code? + +## Solution + +```javascript +/** + * @param {string} s + * @param {string} t + * @return {boolean} + */ +var isSubsequence = function(s, t) { + var j = 0; + for (var i = 0; i < s.length; i++) { + while (s[i] !== t[j] && j < t.length - 1) j++; + if (s[i] != t[j]) return false; + j++; + } + return true; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/401-500/403. Frog Jump.md b/401-500/403. Frog Jump.md new file mode 100644 index 0000000..95ab353 --- /dev/null +++ b/401-500/403. Frog Jump.md @@ -0,0 +1,80 @@ +# 403. Frog Jump + +- Difficulty: Hard. +- Related Topics: Array, Dynamic Programming. +- Similar Questions: Minimum Sideway Jumps, Solving Questions With Brainpower, Maximum Number of Jumps to Reach the Last Index. + +## Problem + +A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water. + +Given a list of `stones`' positions (in units) in sorted **ascending order**, determine if the frog can cross the river by landing on the last stone. Initially, the frog is on the first stone and assumes the first jump must be `1` unit. + +If the frog's last jump was `k` units, its next jump must be either `k - 1`, `k`, or `k + 1` units. The frog can only jump in the forward direction. + +  +Example 1: + +``` +Input: stones = [0,1,3,5,6,8,12,17] +Output: true +Explanation: The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone. +``` + +Example 2: + +``` +Input: stones = [0,1,2,3,4,8,9,11] +Output: false +Explanation: There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large. +``` + +  +**Constraints:** + + + +- `2 <= stones.length <= 2000` + +- `0 <= stones[i] <= 231 - 1` + +- `stones[0] == 0` + +- `stones` is sorted in a strictly increasing order. + + + +## Solution + +```javascript +/** + * @param {number[]} stones + * @return {boolean} + */ +var canCross = function(stones) { + return stones[1] - stones[0] === 1 + ? helper(stones, 1, 1, Array(stones.length).fill(0).map(() => ({}))) + : false; +}; + +var helper = function(stones, i, k, dp) { + if (dp[i][k]) return false; + for (var j = i + 1; j < stones.length; j++) { + var diff = stones[j] - stones[i]; + if (diff > k + 1) break; + if (diff < k - 1) continue; + if (helper(stones, j, diff, dp)) return true; + } + dp[i][k] = true; + return i === stones.length - 1; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n ^ 2). +* Space complexity : O(n ^ 2). diff --git a/401-500/445. Add Two Numbers II.md b/401-500/445. Add Two Numbers II.md new file mode 100644 index 0000000..090c8b9 --- /dev/null +++ b/401-500/445. Add Two Numbers II.md @@ -0,0 +1,112 @@ +# 445. Add Two Numbers II + +- Difficulty: Medium. +- Related Topics: Linked List, Math, Stack. +- Similar Questions: Add Two Numbers, Add Two Polynomials Represented as Linked Lists. + +## Problem + +You are given two **non-empty** linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. + +You may assume the two numbers do not contain any leading zero, except the number 0 itself. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2021/04/09/sumii-linked-list.jpg) + +``` +Input: l1 = [7,2,4,3], l2 = [5,6,4] +Output: [7,8,0,7] +``` + +Example 2: + +``` +Input: l1 = [2,4,3], l2 = [5,6,4] +Output: [8,0,7] +``` + +Example 3: + +``` +Input: l1 = [0], l2 = [0] +Output: [0] +``` + +  +**Constraints:** + + + +- The number of nodes in each linked list is in the range `[1, 100]`. + +- `0 <= Node.val <= 9` + +- It is guaranteed that the list represents a number that does not have leading zeros. + + +  +**Follow up:** Could you solve it without reversing the input lists? + + +## 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} l1 + * @param {ListNode} l2 + * @return {ListNode} + */ +var addTwoNumbers = function(l1, l2) { + var r1 = reverse(l1); + var r2 = reverse(l2); + var root = new ListNode(); + var node = root; + var carry = 0; + var val = 0; + while (r1 || r2) { + val = (r1 ? r1.val : 0) + (r2 ? r2.val : 0) + carry; + node.next = new ListNode(val % 10); + node = node.next; + carry = (val - node.val) / 10; + r1 = r1 ? r1.next : null; + r2 = r2 ? r2.next : null; + } + if (carry) { + node.next = new ListNode(carry); + node = node.next; + } + return reverse(root.next); +}; + +var reverse = function(root) { + var node = root.next; + var last = root; + var tmp = null; + last.next = null; + while (node) { + tmp = node.next; + node.next = last; + last = node; + node = tmp; + } + return last; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). 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/456. 132 Pattern.md b/401-500/456. 132 Pattern.md new file mode 100644 index 0000000..663d03b --- /dev/null +++ b/401-500/456. 132 Pattern.md @@ -0,0 +1,84 @@ +# 456. 132 Pattern + +- Difficulty: Medium. +- Related Topics: Array, Binary Search, Stack, Monotonic Stack, Ordered Set. +- Similar Questions: . + +## Problem + +Given an array of `n` integers `nums`, a **132 pattern** is a subsequence of three integers `nums[i]`, `nums[j]` and `nums[k]` such that `i < j < k` and `nums[i] < nums[k] < nums[j]`. + +Return `true`** if there is a **132 pattern** in **`nums`**, otherwise, return **`false`**.** + +  +Example 1: + +``` +Input: nums = [1,2,3,4] +Output: false +Explanation: There is no 132 pattern in the sequence. +``` + +Example 2: + +``` +Input: nums = [3,1,4,2] +Output: true +Explanation: There is a 132 pattern in the sequence: [1, 4, 2]. +``` + +Example 3: + +``` +Input: nums = [-1,3,2,0] +Output: true +Explanation: There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0]. +``` + +  +**Constraints:** + + + +- `n == nums.length` + +- `1 <= n <= 2 * 105` + +- `-109 <= nums[i] <= 109` + + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @return {boolean} + */ +var find132pattern = function(nums) { + if (nums.length < 3) return false; + var stack = []; + var min = Array(nums.length); + min[0] = nums[0]; + for (var i = 1; i < nums.length; i++) { + min[i] = Math.min(min[i - 1], nums[i]); + } + for (var j = nums.length - 1; j >= 0; j--) { + if (nums[j] > min[j]) { + while (stack.length && stack[stack.length - 1] <= min[j]) stack.pop(); + if (stack.length && stack[stack.length - 1] < nums[j]) return true; + stack.push(nums[j]); + } + } + return false; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/401-500/458. Poor Pigs.md b/401-500/458. Poor Pigs.md new file mode 100644 index 0000000..8b54d51 --- /dev/null +++ b/401-500/458. Poor Pigs.md @@ -0,0 +1,96 @@ +# 458. Poor Pigs + +- Difficulty: Hard. +- Related Topics: Math, Dynamic Programming, Combinatorics. +- Similar Questions: . + +## Problem + +There are `buckets` buckets of liquid, where **exactly one** of the buckets is poisonous. To figure out which one is poisonous, you feed some number of (poor) pigs the liquid to see whether they will die or not. Unfortunately, you only have `minutesToTest` minutes to determine which bucket is poisonous. + +You can feed the pigs according to these steps: + + + +- Choose some live pigs to feed. + +- For each pig, choose which buckets to feed it. The pig will consume all the chosen buckets simultaneously and will take no time. Each pig can feed from any number of buckets, and each bucket can be fed from by any number of pigs. + +- Wait for `minutesToDie` minutes. You may **not** feed any other pigs during this time. + +- After `minutesToDie` minutes have passed, any pigs that have been fed the poisonous bucket will die, and all others will survive. + +- Repeat this process until you run out of time. + + +Given `buckets`, `minutesToDie`, and `minutesToTest`, return **the **minimum** number of pigs needed to figure out which bucket is poisonous within the allotted time**. + +  +Example 1: + +``` +Input: buckets = 4, minutesToDie = 15, minutesToTest = 15 +Output: 2 +Explanation: We can determine the poisonous bucket as follows: +At time 0, feed the first pig buckets 1 and 2, and feed the second pig buckets 2 and 3. +At time 15, there are 4 possible outcomes: +- If only the first pig dies, then bucket 1 must be poisonous. +- If only the second pig dies, then bucket 3 must be poisonous. +- If both pigs die, then bucket 2 must be poisonous. +- If neither pig dies, then bucket 4 must be poisonous. +``` + +Example 2: + +``` +Input: buckets = 4, minutesToDie = 15, minutesToTest = 30 +Output: 2 +Explanation: We can determine the poisonous bucket as follows: +At time 0, feed the first pig bucket 1, and feed the second pig bucket 2. +At time 15, there are 2 possible outcomes: +- If either pig dies, then the poisonous bucket is the one it was fed. +- If neither pig dies, then feed the first pig bucket 3, and feed the second pig bucket 4. +At time 30, one of the two pigs must die, and the poisonous bucket is the one it was fed. +``` + +  +**Constraints:** + + + +- `1 <= buckets <= 1000` + +- `1 <= minutesToDie <= minutesToTest <= 100` + + + +## Solution + +```javascript +/** + * @param {number} buckets + * @param {number} minutesToDie + * @param {number} minutesToTest + * @return {number} + */ +var poorPigs = function(buckets, minutesToDie, minutesToTest) { + return Math.ceil(Math.log2(buckets) / Math.log2(Math.floor(minutesToTest/minutesToDie) + 1)); +}; +``` + +**Explain:** + +We have `M` = `minutesToTest/minutesToDie` test runs. + +Every pig have `M + 1` possible situations, which is die in one of `M` test runs, or survive at last. + +If we got `k` pigs, we could have `(M + 1) ^ k` possibilities. + +If we have to detect one poison bucket in `N` buckets, we need equal more than `N` possibilities, which is `(M + 1) ^ k >= N`. + +Which is `k >= log(N) / log(M + 1)`. + +**Complexity:** + +* Time complexity : O(1). +* Space complexity : O(1). diff --git a/401-500/459. Repeated Substring Pattern.md b/401-500/459. Repeated Substring Pattern.md new file mode 100644 index 0000000..70ea5d3 --- /dev/null +++ b/401-500/459. Repeated Substring Pattern.md @@ -0,0 +1,65 @@ +# 459. Repeated Substring Pattern + +- Difficulty: Easy. +- Related Topics: String, String Matching. +- Similar Questions: Find the Index of the First Occurrence in a String, Repeated String Match. + +## Problem + +Given a string `s`, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. + +  +Example 1: + +``` +Input: s = "abab" +Output: true +Explanation: It is the substring "ab" twice. +``` + +Example 2: + +``` +Input: s = "aba" +Output: false +``` + +Example 3: + +``` +Input: s = "abcabcabcabc" +Output: true +Explanation: It is the substring "abc" four times or the substring "abcabc" twice. +``` + +  +**Constraints:** + + + +- `1 <= s.length <= 104` + +- `s` consists of lowercase English letters. + + + +## Solution + +```javascript +/** + * @param {string} s + * @return {boolean} + */ +var repeatedSubstringPattern = function(s) { + return `${s}${s}`.slice(1, s.length * 2 - 1).includes(s); +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). 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/401-500/486. Predict the Winner.md b/401-500/486. Predict the Winner.md new file mode 100644 index 0000000..ef565a7 --- /dev/null +++ b/401-500/486. Predict the Winner.md @@ -0,0 +1,74 @@ +# 486. Predict the Winner + +- Difficulty: Medium. +- Related Topics: Array, Math, Dynamic Programming, Recursion, Game Theory. +- Similar Questions: Can I Win. + +## Problem + +You are given an integer array `nums`. Two players are playing a game with this array: player 1 and player 2. + +Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of `0`. At each turn, the player takes one of the numbers from either end of the array (i.e., `nums[0]` or `nums[nums.length - 1]`) which reduces the size of the array by `1`. The player adds the chosen number to their score. The game ends when there are no more elements in the array. + +Return `true` if Player 1 can win the game. If the scores of both players are equal, then player 1 is still the winner, and you should also return `true`. You may assume that both players are playing optimally. + +  +Example 1: + +``` +Input: nums = [1,5,2] +Output: false +Explanation: Initially, player 1 can choose between 1 and 2. +If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2). +So, final score of player 1 is 1 + 2 = 3, and player 2 is 5. +Hence, player 1 will never be the winner and you need to return false. +``` + +Example 2: + +``` +Input: nums = [1,5,233,7] +Output: true +Explanation: Player 1 first chooses 1. Then player 2 has to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233. +Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win. +``` + +  +**Constraints:** + + + +- `1 <= nums.length <= 20` + +- `0 <= nums[i] <= 107` + + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @return {boolean} + */ +var PredictTheWinner = function(nums) { + return maxDiff(nums, 0, nums.length - 1) >= 0; +}; + +var maxDiff = function(nums, left, right) { + if (left === right) return nums[left]; + return Math.max( + nums[left] - maxDiff(nums, left + 1, right), + nums[right] - maxDiff(nums, left, right - 1), + ); +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n ^ 2). +* Space complexity : O(n ^ 2). diff --git a/401-500/496. Next Greater Element I.md b/401-500/496. Next Greater Element I.md new file mode 100644 index 0000000..ed7f44c --- /dev/null +++ b/401-500/496. Next Greater Element I.md @@ -0,0 +1,83 @@ +# 496. Next Greater Element I + +- Difficulty: Easy. +- Related Topics: Array, Hash Table, Stack, Monotonic Stack. +- Similar Questions: Next Greater Element II, Next Greater Element III, Daily Temperatures, Sum of Subarray Ranges, Sum of Total Strength of Wizards, Next Greater Element IV, Remove Nodes From Linked List. + +## Problem + +The **next greater element** of some element `x` in an array is the **first greater** element that is **to the right** of `x` in the same array. + +You are given two **distinct 0-indexed** integer arrays `nums1` and `nums2`, where `nums1` is a subset of `nums2`. + +For each `0 <= i < nums1.length`, find the index `j` such that `nums1[i] == nums2[j]` and determine the **next greater element** of `nums2[j]` in `nums2`. If there is no next greater element, then the answer for this query is `-1`. + +Return **an array **`ans`** of length **`nums1.length`** such that **`ans[i]`** is the **next greater element** as described above.** + +  +Example 1: + +``` +Input: nums1 = [4,1,2], nums2 = [1,3,4,2] +Output: [-1,3,-1] +Explanation: The next greater element for each value of nums1 is as follows: +- 4 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1. +- 1 is underlined in nums2 = [1,3,4,2]. The next greater element is 3. +- 2 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1. +``` + +Example 2: + +``` +Input: nums1 = [2,4], nums2 = [1,2,3,4] +Output: [3,-1] +Explanation: The next greater element for each value of nums1 is as follows: +- 2 is underlined in nums2 = [1,2,3,4]. The next greater element is 3. +- 4 is underlined in nums2 = [1,2,3,4]. There is no next greater element, so the answer is -1. +``` + +  +**Constraints:** + + + +- `1 <= nums1.length <= nums2.length <= 1000` + +- `0 <= nums1[i], nums2[i] <= 104` + +- All integers in `nums1` and `nums2` are **unique**. + +- All the integers of `nums1` also appear in `nums2`. + + +  +**Follow up:** Could you find an `O(nums1.length + nums2.length)` solution? + +## Solution + +```javascript +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number[]} + */ +var nextGreaterElement = function(nums1, nums2) { + var map = {}; + var stack = []; + for (var i = nums2.length - 1; i >= 0; i--) { + while (stack.length && stack[stack.length - 1] <= nums2[i]) stack.pop(); + map[nums2[i]] = stack.length ? stack[stack.length - 1] : -1; + stack.push(nums2[i]); + } + return nums1.map(num => map[num]); +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/501-600/501. Find Mode in Binary Search Tree.md b/501-600/501. Find Mode in Binary Search Tree.md new file mode 100644 index 0000000..6147f77 --- /dev/null +++ b/501-600/501. Find Mode in Binary Search Tree.md @@ -0,0 +1,111 @@ +# 501. Find Mode in Binary Search Tree + +- Difficulty: Easy. +- Related Topics: Tree, Depth-First Search, Binary Search Tree, Binary Tree. +- Similar Questions: Validate Binary Search Tree. + +## Problem + +Given the `root` of a binary search tree (BST) with duplicates, return **all the mode(s) (i.e., the most frequently occurred element) in it**. + +If the tree has more than one mode, return them in **any order**. + +Assume a BST is defined as follows: + + + +- The left subtree of a node contains only nodes with keys **less than or equal to** the node's key. + +- The right subtree of a node contains only nodes with keys **greater than or equal to** the node's key. + +- Both the left and right subtrees must also be binary search trees. + + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2021/03/11/mode-tree.jpg) + +``` +Input: root = [1,null,2,2] +Output: [2] +``` + +Example 2: + +``` +Input: root = [0] +Output: [0] +``` + +  +**Constraints:** + + + +- The number of nodes in the tree is in the range `[1, 104]`. + +- `-105 <= Node.val <= 105` + + +  +**Follow up:** Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count). + +## 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 findMode = function(root) { + var max = 0; + var res = []; + var num = 0.1; + var count = 0; + var update = () => { + if (count === max) { + res.push(num); + } else if (count > max) { + max = count; + res = [num]; + } + }; + preOrder(root, node => { + if (node.val === num) { + count += 1; + } else { + update(); + num = node.val; + count = 1; + } + }); + update(); + return res; +}; + +var preOrder = function(root, visit) { + root.left && preOrder(root.left, visit); + visit(root); + root.right && preOrder(root.right, visit); +}; +``` + +**Explain:** + +Pre-order traversal visiting can visit binary search tree's nodes value by ascending order. + +Imaging you have an ordered array, find the most consecutive number(s). + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/501-600/503. Next Greater Element II.md b/501-600/503. Next Greater Element II.md new file mode 100644 index 0000000..4209668 --- /dev/null +++ b/501-600/503. Next Greater Element II.md @@ -0,0 +1,69 @@ +# 503. Next Greater Element II + +- Difficulty: Medium. +- Related Topics: Array, Stack, Monotonic Stack. +- Similar Questions: Next Greater Element I, Next Greater Element III. + +## Problem + +Given a circular integer array `nums` (i.e., the next element of `nums[nums.length - 1]` is `nums[0]`), return **the **next greater number** for every element in** `nums`. + +The **next greater number** of a number `x` is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, return `-1` for this number. + +  +Example 1: + +``` +Input: nums = [1,2,1] +Output: [2,-1,2] +Explanation: The first 1's next greater number is 2; +The number 2 can't find next greater number. +The second 1's next greater number needs to search circularly, which is also 2. +``` + +Example 2: + +``` +Input: nums = [1,2,3,4,3] +Output: [2,3,4,-1,4] +``` + +  +**Constraints:** + + + +- `1 <= nums.length <= 104` + +- `-109 <= nums[i] <= 109` + + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @return {number[]} + */ +var nextGreaterElements = function(nums) { + var map = Array(nums.length); + var stack = []; + for (var i = nums.length * 2 - 1; i >= 0; i--) { + var index = i % nums.length; + while (stack.length && stack[stack.length - 1] <= nums[index]) stack.pop(); + map[index] = stack.length ? stack[stack.length - 1] : -1; + stack.push(nums[index]); + } + return map; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). 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/515. Find Largest Value in Each Tree Row.md b/501-600/515. Find Largest Value in Each Tree Row.md new file mode 100644 index 0000000..d847d23 --- /dev/null +++ b/501-600/515. Find Largest Value in Each Tree Row.md @@ -0,0 +1,78 @@ +# 515. Find Largest Value in Each Tree Row + +- Difficulty: Medium. +- Related Topics: Tree, Depth-First Search, Breadth-First Search, Binary Tree. +- Similar Questions: . + +## Problem + +Given the `root` of a binary tree, return **an array of the largest value in each row** of the tree **(0-indexed)**. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2020/08/21/largest_e1.jpg) + +``` +Input: root = [1,3,2,5,3,null,9] +Output: [1,3,9] +``` + +Example 2: + +``` +Input: root = [1,2,3] +Output: [1,3] +``` + +  +**Constraints:** + + + +- The number of nodes in the tree will be in the range `[0, 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 largestValues = function(root) { + var res = []; + dfs(root, 0, res); + return res; +}; + +var dfs = function(root, row, res) { + if (!root) return; + res[row] = Math.max( + res[row] === undefined ? Number.MIN_SAFE_INTEGER : res[row], + root.val, + ); + dfs(root.left, row + 1, res); + dfs(root.right, row + 1, res); +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). 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/542. 01 Matrix.md b/501-600/542. 01 Matrix.md new file mode 100644 index 0000000..d72e85f --- /dev/null +++ b/501-600/542. 01 Matrix.md @@ -0,0 +1,92 @@ +# 542. 01 Matrix + +- Difficulty: Medium. +- Related Topics: Array, Dynamic Programming, Breadth-First Search, Matrix. +- Similar Questions: Shortest Path to Get Food, Minimum Operations to Remove Adjacent Ones in Matrix, Difference Between Ones and Zeros in Row and Column. + +## Problem + +Given an `m x n` binary matrix `mat`, return **the distance of the nearest **`0`** for each cell**. + +The distance between two adjacent cells is `1`. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2021/04/24/01-1-grid.jpg) + +``` +Input: mat = [[0,0,0],[0,1,0],[0,0,0]] +Output: [[0,0,0],[0,1,0],[0,0,0]] +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2021/04/24/01-2-grid.jpg) + +``` +Input: mat = [[0,0,0],[0,1,0],[1,1,1]] +Output: [[0,0,0],[0,1,0],[1,2,1]] +``` + +  +**Constraints:** + + + +- `m == mat.length` + +- `n == mat[i].length` + +- `1 <= m, n <= 104` + +- `1 <= m * n <= 104` + +- `mat[i][j]` is either `0` or `1`. + +- There is at least one `0` in `mat`. + + + +## Solution + +```javascript +/** + * @param {number[][]} mat + * @return {number[][]} + */ +var updateMatrix = function(mat) { + var arr = []; + var m = mat.length; + var n = mat[0].length; + var res = Array(m).fill(0).map(() => Array(n)); + var mark = function(i, j, distance) { + if (mat[i] === undefined || mat[i][j] === undefined) return; + if (res[i][j] !== undefined) return; + arr.push([i, j]); + res[i][j] = distance; + }; + for (var i = 0; i < m; i++) { + for (var j = 0; j < n; j++) { + mat[i][j] === 0 && mark(i, j, 0); + } + } + while (arr.length) { + var [i, j] = arr.shift(); + mark(i - 1, j, res[i][j] + 1); + mark(i + 1, j, res[i][j] + 1); + mark(i, j - 1, res[i][j] + 1); + mark(i, j + 1, res[i][j] + 1); + } + return res; +}; +``` + +**Explain:** + +Breadth-first search. + +**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/556. Next Greater Element III.md b/501-600/556. Next Greater Element III.md new file mode 100644 index 0000000..5e75cc3 --- /dev/null +++ b/501-600/556. Next Greater Element III.md @@ -0,0 +1,66 @@ +# 556. Next Greater Element III + +- Difficulty: Medium. +- Related Topics: Math, Two Pointers, String. +- Similar Questions: Next Greater Element I, Next Greater Element II, Next Palindrome Using Same Digits. + +## Problem + +Given a positive integer `n`, find **the smallest integer which has exactly the same digits existing in the integer** `n` **and is greater in value than** `n`. If no such positive integer exists, return `-1`. + +**Note** that the returned integer should fit in **32-bit integer**, if there is a valid answer but it does not fit in **32-bit integer**, return `-1`. + +  +Example 1: +``` +Input: n = 12 +Output: 21 +```Example 2: +``` +Input: n = 21 +Output: -1 +``` +  +**Constraints:** + + + +- `1 <= n <= 231 - 1` + + + +## Solution + +```javascript +/** + * @param {number} n + * @return {number} + */ +var nextGreaterElement = function(n) { + var nums = n.toString().split(''); + var i = nums.length - 1; + while (i > 0 && nums[i] <= nums[i - 1]) i--; + if (i === 0) return -1; + var j = i; + while (j <= nums.length - 1 && nums[j] > nums[i - 1]) j++; + swap(nums, i - 1, j - 1); + var newNums = nums.slice(0, i).concat(nums.slice(i).reverse()); + var newNum = Number(newNums.join('')); + return newNum > Math.pow(2, 31) - 1 ? -1 : newNum; +}; + +var swap = function(nums, i, j) { + var tmp = nums[i]; + nums[i] = nums[j]; + nums[j] = tmp; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). 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/646. Maximum Length of Pair Chain.md b/601-700/646. Maximum Length of Pair Chain.md new file mode 100644 index 0000000..4910de3 --- /dev/null +++ b/601-700/646. Maximum Length of Pair Chain.md @@ -0,0 +1,106 @@ +# 646. Maximum Length of Pair Chain + +- Difficulty: Medium. +- Related Topics: Array, Dynamic Programming, Greedy, Sorting. +- Similar Questions: Longest Increasing Subsequence, Non-decreasing Subsequences, Longest Non-decreasing Subarray From Two Arrays. + +## Problem + +You are given an array of `n` pairs `pairs` where `pairs[i] = [lefti, righti]` and `lefti < righti`. + +A pair `p2 = [c, d]` **follows** a pair `p1 = [a, b]` if `b < c`. A **chain** of pairs can be formed in this fashion. + +Return **the length longest chain which can be formed**. + +You do not need to use up all the given intervals. You can select pairs in any order. + +  +Example 1: + +``` +Input: pairs = [[1,2],[2,3],[3,4]] +Output: 2 +Explanation: The longest chain is [1,2] -> [3,4]. +``` + +Example 2: + +``` +Input: pairs = [[1,2],[7,8],[4,5]] +Output: 3 +Explanation: The longest chain is [1,2] -> [4,5] -> [7,8]. +``` + +  +**Constraints:** + + + +- `n == pairs.length` + +- `1 <= n <= 1000` + +- `-1000 <= lefti < righti <= 1000` + + + +## Solution + +```javascript +/** + * @param {number[][]} pairs + * @return {number} + */ +var findLongestChain = function(pairs) { + pairs.sort((a, b) => a[0] - b[0]); + var dp = Array(pairs.length); + for (var i = pairs.length - 1; i >= 0; i--) { + var j = i + 1; + while (j < pairs.length && pairs[j][0] <= pairs[i][1]) j++; + dp[i] = Math.max( + dp[i + 1] || 0, + 1 + (dp[j] || 0), + ); + } + return dp[0]; +}; +``` + +**Explain:** + +Dynamic programming. + +**Complexity:** + +* Time complexity : O(n ^ 2). +* Space complexity : O(n). + +## Solution 2 + +```javascript +/** + * @param {number[][]} pairs + * @return {number} + */ +var findLongestChain = function(pairs) { + pairs.sort((a, b) => a[1] - b[1]); + var res = 1; + var i = 0; + for (var j = 0; j < pairs.length; j++) { + if (pairs[j][0] > pairs[i][1]) { + i = j; + res++; + } + } + return res; +}; +``` + +**Explain:** + +Greedy. + +**Complexity:** + +* Time complexity : O(n * log(n)). +* Space complexity : O(1). diff --git a/601-700/649. Dota2 Senate.md b/601-700/649. Dota2 Senate.md new file mode 100644 index 0000000..6fdf88a --- /dev/null +++ b/601-700/649. Dota2 Senate.md @@ -0,0 +1,104 @@ +# 649. Dota2 Senate + +- Difficulty: Medium. +- Related Topics: String, Greedy, Queue. +- Similar Questions: Teemo Attacking. + +## Problem + +In the world of Dota2, there are two parties: the Radiant and the Dire. + +The Dota2 senate consists of senators coming from two parties. Now the Senate wants to decide on a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise **one** of the two rights: + + + +- **Ban one senator's right:** A senator can make another senator lose all his rights in this and all the following rounds. + +- **Announce the victory:** If this senator found the senators who still have rights to vote are all from the same party, he can announce the victory and decide on the change in the game. + + +Given a string `senate` representing each senator's party belonging. The character `'R'` and `'D'` represent the Radiant party and the Dire party. Then if there are `n` senators, the size of the given string will be `n`. + +The round-based procedure starts from the first senator to the last senator in the given order. This procedure will last until the end of voting. All the senators who have lost their rights will be skipped during the procedure. + +Suppose every senator is smart enough and will play the best strategy for his own party. Predict which party will finally announce the victory and change the Dota2 game. The output should be `"Radiant"` or `"Dire"`. + +  +Example 1: + +``` +Input: senate = "RD" +Output: "Radiant" +Explanation: +The first senator comes from Radiant and he can just ban the next senator's right in round 1. +And the second senator can't exercise any rights anymore since his right has been banned. +And in round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote. +``` + +Example 2: + +``` +Input: senate = "RDD" +Output: "Dire" +Explanation: +The first senator comes from Radiant and he can just ban the next senator's right in round 1. +And the second senator can't exercise any rights anymore since his right has been banned. +And the third senator comes from Dire and he can ban the first senator's right in round 1. +And in round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote. +``` + +  +**Constraints:** + + + +- `n == senate.length` + +- `1 <= n <= 104` + +- `senate[i]` is either `'R'` or `'D'`. + + + +## Solution + +```javascript +/** + * @param {string} senate + * @return {string} + */ +var predictPartyVictory = function(senate) { + var s1 = []; + var s2 = []; + for (var i = 0; i < senate.length; i++) { + if (senate[i] === 'R') { + s1.push(i); + } else { + s2.push(i); + } + } + while (s1.length && s2.length) { + if (s1[0] < s2[0]) { + s1.push(s1.shift() + senate.length); + s2.shift(); + } else { + s2.push(s2.shift() + senate.length); + s1.shift(); + } + } + return s1.length ? 'Radiant' : 'Dire'; +}; +``` + +**Explain:** + +Since only one member of the current party can be selected, the member who can vote at the earliest should be selected. + +So we use two stack to store the vote members, when one member vote, pick another member from other side party to remove, and let current member vote in next round. + +The stack[i] means the member's vote order index, while the member who has least index will vote next. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/601-700/654. Maximum Binary Tree.md b/601-700/654. Maximum Binary Tree.md new file mode 100644 index 0000000..606731a --- /dev/null +++ b/601-700/654. Maximum Binary Tree.md @@ -0,0 +1,105 @@ +# 654. Maximum Binary Tree + +- Difficulty: Medium. +- Related Topics: Array, Divide and Conquer, Stack, Tree, Monotonic Stack, Binary Tree. +- Similar Questions: Maximum Binary Tree II. + +## Problem + +You are given an integer array `nums` with no duplicates. A **maximum binary tree** can be built recursively from `nums` using the following algorithm: + + + +- Create a root node whose value is the maximum value in `nums`. + +- Recursively build the left subtree on the **subarray prefix** to the **left** of the maximum value. + +- Recursively build the right subtree on the **subarray suffix** to the **right** of the maximum value. + + +Return **the **maximum binary tree** built from **`nums`. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2020/12/24/tree1.jpg) + +``` +Input: nums = [3,2,1,6,0,5] +Output: [6,3,5,null,2,0,null,null,1] +Explanation: The recursive calls are as follow: +- The largest value in [3,2,1,6,0,5] is 6. Left prefix is [3,2,1] and right suffix is [0,5]. + - The largest value in [3,2,1] is 3. Left prefix is [] and right suffix is [2,1]. + - Empty array, so no child. + - The largest value in [2,1] is 2. Left prefix is [] and right suffix is [1]. + - Empty array, so no child. + - Only one element, so child is a node with value 1. + - The largest value in [0,5] is 5. Left prefix is [0] and right suffix is []. + - Only one element, so child is a node with value 0. + - Empty array, so no child. +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2020/12/24/tree2.jpg) + +``` +Input: nums = [3,2,1] +Output: [3,null,2,null,1] +``` + +  +**Constraints:** + + + +- `1 <= nums.length <= 1000` + +- `0 <= nums[i] <= 1000` + +- All integers in `nums` 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 {number[]} nums + * @return {TreeNode} + */ +var constructMaximumBinaryTree = function(nums) { + return solve(nums, 0, nums.length - 1); +}; + +var solve = function(nums, left, right) { + var maxI = left; + for (var i = left + 1; i <= right; i++) { + if (nums[i] > nums[maxI]) { + maxI = i; + } + } + return new TreeNode( + nums[maxI], + maxI > left ? solve(nums, left, maxI - 1) : null, + maxI < right ? solve(nums, maxI + 1, right) : null, + ); +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n ^ 2). +* Space complexity : O(n). 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/601-700/688. Knight Probability in Chessboard.md b/601-700/688. Knight Probability in Chessboard.md new file mode 100644 index 0000000..5136262 --- /dev/null +++ b/601-700/688. Knight Probability in Chessboard.md @@ -0,0 +1,161 @@ +# 688. Knight Probability in Chessboard + +- Difficulty: Medium. +- Related Topics: Dynamic Programming. +- Similar Questions: Out of Boundary Paths. + +## Problem + +On an `n x n` chessboard, a knight starts at the cell `(row, column)` and attempts to make exactly `k` moves. The rows and columns are **0-indexed**, so the top-left cell is `(0, 0)`, and the bottom-right cell is `(n - 1, n - 1)`. + +A chess knight has eight possible moves it can make, as illustrated below. Each move is two cells in a cardinal direction, then one cell in an orthogonal direction. + +![](https://assets.leetcode.com/uploads/2018/10/12/knight.png) + +Each time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there. + +The knight continues moving until it has made exactly `k` moves or has moved off the chessboard. + +Return **the probability that the knight remains on the board after it has stopped moving**. + +  +Example 1: + +``` +Input: n = 3, k = 2, row = 0, column = 0 +Output: 0.06250 +Explanation: There are two moves (to (1,2), (2,1)) that will keep the knight on the board. +From each of those positions, there are also two moves that will keep the knight on the board. +The total probability the knight stays on the board is 0.0625. +``` + +Example 2: + +``` +Input: n = 1, k = 0, row = 0, column = 0 +Output: 1.00000 +``` + +  +**Constraints:** + + + +- `1 <= n <= 25` + +- `0 <= k <= 100` + +- `0 <= row, column <= n - 1` + + + +## Solution + +```javascript +/** + * @param {number} n + * @param {number} k + * @param {number} row + * @param {number} column + * @return {number} + */ +var knightProbability = function(n, k, row, column) { + var dp = Array(n).fill(0).map(() => Array(n).fill(0).map(() => Array(k + 1))); + for (var m = 0; m <= k; m++) { + for (var i = 0; i < n; i++) { + for (var j = 0; j < n; j++) { + solve(n, m, i, j, dp); + } + } + } + return dp[row][column][k]; +}; + +var directions = [ + [-1, -2], + [-2, -1], + [-2, 1], + [-1, 2], + [1, 2], + [2, 1], + [2, -1], + [1, -2] +]; + +var solve = function(n, k, row, column, dp) { + if (k === 0) { + dp[row][column][k] = 1; + return; + } + dp[row][column][k] = 0; + for (var i = 0; i < directions.length; i++) { + var x = row + directions[i][0]; + var y = column + directions[i][1]; + if (x < 0 || x >= n || y < 0 || y >= n) continue; + dp[row][column][k] += dp[x][y][k - 1] * 0.125; + } +}; +``` + +**Explain:** + +Bottom-up Dynamic Programming. + +**Complexity:** + +* Time complexity : O(k * n^2). +* Space complexity : O(k * n^2). + +## Solution 2 + +```javascript +/** + * @param {number} n + * @param {number} k + * @param {number} row + * @param {number} column + * @return {number} + */ +var knightProbability = function(n, k, row, column) { + var lastDp = Array(n).fill(0).map(() => Array(n).fill(1)); + for (var m = 1; m <= k; m++) { + var newDp = Array(n).fill(0).map(() => Array(n).fill(0)) + for (var i = 0; i < n; i++) { + for (var j = 0; j < n; j++) { + solve(n, i, j, lastDp, newDp); + } + } + lastDp = newDp; + } + return lastDp[row][column]; +}; + +var directions = [ + [-1, -2], + [-2, -1], + [-2, 1], + [-1, 2], + [1, 2], + [2, 1], + [2, -1], + [1, -2] +]; + +var solve = function(n, row, column, lastDp, newDp) { + for (var i = 0; i < directions.length; i++) { + var x = row + directions[i][0]; + var y = column + directions[i][1]; + if (x < 0 || x >= n || y < 0 || y >= n) continue; + newDp[row][column] += lastDp[x][y] * 0.125; + } +}; +``` + +**Explain:** + +Bottom-up Dynamic Programming with Optimized Space Complexity. + +**Complexity:** + +* Time complexity : O(k * n^2). +* Space complexity : O(n^2). diff --git a/601-700/697. Degree of an Array.md b/601-700/697. Degree of an Array.md new file mode 100644 index 0000000..015bbe4 --- /dev/null +++ b/601-700/697. Degree of an Array.md @@ -0,0 +1,87 @@ +# 697. Degree of an Array + +- Difficulty: Easy. +- Related Topics: Array, Hash Table. +- Similar Questions: Maximum Subarray. + +## Problem + +Given a non-empty array of non-negative integers `nums`, the **degree** of this array is defined as the maximum frequency of any one of its elements. + +Your task is to find the smallest possible length of a (contiguous) subarray of `nums`, that has the same degree as `nums`. + +  +Example 1: + +``` +Input: nums = [1,2,2,3,1] +Output: 2 +Explanation: +The input array has a degree of 2 because both elements 1 and 2 appear twice. +Of the subarrays that have the same degree: +[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2] +The shortest length is 2. So return 2. +``` + +Example 2: + +``` +Input: nums = [1,2,2,3,1,4,2] +Output: 6 +Explanation: +The degree is 3 because the element 2 is repeated 3 times. +So [2,2,3,1,4,2] is the shortest subarray, therefore returning 6. +``` + +  +**Constraints:** + + + +- `nums.length` will be between 1 and 50,000. + +- `nums[i]` will be an integer between 0 and 49,999. + + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @return {number} + */ +var findShortestSubArray = function(nums) { + var map = {}; + var degree = 0; + for (var i = 0; i < nums.length; i++) { + if (!map[nums[i]]) { + map[nums[i]] = { + left: i, + right: i, + num: 1, + }; + } else { + map[nums[i]].right = i; + map[nums[i]].num += 1; + } + degree = Math.max(degree, map[nums[i]].num); + } + var min = Number.MAX_SAFE_INTEGER; + for (var i = 0; i < nums.length; i++) { + if (map[nums[i]].num === degree) { + min = Math.min(map[nums[i]].right - map[nums[i]].left + 1, min); + } + } + return min; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/701-800/704. Binary Search.md b/701-800/704. Binary Search.md new file mode 100644 index 0000000..be868f9 --- /dev/null +++ b/701-800/704. Binary Search.md @@ -0,0 +1,77 @@ +# 704. Binary Search + +- Difficulty: Easy. +- Related Topics: Array, Binary Search. +- Similar Questions: Search in a Sorted Array of Unknown Size, Maximum Count of Positive Integer and Negative Integer. + +## Problem + +Given an array of integers `nums` which is sorted in ascending order, and an integer `target`, write a function to search `target` in `nums`. If `target` exists, then return its index. Otherwise, return `-1`. + +You must write an algorithm with `O(log n)` runtime complexity. + +  +Example 1: + +``` +Input: nums = [-1,0,3,5,9,12], target = 9 +Output: 4 +Explanation: 9 exists in nums and its index is 4 +``` + +Example 2: + +``` +Input: nums = [-1,0,3,5,9,12], target = 2 +Output: -1 +Explanation: 2 does not exist in nums so return -1 +``` + +  +**Constraints:** + + + +- `1 <= nums.length <= 104` + +- `-104 < nums[i], target < 104` + +- All the integers in `nums` are **unique**. + +- `nums` is sorted in ascending order. + + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +var search = function(nums, target) { + var left = 0; + var right = nums.length - 1; + while (left <= right) { + var mid = left + Math.floor((right - left) / 2); + if (nums[mid] === target) { + return mid; + } else if (nums[mid] > target) { + right = mid - 1; + } else { + left = mid + 1; + } + } + return -1; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(log(n)). +* Space complexity : O(1). diff --git a/701-800/706. Design HashMap.md b/701-800/706. Design HashMap.md new file mode 100644 index 0000000..22beb6b --- /dev/null +++ b/701-800/706. Design HashMap.md @@ -0,0 +1,106 @@ +# 706. Design HashMap + +- Difficulty: Easy. +- Related Topics: Array, Hash Table, Linked List, Design, Hash Function. +- Similar Questions: Design HashSet, Design Skiplist. + +## Problem + +Design a HashMap without using any built-in hash table libraries. + +Implement the `MyHashMap` class: + + + +- `MyHashMap()` initializes the object with an empty map. + +- `void put(int key, int value)` inserts a `(key, value)` pair into the HashMap. If the `key` already exists in the map, update the corresponding `value`. + +- `int get(int key)` returns the `value` to which the specified `key` is mapped, or `-1` if this map contains no mapping for the `key`. + +- `void remove(key)` removes the `key` and its corresponding `value` if the map contains the mapping for the `key`. + + +  +Example 1: + +``` +Input +["MyHashMap", "put", "put", "get", "get", "put", "get", "remove", "get"] +[[], [1, 1], [2, 2], [1], [3], [2, 1], [2], [2], [2]] +Output +[null, null, null, 1, -1, null, 1, null, -1] + +Explanation +MyHashMap myHashMap = new MyHashMap(); +myHashMap.put(1, 1); // The map is now [[1,1]] +myHashMap.put(2, 2); // The map is now [[1,1], [2,2]] +myHashMap.get(1); // return 1, The map is now [[1,1], [2,2]] +myHashMap.get(3); // return -1 (i.e., not found), The map is now [[1,1], [2,2]] +myHashMap.put(2, 1); // The map is now [[1,1], [2,1]] (i.e., update the existing value) +myHashMap.get(2); // return 1, The map is now [[1,1], [2,1]] +myHashMap.remove(2); // remove the mapping for 2, The map is now [[1,1]] +myHashMap.get(2); // return -1 (i.e., not found), The map is now [[1,1]] +``` + +  +**Constraints:** + + + +- `0 <= key, value <= 106` + +- At most `104` calls will be made to `put`, `get`, and `remove`. + + + +## Solution + +```javascript + +var MyHashMap = function() { + this.map = []; +}; + +/** + * @param {number} key + * @param {number} value + * @return {void} + */ +MyHashMap.prototype.put = function(key, value) { + this.map[key] = value; +}; + +/** + * @param {number} key + * @return {number} + */ +MyHashMap.prototype.get = function(key) { + return this.map[key] ?? -1; +}; + +/** + * @param {number} key + * @return {void} + */ +MyHashMap.prototype.remove = function(key) { + this.map[key] = undefined; +}; + +/** + * Your MyHashMap object will be instantiated and called as such: + * var obj = new MyHashMap() + * obj.put(key,value) + * var param_2 = obj.get(key) + * obj.remove(key) + */ +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(1). +* Space complexity : O(1). diff --git a/701-800/712. Minimum ASCII Delete Sum for Two Strings.md b/701-800/712. Minimum ASCII Delete Sum for Two Strings.md new file mode 100644 index 0000000..f084346 --- /dev/null +++ b/701-800/712. Minimum ASCII Delete Sum for Two Strings.md @@ -0,0 +1,84 @@ +# 712. Minimum ASCII Delete Sum for Two Strings + +- Difficulty: Medium. +- Related Topics: String, Dynamic Programming. +- Similar Questions: Edit Distance, Longest Increasing Subsequence, Delete Operation for Two Strings. + +## Problem + +Given two strings ```s1``` and ```s2```, return **the lowest **ASCII** sum of deleted characters to make two strings equal**. + +  +Example 1: + +``` +Input: s1 = "sea", s2 = "eat" +Output: 231 +Explanation: Deleting "s" from "sea" adds the ASCII value of "s" (115) to the sum. +Deleting "t" from "eat" adds 116 to the sum. +At the end, both strings are equal, and 115 + 116 = 231 is the minimum sum possible to achieve this. +``` + +Example 2: + +``` +Input: s1 = "delete", s2 = "leet" +Output: 403 +Explanation: Deleting "dee" from "delete" to turn the string into "let", +adds 100[d] + 101[e] + 101[e] to the sum. +Deleting "e" from "leet" adds 101[e] to the sum. +At the end, both strings are equal to "let", and the answer is 100+101+101+101 = 403. +If instead we turned both strings into "lee" or "eet", we would get answers of 433 or 417, which are higher. +``` + +  +**Constraints:** + + + +- ```1 <= s1.length, s2.length <= 1000``` + +- ```s1``` and ```s2``` consist of lowercase English letters. + + + +## Solution + +```javascript +/** + * @param {string} s1 + * @param {string} s2 + * @return {number} + */ +var minimumDeleteSum = function(s1, s2) { + var map = {}; + var dfs = function(i, j) { + var key = i + ',' + j; + if (map[key]) return map[key]; + if (!s1[i] && !s2[j]) return 0; + if (!s1[i]) return map[key] = s2.slice(j).split('').reduce((sum, s) => sum + s.charCodeAt(0), 0); + if (!s2[j]) return map[key] = s1.slice(i).split('').reduce((sum, s) => sum + s.charCodeAt(0), 0); + if (s1[i] === s2[j]) return map[key] = dfs(i + 1, j + 1); + return map[key] = Math.min( + dfs(i + 1, j) + s1.charCodeAt(i), + dfs(i, j + 1) + s2.charCodeAt(j), + ); + }; + return dfs(0, 0); +}; +``` + +**Explain:** + +For every [i, j] in [s1, s2], you could delete a char from s1[i] or s2[j], that end up with two possible ways. + + +Top down to search and summarize, use map to memorize the result of every path we tried. + + +We could also go bottom up, that's the reverse version of it, try it yourself! + +**Complexity:** + +* Time complexity : O(m * n). +* Space complexity : O(m * n). diff --git a/701-800/714. Best Time to Buy and Sell Stock with Transaction Fee.md b/701-800/714. Best Time to Buy and Sell Stock with Transaction Fee.md new file mode 100644 index 0000000..883a06c --- /dev/null +++ b/701-800/714. Best Time to Buy and Sell Stock with Transaction Fee.md @@ -0,0 +1,84 @@ +# 714. Best Time to Buy and Sell Stock with Transaction Fee + +- Difficulty: Medium. +- Related Topics: Array, Dynamic Programming, Greedy. +- Similar Questions: Best Time to Buy and Sell Stock II. + +## Problem + +You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day, and an integer `fee` representing a transaction fee. + +Find the maximum profit you can achieve. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction. + +**Note:** + + + +- You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). + +- The transaction fee is only charged once for each stock purchase and sale. + + +  +Example 1: + +``` +Input: prices = [1,3,2,8,4,9], fee = 2 +Output: 8 +Explanation: The maximum profit can be achieved by: +- Buying at prices[0] = 1 +- Selling at prices[3] = 8 +- Buying at prices[4] = 4 +- Selling at prices[5] = 9 +The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8. +``` + +Example 2: + +``` +Input: prices = [1,3,7,5,10,3], fee = 3 +Output: 6 +``` + +  +**Constraints:** + + + +- `1 <= prices.length <= 5 * 104` + +- `1 <= prices[i] < 5 * 104` + +- `0 <= fee < 5 * 104` + + + +## Solution + +```javascript +/** + * @param {number[]} prices + * @param {number} fee + * @return {number} + */ +var maxProfit = function(prices, fee) { + var hasStock = Number.MIN_SAFE_INTEGER; + var hasNoStock = 0; + for (var i = 0; i < prices.length; i++) { + var a = Math.max(hasStock, hasNoStock - prices[i]); + var b = Math.max(hasNoStock, hasStock + prices[i] - fee); + hasStock = a; + hasNoStock = b; + } + return Math.max(hasStock, hasNoStock); +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). 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/735. Asteroid Collision.md b/701-800/735. Asteroid Collision.md new file mode 100644 index 0000000..c348db2 --- /dev/null +++ b/701-800/735. Asteroid Collision.md @@ -0,0 +1,89 @@ +# 735. Asteroid Collision + +- Difficulty: Medium. +- Related Topics: Array, Stack, Simulation. +- Similar Questions: Can Place Flowers, Destroying Asteroids, Count Collisions on a Road, Robot Collisions. + +## Problem + +We are given an array `asteroids` of integers representing asteroids in a row. + +For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed. + +Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet. + +  +Example 1: + +``` +Input: asteroids = [5,10,-5] +Output: [5,10] +Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide. +``` + +Example 2: + +``` +Input: asteroids = [8,-8] +Output: [] +Explanation: The 8 and -8 collide exploding each other. +``` + +Example 3: + +``` +Input: asteroids = [10,2,-5] +Output: [10] +Explanation: The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10. +``` + +  +**Constraints:** + + + +- `2 <= asteroids.length <= 104` + +- `-1000 <= asteroids[i] <= 1000` + +- `asteroids[i] != 0` + + + +## Solution + +```javascript +/** + * @param {number[]} asteroids + * @return {number[]} + */ +var asteroidCollision = function(asteroids) { + var left = []; + var right = []; + for (var i = 0; i < asteroids.length; i++) { + if (asteroids[i] > 0) { + right.push(asteroids[i]); + } else { + while (true) { + if (!right.length) { + left.push(asteroids[i]); + break; + } + const num = right[right.length - 1] || 0; + if (num <= -asteroids[i]) right.pop(); + if (num >= -asteroids[i]) break; + } + } + } + return left.concat(right); +}; +``` + +**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/746. Min Cost Climbing Stairs.md b/701-800/746. Min Cost Climbing Stairs.md new file mode 100644 index 0000000..2a80e5d --- /dev/null +++ b/701-800/746. Min Cost Climbing Stairs.md @@ -0,0 +1,81 @@ +# 746. Min Cost Climbing Stairs + +- Difficulty: Easy. +- Related Topics: Array, Dynamic Programming. +- Similar Questions: Climbing Stairs. + +## Problem + +You are given an integer array `cost` where `cost[i]` is the cost of `ith` step on a staircase. Once you pay the cost, you can either climb one or two steps. + +You can either start from the step with index `0`, or the step with index `1`. + +Return **the minimum cost to reach the top of the floor**. + +  +Example 1: + +``` +Input: cost = [10,15,20] +Output: 15 +Explanation: You will start at index 1. +- Pay 15 and climb two steps to reach the top. +The total cost is 15. +``` + +Example 2: + +``` +Input: cost = [1,100,1,1,1,100,1,1,100,1] +Output: 6 +Explanation: You will start at index 0. +- Pay 1 and climb two steps to reach index 2. +- Pay 1 and climb two steps to reach index 4. +- Pay 1 and climb two steps to reach index 6. +- Pay 1 and climb one step to reach index 7. +- Pay 1 and climb two steps to reach index 9. +- Pay 1 and climb one step to reach the top. +The total cost is 6. +``` + +  +**Constraints:** + + + +- `2 <= cost.length <= 1000` + +- `0 <= cost[i] <= 999` + + + +## Solution + +```javascript +/** + * @param {number[]} cost + * @return {number} + */ +var minCostClimbingStairs = function(cost) { + var prevOne = 0; + var prevTwo = 0; + for (var i = 0; i <= cost.length; i++) { + var min = Math.min( + prevOne + (cost[i - 1] || 0), + prevTwo + (cost[i - 2] || 0), + ); + prevTwo = prevOne; + prevOne = min; + } + return prevOne; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). 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/779. K-th Symbol in Grammar.md b/701-800/779. K-th Symbol in Grammar.md new file mode 100644 index 0000000..c564c5e --- /dev/null +++ b/701-800/779. K-th Symbol in Grammar.md @@ -0,0 +1,86 @@ +# 779. K-th Symbol in Grammar + +- Difficulty: Medium. +- Related Topics: Math, Bit Manipulation, Recursion. +- Similar Questions: . + +## Problem + +We build a table of `n` rows (**1-indexed**). We start by writing `0` in the `1st` row. Now in every subsequent row, we look at the previous row and replace each occurrence of `0` with `01`, and each occurrence of `1` with `10`. + + + +- For example, for `n = 3`, the `1st` row is `0`, the `2nd` row is `01`, and the `3rd` row is `0110`. + + +Given two integer `n` and `k`, return the `kth` (**1-indexed**) symbol in the `nth` row of a table of `n` rows. + +  +Example 1: + +``` +Input: n = 1, k = 1 +Output: 0 +Explanation: row 1: 0 +``` + +Example 2: + +``` +Input: n = 2, k = 1 +Output: 0 +Explanation: +row 1: 0 +row 2: 01 +``` + +Example 3: + +``` +Input: n = 2, k = 2 +Output: 1 +Explanation: +row 1: 0 +row 2: 01 +``` + +  +**Constraints:** + + + +- `1 <= n <= 30` + +- `1 <= k <= 2n - 1` + + + +## Solution + +```javascript +/** + * @param {number} n + * @param {number} k + * @return {number} + */ +var kthGrammar = function(n, k) { + var op = 0; + while (n > 1) { + n--; + if (k % 2 === 0) { + op = op === 0 ? 1 : 0; + } + k = Math.ceil(k / 2); + } + return op; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). 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/701-800/799. Champagne Tower.md b/701-800/799. Champagne Tower.md new file mode 100644 index 0000000..39a2093 --- /dev/null +++ b/701-800/799. Champagne Tower.md @@ -0,0 +1,90 @@ +# 799. Champagne Tower + +- Difficulty: Medium. +- Related Topics: Dynamic Programming. +- Similar Questions: Number of Ways to Build House of Cards. + +## Problem + +We stack glasses in a pyramid, where the **first** row has `1` glass, the **second** row has `2` glasses, and so on until the 100th row.  Each glass holds one cup of champagne. + +Then, some champagne is poured into the first glass at the top.  When the topmost glass is full, any excess liquid poured will fall equally to the glass immediately to the left and right of it.  When those glasses become full, any excess champagne will fall equally to the left and right of those glasses, and so on.  (A glass at the bottom row has its excess champagne fall on the floor.) + +For example, after one cup of champagne is poured, the top most glass is full.  After two cups of champagne are poured, the two glasses on the second row are half full.  After three cups of champagne are poured, those two cups become full - there are 3 full glasses total now.  After four cups of champagne are poured, the third row has the middle glass half full, and the two outside glasses are a quarter full, as pictured below. + + +![](https://s3-lc-upload.s3.amazonaws.com/uploads/2018/03/09/tower.png) + + +Now after pouring some non-negative integer cups of champagne, return how full the `jth` glass in the `ith` row is (both `i` and `j` are 0-indexed.) + +  +Example 1: + +``` +Input: poured = 1, query_row = 1, query_glass = 1 +Output: 0.00000 +Explanation: We poured 1 cup of champange to the top glass of the tower (which is indexed as (0, 0)). There will be no excess liquid so all the glasses under the top glass will remain empty. +``` + +Example 2: + +``` +Input: poured = 2, query_row = 1, query_glass = 1 +Output: 0.50000 +Explanation: We poured 2 cups of champange to the top glass of the tower (which is indexed as (0, 0)). There is one cup of excess liquid. The glass indexed as (1, 0) and the glass indexed as (1, 1) will share the excess liquid equally, and each will get half cup of champange. +``` + +Example 3: + +``` +Input: poured = 100000009, query_row = 33, query_glass = 17 +Output: 1.00000 +``` + +  +**Constraints:** + + + +- `0 <= poured <= 109` + +- `0 <= query_glass <= query_row < 100` + + +## Solution + +```javascript +/** + * @param {number} poured + * @param {number} query_row + * @param {number} query_glass + * @return {number} + */ +var champagneTower = function(poured, query_row, query_glass) { + var glasses = [poured]; + for (var i = 0; i < query_row; i++) { + var nextRow = Array(i + 2).fill(0); + var hasNext = false; + for (var j = 0; j <= i; j++) { + var extra = (glasses[j] - 1) / 2; + if (extra <= 0) continue; + hasNext = true; + nextRow[j] += extra; + nextRow[j + 1] += extra; + } + if (!hasNext) return 0; + glasses = nextRow; + } + return Math.min(glasses[query_glass], 1); +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(query_row ^ 2). +* Space complexity : O(1). diff --git a/801-900/802. Find Eventual Safe States.md b/801-900/802. Find Eventual Safe States.md new file mode 100644 index 0000000..cc6efb7 --- /dev/null +++ b/801-900/802. Find Eventual Safe States.md @@ -0,0 +1,104 @@ +# 802. Find Eventual Safe States + +- Difficulty: Medium. +- Related Topics: Depth-First Search, Breadth-First Search, Graph, Topological Sort. +- Similar Questions: Build a Matrix With Conditions. + +## Problem + +There is a directed graph of `n` nodes with each node labeled from `0` to `n - 1`. The graph is represented by a **0-indexed** 2D integer array `graph` where `graph[i]` is an integer array of nodes adjacent to node `i`, meaning there is an edge from node `i` to each node in `graph[i]`. + +A node is a **terminal node** if there are no outgoing edges. A node is a **safe node** if every possible path starting from that node leads to a **terminal node** (or another safe node). + +Return **an array containing all the **safe nodes** of the graph**. The answer should be sorted in **ascending** order. + +  +Example 1: + +![](https://s3-lc-upload.s3.amazonaws.com/uploads/2018/03/17/picture1.png) + +``` +Input: graph = [[1,2],[2,3],[5],[0],[5],[],[]] +Output: [2,4,5,6] +Explanation: The given graph is shown above. +Nodes 5 and 6 are terminal nodes as there are no outgoing edges from either of them. +Every path starting at nodes 2, 4, 5, and 6 all lead to either node 5 or 6. +``` + +Example 2: + +``` +Input: graph = [[1,2,3,4],[1,2],[3,4],[0,4],[]] +Output: [4] +Explanation: +Only node 4 is a terminal node, and every path starting at node 4 leads to node 4. +``` + +  +**Constraints:** + + + +- `n == graph.length` + +- `1 <= n <= 104` + +- `0 <= graph[i].length <= n` + +- `0 <= graph[i][j] <= n - 1` + +- `graph[i]` is sorted in a strictly increasing order. + +- The graph may contain self-loops. + +- The number of edges in the graph will be in the range `[1, 4 * 104]`. + + + +## Solution + +```javascript +/** + * @param {number[][]} graph + * @return {number[]} + */ +var eventualSafeNodes = function(graph) { + var map = Array(graph.length); + var path = Array(graph.length); + var res = []; + for (var i = 0; i < graph.length; i++) { + if (isSafeNode(i, graph, map, path)) { + res.push(i); + } + } + return res; +}; + +var isSafeNode = function(i, graph, map, path) { + if (graph[i].length === 0 || map[i] === 1) return true; + if (map[i] === 2 || path[i] === 1) return false; + path[i] = 1; + for (var j = 0; j < graph[i].length; j++) { + var index = graph[i][j]; + if (!isSafeNode(index, graph, map, path)) { + path[i] = 0; + map[i] = 2; + return false; + } + } + path[i] = 0; + map[i] = 1; + return true; +}; +``` + +**Explain:** + +DFS (Depth First Search). + +**Complexity:** + +`n` nodes, `m` edges. + +* Time complexity : O(n + m). +* Space complexity : O(n + m). diff --git a/801-900/808. Soup Servings.md b/801-900/808. Soup Servings.md new file mode 100644 index 0000000..52739b5 --- /dev/null +++ b/801-900/808. Soup Servings.md @@ -0,0 +1,96 @@ +# 808. Soup Servings + +- Difficulty: Medium. +- Related Topics: Math, Dynamic Programming, Probability and Statistics. +- Similar Questions: . + +## Problem + +There are two types of soup: **type A** and **type B**. Initially, we have `n` ml of each type of soup. There are four kinds of operations: + + + +- Serve `100` ml of **soup A** and `0` ml of **soup B**, + +- Serve `75` ml of **soup A** and `25` ml of **soup B**, + +- Serve `50` ml of **soup A** and `50` ml of **soup B**, and + +- Serve `25` ml of **soup A** and `75` ml of **soup B**. + + +When we serve some soup, we give it to someone, and we no longer have it. Each turn, we will choose from the four operations with an equal probability `0.25`. If the remaining volume of soup is not enough to complete the operation, we will serve as much as possible. We stop once we no longer have some quantity of both types of soup. + +**Note** that we do not have an operation where all `100` ml's of **soup B** are used first. + +Return **the probability that **soup A** will be empty first, plus half the probability that **A** and **B** become empty at the same time**. Answers within `10-5` of the actual answer will be accepted. + +  +Example 1: + +``` +Input: n = 50 +Output: 0.62500 +Explanation: If we choose the first two operations, A will become empty first. +For the third operation, A and B will become empty at the same time. +For the fourth operation, B will become empty first. +So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625. +``` + +Example 2: + +``` +Input: n = 100 +Output: 0.71875 +``` + +  +**Constraints:** + + + +- `0 <= n <= 109` + + + +## Solution + +```javascript +/** + * @param {number} n + * @return {number} + */ +var soupServings = function(n) { + var m = Math.ceil(n / 25); + var dp = {}; + for (var i = 1; i <= m; i++) { + if (solve(i, i, dp) > (1 - Math.pow(10, -5))) { + return 1; + } + } + return solve(m, m, dp); +}; + +var solve = function(a, b, dp) { + if (a <= 0 && b <= 0) return 0.5; + if (a <= 0) return 1; + if (b <= 0) return 0; + var key = `${a}-${b}`; + if (dp[key] === undefined) { + dp[key] = 0.25 * solve(a - 4, b, dp) + + 0.25 * solve(a - 3, b - 1, dp) + + 0.25 * solve(a - 2, b - 2, dp) + + 0.25 * solve(a - 1, b - 3, dp); + } + return dp[key]; +}; +``` + +**Explain:** + +Top-down, DP. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/801-900/815. Bus Routes.md b/801-900/815. Bus Routes.md new file mode 100644 index 0000000..e629ad1 --- /dev/null +++ b/801-900/815. Bus Routes.md @@ -0,0 +1,123 @@ +# 815. Bus Routes + +- Difficulty: Hard. +- Related Topics: Array, Hash Table, Breadth-First Search. +- Similar Questions: Minimum Costs Using the Train Line. + +## Problem + +You are given an array `routes` representing bus routes where `routes[i]` is a bus route that the `ith` bus repeats forever. + + + +- For example, if `routes[0] = [1, 5, 7]`, this means that the `0th` bus travels in the sequence `1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ...` forever. + + +You will start at the bus stop `source` (You are not on any bus initially), and you want to go to the bus stop `target`. You can travel between bus stops by buses only. + +Return **the least number of buses you must take to travel from **`source`** to **`target`. Return `-1` if it is not possible. + +  +Example 1: + +``` +Input: routes = [[1,2,7],[3,6,7]], source = 1, target = 6 +Output: 2 +Explanation: The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6. +``` + +Example 2: + +``` +Input: routes = [[7,12],[4,5,15],[6],[15,19],[9,12,13]], source = 15, target = 12 +Output: -1 +``` + +  +**Constraints:** + + + +- `1 <= routes.length <= 500`. + +- `1 <= routes[i].length <= 105` + +- All the values of `routes[i]` are **unique**. + +- `sum(routes[i].length) <= 105` + +- `0 <= routes[i][j] < 106` + +- `0 <= source, target < 106` + + + +## Solution + +```javascript +/** + * @param {number[][]} routes + * @param {number} source + * @param {number} target + * @return {number} + */ +var numBusesToDestination = function(routes, source, target) { + if (source === target) return 0; + var stopToBusMap = {}; + // O(n * m) + for (var i = 0 ; i < routes.length; i++) { + for (var j = 0; j < routes[i].length; j++) { + var stop = routes[i][j]; + stopToBusMap[stop] = stopToBusMap[stop] || []; + stopToBusMap[stop].push(i); + } + } + // O(n * m * n) + var busToBusMap = Array(routes.length).fill(0).map(() => []); + for (var i = 0 ; i < routes.length; i++) { + var busMap = Array(routes.length); + for (var j = 0; j < routes[i].length; j++) { + var stop = routes[i][j]; + stopToBusMap[stop].forEach(bus => { + bus !== i && !busMap[bus] && busToBusMap[i].push(bus); + busMap[bus] = true; + }); + } + } + if (!stopToBusMap[target] || !stopToBusMap[source]) return -1; + var targetBusMap = stopToBusMap[target].reduce((map, bus) => { + map[bus] = true; + return map; + }, {}); + var visited = Array(routes.length); + var queue = stopToBusMap[source]; + var res = 1; + queue.forEach(bus => visited[bus] = true); + // O(n) + while (queue.length) { + var nextQueue = []; + for (var i = 0; i < queue.length; i++) { + var bus = queue[i]; + if (targetBusMap[bus]) return res; + for (var j = 0; j < busToBusMap[bus].length; j++) { + var bus2 = busToBusMap[bus][j]; + if (visited[bus2]) continue; + visited[bus2] = true; + nextQueue.push(bus2); + } + } + queue = nextQueue; + res += 1; + } + return -1; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n ^ 2 * m). +* Space complexity : O(n * m). diff --git a/801-900/823. Binary Trees With Factors.md b/801-900/823. Binary Trees With Factors.md new file mode 100644 index 0000000..366a5ba --- /dev/null +++ b/801-900/823. Binary Trees With Factors.md @@ -0,0 +1,84 @@ +# 823. Binary Trees With Factors + +- Difficulty: Medium. +- Related Topics: Array, Hash Table, Dynamic Programming, Sorting. +- Similar Questions: . + +## Problem + +Given an array of unique integers, `arr`, where each integer `arr[i]` is strictly greater than `1`. + +We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of its children. + +Return **the number of binary trees we can make**. The answer may be too large so return the answer **modulo** `109 + 7`. + +  +Example 1: + +``` +Input: arr = [2,4] +Output: 3 +Explanation: We can make these trees: [2], [4], [4, 2, 2] +``` + +Example 2: + +``` +Input: arr = [2,4,5,10] +Output: 7 +Explanation: We can make these trees: [2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2]. +``` + +  +**Constraints:** + + + +- `1 <= arr.length <= 1000` + +- `2 <= arr[i] <= 109` + +- All the values of `arr` are **unique**. + + + +## Solution + +```javascript +/** + * @param {number[]} arr + * @return {number} + */ +var numFactoredBinaryTrees = function(arr) { + arr.sort((a, b) => a - b); + + var numMap = {}; + for (var i = 0; i < arr.length; i++) { + numMap[arr[i]] = i; + } + + var dp = Array(arr.length).fill(1); + var mod = Math.pow(10, 9) + 7; + var res = 0; + for (var i = 0; i < arr.length; i++) { + for (var j = 0; arr[j] <= Math.sqrt(arr[i]); j++) { + var k = numMap[arr[i] / arr[j]]; + if (k === undefined) continue; + var num = j === k ? (dp[j] * dp[k]) % mod : (dp[j] * dp[k] * 2) % mod; + dp[i] = (dp[i] + num) % mod; + } + res = (res + dp[i]) % mod; + } + + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * log(n)). +* Space complexity : O(n). diff --git a/801-900/844. Backspace String Compare.md b/801-900/844. Backspace String Compare.md new file mode 100644 index 0000000..7acb8ee --- /dev/null +++ b/801-900/844. Backspace String Compare.md @@ -0,0 +1,90 @@ +# 844. Backspace String Compare + +- Difficulty: Easy. +- Related Topics: Two Pointers, String, Stack, Simulation. +- Similar Questions: Crawler Log Folder, Removing Stars From a String. + +## Problem + +Given two strings `s` and `t`, return `true` **if they are equal when both are typed into empty text editors**. `'#'` means a backspace character. + +Note that after backspacing an empty text, the text will continue empty. + +  +Example 1: + +``` +Input: s = "ab#c", t = "ad#c" +Output: true +Explanation: Both s and t become "ac". +``` + +Example 2: + +``` +Input: s = "ab##", t = "c#d#" +Output: true +Explanation: Both s and t become "". +``` + +Example 3: + +``` +Input: s = "a#c", t = "b" +Output: false +Explanation: s becomes "c" while t becomes "b". +``` + +  +**Constraints:** + + + +- `1 <= s.length, t.length <= 200` + +- `s` and `t` only contain lowercase letters and `'#'` characters. + + +  +**Follow up:** Can you solve it in `O(n)` time and `O(1)` space? + + +## Solution + +```javascript +/** + * @param {string} s + * @param {string} t + * @return {boolean} + */ +var backspaceCompare = function(s, t) { + var i = s.length - 1; + var j = t.length - 1; + while (i >= 0 || j >= 0) { + i = findCharIndex(s, i); + j = findCharIndex(t, j); + if (s[i] !== t[j]) return false; + i--; + j--; + } + return true; +}; + +var findCharIndex = function(s, i) { + var num = 0; + while (num || s[i] === '#') { + s[i] === '#' ? num++ : num--; + i--; + } + return i; +} +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/801-900/852. Peak Index in a Mountain Array.md b/801-900/852. Peak Index in a Mountain Array.md new file mode 100644 index 0000000..7413014 --- /dev/null +++ b/801-900/852. Peak Index in a Mountain Array.md @@ -0,0 +1,92 @@ +# 852. Peak Index in a Mountain Array + +- Difficulty: Medium. +- Related Topics: Array, Binary Search. +- Similar Questions: Find Peak Element, Find in Mountain Array, Minimum Number of Removals to Make Mountain Array. + +## Problem + +An array `arr` is a **mountain** if the following properties hold: + + + +- `arr.length >= 3` + There exists some `i` with `0 < i < arr.length - 1` such that: + + +- `arr[0] < arr[1] < ... < arr[i - 1] < arr[i] ` + +- `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]` + + + + +Given a mountain array `arr`, return the index `i` such that `arr[0] < arr[1] < ... < arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1]`. + +You must solve it in `O(log(arr.length))` time complexity. + +  +Example 1: + +``` +Input: arr = [0,1,0] +Output: 1 +``` + +Example 2: + +``` +Input: arr = [0,2,1,0] +Output: 1 +``` + +Example 3: + +``` +Input: arr = [0,10,5,2] +Output: 1 +``` + +  +**Constraints:** + + + +- `3 <= arr.length <= 105` + +- `0 <= arr[i] <= 106` + +- `arr` is **guaranteed** to be a mountain array. + + + +## Solution + +```javascript +/** + * @param {number[]} arr + * @return {number} + */ +var peakIndexInMountainArray = function(arr) { + var left = 0; + var right = arr.length - 1; + while (left < right) { + var mid = left + Math.floor((right - left) / 2); + if (arr[mid] > arr[mid + 1]) { + right = mid; + } else { + left = mid + 1; + } + } + return left; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(log(n)). +* Space complexity : O(1). diff --git a/801-900/859. Buddy Strings.md b/801-900/859. Buddy Strings.md new file mode 100644 index 0000000..92a4591 --- /dev/null +++ b/801-900/859. Buddy Strings.md @@ -0,0 +1,89 @@ +# 859. Buddy Strings + +- Difficulty: Easy. +- Related Topics: Hash Table, String. +- Similar Questions: Determine if Two Strings Are Close, Check if One String Swap Can Make Strings Equal, Make Number of Distinct Characters Equal. + +## Problem + +Given two strings `s` and `goal`, return `true`** if you can swap two letters in **`s`** so the result is equal to **`goal`**, otherwise, return **`false`**.** + +Swapping letters is defined as taking two indices `i` and `j` (0-indexed) such that `i != j` and swapping the characters at `s[i]` and `s[j]`. + + + +- For example, swapping at indices `0` and `2` in `"abcd"` results in `"cbad"`. + + +  +Example 1: + +``` +Input: s = "ab", goal = "ba" +Output: true +Explanation: You can swap s[0] = 'a' and s[1] = 'b' to get "ba", which is equal to goal. +``` + +Example 2: + +``` +Input: s = "ab", goal = "ab" +Output: false +Explanation: The only letters you can swap are s[0] = 'a' and s[1] = 'b', which results in "ba" != goal. +``` + +Example 3: + +``` +Input: s = "aa", goal = "aa" +Output: true +Explanation: You can swap s[0] = 'a' and s[1] = 'a' to get "aa", which is equal to goal. +``` + +  +**Constraints:** + + + +- `1 <= s.length, goal.length <= 2 * 104` + +- `s` and `goal` consist of lowercase letters. + + + +## Solution + +```javascript +/** + * @param {string} s + * @param {string} goal + * @return {boolean} + */ +var buddyStrings = function(s, goal) { + if (s.length !== goal.length) return false; + if (s === goal) { + const map = {}; + return !!Array.from(s).find(char => { + map[char] = (map[char] || 0) + 1; + return map[char] === 2; + }); + } + var diff = []; + for (var i = 0; i < s.length; i++) { + if (s[i] !== goal[i]) { + if (diff.length >= 2) return false; + diff.push(i); + } + } + return diff.length === 2 && s[diff[0]] === goal[diff[1]] && s[diff[1]] === goal[diff[0]]; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/801-900/863. All Nodes Distance K in Binary Tree.md b/801-900/863. All Nodes Distance K in Binary Tree.md new file mode 100644 index 0000000..6b407ca --- /dev/null +++ b/801-900/863. All Nodes Distance K in Binary Tree.md @@ -0,0 +1,108 @@ +# 863. All Nodes Distance K in Binary Tree + +- Difficulty: Medium. +- Related Topics: Tree, Depth-First Search, Breadth-First Search, Binary Tree. +- Similar Questions: Amount of Time for Binary Tree to Be Infected. + +## Problem + +Given the `root` of a binary tree, the value of a target node `target`, and an integer `k`, return **an array of the values of all nodes that have a distance **`k`** from the target node.** + +You can return the answer in **any order**. + +  +Example 1: + +![](https://s3-lc-upload.s3.amazonaws.com/uploads/2018/06/28/sketch0.png) + +``` +Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, k = 2 +Output: [7,4,1] +Explanation: The nodes that are a distance 2 from the target node (with value 5) have values 7, 4, and 1. +``` + +Example 2: + +``` +Input: root = [1], target = 1, k = 3 +Output: [] +``` + +  +**Constraints:** + + + +- The number of nodes in the tree is in the range `[1, 500]`. + +- `0 <= Node.val <= 500` + +- All the values `Node.val` are **unique**. + +- `target` is the value of one of the nodes in the tree. + +- `0 <= k <= 1000` + + + +## Solution + +```javascript +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ +/** + * @param {TreeNode} root + * @param {TreeNode} target + * @param {number} k + * @return {number[]} + */ +var distanceK = function(root, target, k) { + var nodes = []; + var parents = []; + visit(root, nodes, parents); + + var arr = [[nodes[target.val], '']]; + while (k > 0) { + var newArr = []; + for (var i = 0; i < arr.length; i++) { + var [node, direction] = arr[i]; + node.left && direction !== 'left' && newArr.push([node.left, 'parent']); + node.right && direction !== 'right' && newArr.push([node.right, 'parent']); + parents[node.val] && direction !== 'parent' && newArr.push([ + parents[node.val], + parents[node.val].left === node ? 'left' : 'right', + ]); + } + arr = newArr; + k--; + } + + return arr.map(node => node[0].val); +}; + +var visit = function(root, nodes, parents) { + nodes[root.val] = root; + if (root.left) { + parents[root.left.val] = root; + visit(root.left, nodes, parents); + } + if (root.right) { + parents[root.right.val] = root; + visit(root.right, nodes, parents); + } +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/801-900/867. Transpose Matrix.md b/801-900/867. Transpose Matrix.md new file mode 100644 index 0000000..e55c077 --- /dev/null +++ b/801-900/867. Transpose Matrix.md @@ -0,0 +1,76 @@ +# 867. Transpose Matrix + +- Difficulty: Easy. +- Related Topics: Array, Matrix, Simulation. +- Similar Questions: . + +## Problem + +Given a 2D integer array `matrix`, return **the **transpose** of** `matrix`. + +The **transpose** of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices. + + +![](https://assets.leetcode.com/uploads/2021/02/10/hint_transpose.png) + + +  +Example 1: + +``` +Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] +Output: [[1,4,7],[2,5,8],[3,6,9]] +``` + +Example 2: + +``` +Input: matrix = [[1,2,3],[4,5,6]] +Output: [[1,4],[2,5],[3,6]] +``` + +  +**Constraints:** + + + +- `m == matrix.length` + +- `n == matrix[i].length` + +- `1 <= m, n <= 1000` + +- `1 <= m * n <= 105` + +- `-109 <= matrix[i][j] <= 109` + + + +## Solution + +```javascript +/** + * @param {number[][]} matrix + * @return {number[][]} + */ +var transpose = function(matrix) { + var m = matrix.length; + var n = matrix[0].length; + var res = Array(n).fill(0).map(() => Array(m)); + for (var i = 0; i < m; i++) { + for (var j = 0; j < n; j++) { + res[j][i] = matrix[i][j]; + } + } + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(m * n). +* Space complexity : O(m * n). 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/880. Decoded String at Index.md b/801-900/880. Decoded String at Index.md new file mode 100644 index 0000000..d47e602 --- /dev/null +++ b/801-900/880. Decoded String at Index.md @@ -0,0 +1,120 @@ +# 880. Decoded String at Index + +- Difficulty: Medium. +- Related Topics: String, Stack. +- Similar Questions: . + +## Problem + +You are given an encoded string `s`. To decode the string to a tape, the encoded string is read one character at a time and the following steps are taken: + + + +- If the character read is a letter, that letter is written onto the tape. + +- If the character read is a digit `d`, the entire current tape is repeatedly written `d - 1` more times in total. + + +Given an integer `k`, return **the **`kth`** letter (**1-indexed)** in the decoded string**. + +  +Example 1: + +``` +Input: s = "leet2code3", k = 10 +Output: "o" +Explanation: The decoded string is "leetleetcodeleetleetcodeleetleetcode". +The 10th letter in the string is "o". +``` + +Example 2: + +``` +Input: s = "ha22", k = 5 +Output: "h" +Explanation: The decoded string is "hahahaha". +The 5th letter is "h". +``` + +Example 3: + +``` +Input: s = "a2345678999999999999999", k = 1 +Output: "a" +Explanation: The decoded string is "a" repeated 8301530446056247680 times. +The 1st letter is "a". +``` + +  +**Constraints:** + + + +- `2 <= s.length <= 100` + +- `s` consists of lowercase English letters and digits `2` through `9`. + +- `s` starts with a letter. + +- `1 <= k <= 109` + +- It is guaranteed that `k` is less than or equal to the length of the decoded string. + +- The decoded string is guaranteed to have less than `263` letters. + + + +## Solution + +```javascript +/** + * @param {string} s + * @param {number} k + * @return {string} + */ +var decodeAtIndex = function(s, k) { + var totalMap = Array(s.length); + for (var i = 0; i < s.length; i++) { + if (isDigit(s[i])) { + totalMap[i] = Number(s[i]) * totalMap[i - 1]; + } else { + totalMap[i] = (totalMap[i - 1] || 0) + 1; + } + if (totalMap[i] >= k) { + return helper(s, k, totalMap, i); + } + } +}; + +var helper = function(s, k, totalMap, i) { + if (isDigit(s[i])) { + if (totalMap[i] === k || k % totalMap[i - 1] === 0) { + var j = i - 1; + while (isDigit(s[j])) j--; + return s[j]; + } else { + var n = k % totalMap[i - 1]; + return helper(s, n, totalMap, i - 1); + } + } else { + if (totalMap[i] === k) { + return s[i]; + } else { + return helper(s, k, totalMap, i - 1); + } + } +}; + +var isDigit = function(char) { + return char >= '2' && char <= '9'; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/801-900/881. Boats to Save People.md b/801-900/881. Boats to Save People.md new file mode 100644 index 0000000..edd2598 --- /dev/null +++ b/801-900/881. Boats to Save People.md @@ -0,0 +1,85 @@ +# 881. Boats to Save People + +- Difficulty: Medium. +- Related Topics: Array, Two Pointers, Greedy, Sorting. +- Similar Questions: . + +## Problem + +You are given an array `people` where `people[i]` is the weight of the `ith` person, and an **infinite number of boats** where each boat can carry a maximum weight of `limit`. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most `limit`. + +Return **the minimum number of boats to carry every given person**. + +  +Example 1: + +``` +Input: people = [1,2], limit = 3 +Output: 1 +Explanation: 1 boat (1, 2) +``` + +Example 2: + +``` +Input: people = [3,2,2,1], limit = 3 +Output: 3 +Explanation: 3 boats (1, 2), (2) and (3) +``` + +Example 3: + +``` +Input: people = [3,5,3,4], limit = 5 +Output: 4 +Explanation: 4 boats (3), (3), (4), (5) +``` + +  +**Constraints:** + + + +- `1 <= people.length <= 5 * 104` + +- `1 <= people[i] <= limit <= 3 * 104` + + + +## Solution + +```javascript +/** + * @param {number[]} people + * @param {number} limit + * @return {number} + */ +var numRescueBoats = function(people, limit) { + people.sort((a, b) => a - b); + var left = 0; + var right = people.length - 1; + var res = 0; + while (left <= right) { + res++; + if (left === right) { + break; + } + if (people[left] + people[right] > limit) { + right--; + } else { + right--; + left++; + } + } + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n * log(n)). +* Space complexity : O(1). diff --git a/801-900/894. All Possible Full Binary Trees.md b/801-900/894. All Possible Full Binary Trees.md new file mode 100644 index 0000000..228a06e --- /dev/null +++ b/801-900/894. All Possible Full Binary Trees.md @@ -0,0 +1,86 @@ +# 894. All Possible Full Binary Trees + +- Difficulty: Medium. +- Related Topics: Dynamic Programming, Tree, Recursion, Memoization, Binary Tree. +- Similar Questions: . + +## Problem + +Given an integer `n`, return **a list of all possible **full binary trees** with** `n` **nodes**. Each node of each tree in the answer must have `Node.val == 0`. + +Each element of the answer is the root node of one possible tree. You may return the final list of trees in **any order**. + +A **full binary tree** is a binary tree where each node has exactly `0` or `2` children. + +  +Example 1: + +![](https://s3-lc-upload.s3.amazonaws.com/uploads/2018/08/22/fivetrees.png) + +``` +Input: n = 7 +Output: [[0,0,0,null,null,0,0,null,null,0,0],[0,0,0,null,null,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,null,null,null,null,0,0],[0,0,0,0,0,null,null,0,0]] +``` + +Example 2: + +``` +Input: n = 3 +Output: [[0,0,0]] +``` + +  +**Constraints:** + + + +- `1 <= n <= 20` + + + +## 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 {number} n + * @return {TreeNode[]} + */ +var allPossibleFBT = function(n) { + var dp = Array(n); + dp[0] = [new TreeNode()]; + return solve(n, dp); +}; + +var solve = function(n, dp) { + if (dp[n - 1]) return dp[n - 1]; + var res = []; + for (var i = 1; i < n - 1; i += 2) { + var left = solve(i, dp); + var right = solve(n - 1 - i, dp); + for (var j = 0; j < left.length; j++) { + for (var m = 0; m < right.length; m++) { + res.push(new TreeNode(0, left[j], right[m])); + } + } + } + dp[n - 1] = res; + return res; +}; +``` + +**Explain:** + +Bottom-up with dynamic programming. + +**Complexity:** + +* Time complexity : O(2 ^ (n / 2)). +* Space complexity : O(n * 2 ^ (n / 2)). diff --git a/801-900/896. Monotonic Array.md b/801-900/896. Monotonic Array.md new file mode 100644 index 0000000..5ca3cac --- /dev/null +++ b/801-900/896. Monotonic Array.md @@ -0,0 +1,68 @@ +# 896. Monotonic Array + +- Difficulty: Easy. +- Related Topics: Array. +- Similar Questions: Count Hills and Valleys in an Array. + +## Problem + +An array is **monotonic** if it is either monotone increasing or monotone decreasing. + +An array `nums` is monotone increasing if for all `i <= j`, `nums[i] <= nums[j]`. An array `nums` is monotone decreasing if for all `i <= j`, `nums[i] >= nums[j]`. + +Given an integer array `nums`, return `true`** if the given array is monotonic, or **`false`** otherwise**. + +  +Example 1: + +``` +Input: nums = [1,2,2,3] +Output: true +``` + +Example 2: + +``` +Input: nums = [6,5,4,4] +Output: true +``` + +Example 3: + +``` +Input: nums = [1,3,2] +Output: false +``` + +  +**Constraints:** + + + +- `1 <= nums.length <= 105` + +- `-105 <= nums[i] <= 105` + + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @return {boolean} + */ +var isMonotonic = function(nums) { + return nums.every((num, i) => i === 0 || nums[i - 1] <= num) + || nums.every((num, i) => i === 0 || nums[i - 1] >= num); +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/901-1000/905. Sort Array By Parity.md b/901-1000/905. Sort Array By Parity.md new file mode 100644 index 0000000..389f9cb --- /dev/null +++ b/901-1000/905. Sort Array By Parity.md @@ -0,0 +1,75 @@ +# 905. Sort Array By Parity + +- Difficulty: Easy. +- Related Topics: Array, Two Pointers, Sorting. +- Similar Questions: Sort Even and Odd Indices Independently, Largest Number After Digit Swaps by Parity. + +## Problem + +Given an integer array `nums`, move all the even integers at the beginning of the array followed by all the odd integers. + +Return ****any array** that satisfies this condition**. + +  +Example 1: + +``` +Input: nums = [3,1,2,4] +Output: [2,4,3,1] +Explanation: The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted. +``` + +Example 2: + +``` +Input: nums = [0] +Output: [0] +``` + +  +**Constraints:** + + + +- `1 <= nums.length <= 5000` + +- `0 <= nums[i] <= 5000` + + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @return {number[]} + */ +var sortArrayByParity = function(nums) { + var right = nums.length - 1; + var i = 0; + while (i < right) { + if (nums[i] % 2) { + swap(nums, i, right); + right--; + } else { + i++; + } + } + return nums; +}; + +var swap = function(nums, i, j) { + var tmp = nums[i]; + nums[i] = nums[j]; + nums[j] = tmp; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(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/910. Smallest Range II.md b/901-1000/910. Smallest Range II.md new file mode 100644 index 0000000..c6d1c24 --- /dev/null +++ b/901-1000/910. Smallest Range II.md @@ -0,0 +1,83 @@ +# 910. Smallest Range II + +- Difficulty: Medium. +- Related Topics: Array, Math, Greedy, Sorting. +- Similar Questions: . + +## Problem + +You are given an integer array `nums` and an integer `k`. + +For each index `i` where `0 <= i < nums.length`, change `nums[i]` to be either `nums[i] + k` or `nums[i] - k`. + +The **score** of `nums` is the difference between the maximum and minimum elements in `nums`. + +Return **the minimum **score** of **`nums`** after changing the values at each index**. + +  +Example 1: + +``` +Input: nums = [1], k = 0 +Output: 0 +Explanation: The score is max(nums) - min(nums) = 1 - 1 = 0. +``` + +Example 2: + +``` +Input: nums = [0,10], k = 2 +Output: 6 +Explanation: Change nums to be [2, 8]. The score is max(nums) - min(nums) = 8 - 2 = 6. +``` + +Example 3: + +``` +Input: nums = [1,3,6], k = 3 +Output: 3 +Explanation: Change nums to be [4, 6, 3]. The score is max(nums) - min(nums) = 6 - 3 = 3. +``` + +  +**Constraints:** + + + +- `1 <= nums.length <= 104` + +- `0 <= nums[i] <= 104` + +- `0 <= k <= 104` + + + +## Solution + +```javascript +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var smallestRangeII = function(nums, k) { + nums.sort((a, b) => a - b); + var n = nums.length; + var res = nums[n - 1] - nums[0]; + for (var i = 0; i < n - 1; i++) { + var low = Math.min(nums[0] + k, nums[i + 1] - k); + var high = Math.max(nums[n - 1] - k, nums[i] + k); + res = Math.min(res, high - low); + } + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(1). diff --git a/901-1000/920. Number of Music Playlists.md b/901-1000/920. Number of Music Playlists.md new file mode 100644 index 0000000..aa2d5d1 --- /dev/null +++ b/901-1000/920. Number of Music Playlists.md @@ -0,0 +1,87 @@ +# 920. Number of Music Playlists + +- Difficulty: Hard. +- Related Topics: Math, Dynamic Programming, Combinatorics. +- Similar Questions: Count the Number of Good Subsequences. + +## Problem + +Your music player contains `n` different songs. You want to listen to `goal` songs (not necessarily different) during your trip. To avoid boredom, you will create a playlist so that: + + + +- Every song is played **at least once**. + +- A song can only be played again only if `k` other songs have been played. + + +Given `n`, `goal`, and `k`, return **the number of possible playlists that you can create**. Since the answer can be very large, return it **modulo** `109 + 7`. +  +Example 1: + +``` +Input: n = 3, goal = 3, k = 1 +Output: 6 +Explanation: There are 6 possible playlists: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], and [3, 2, 1]. +``` + +Example 2: + +``` +Input: n = 2, goal = 3, k = 0 +Output: 6 +Explanation: There are 6 possible playlists: [1, 1, 2], [1, 2, 1], [2, 1, 1], [2, 2, 1], [2, 1, 2], and [1, 2, 2]. +``` + +Example 3: + +``` +Input: n = 2, goal = 3, k = 1 +Output: 2 +Explanation: There are 2 possible playlists: [1, 2, 1] and [2, 1, 2]. +``` + +  +**Constraints:** + + + +- `0 <= k < n <= goal <= 100` + + + +## Solution + +```javascript +/** + * @param {number} n + * @param {number} goal + * @param {number} k + * @return {number} + */ +var numMusicPlaylists = function(n, goal, k) { + var mod = Math.pow(10, 9) + 7; + var dp = Array(goal + 1).fill(0).map(() => Array(n + 1).fill(0)); + dp[0][0] = 1; + for (var i = 1; i <= goal; i++) { + for (var j = 1; j <= Math.min(i, n); j++) { + // new song + dp[i][j] = dp[i - 1][j - 1] * (n - (j - 1)) % mod; + // old song + if (j > k) { + dp[i][j] = (dp[i][j] + dp[i - 1][j] * (j - k)) % mod; + } + } + } + return dp[goal][n]; +}; +``` + +**Explain:** + +Bottom-up DP. + +**Complexity:** + +* Time complexity : O(goal * n). +* Space complexity : O(goal * 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/935. Knight Dialer.md b/901-1000/935. Knight Dialer.md new file mode 100644 index 0000000..b3fbd99 --- /dev/null +++ b/901-1000/935. Knight Dialer.md @@ -0,0 +1,111 @@ +# 935. Knight Dialer + +- Difficulty: Medium. +- Related Topics: Dynamic Programming. +- Similar Questions: . + +## Problem + +The chess knight has a **unique movement**, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an **L**). The possible movements of chess knight are shown in this diagaram: + +A chess knight can move as indicated in the chess diagram below: + +![](https://assets.leetcode.com/uploads/2020/08/18/chess.jpg) + +We have a chess knight and a phone pad as shown below, the knight **can only stand on a numeric cell** (i.e. blue cell). + +![](https://assets.leetcode.com/uploads/2020/08/18/phone.jpg) + +Given an integer `n`, return how many distinct phone numbers of length `n` we can dial. + +You are allowed to place the knight **on any numeric cell** initially and then you should perform `n - 1` jumps to dial a number of length `n`. All jumps should be **valid** knight jumps. + +As the answer may be very large, **return the answer modulo** `109 + 7`. + +  +Example 1: + +``` +Input: n = 1 +Output: 10 +Explanation: We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient. +``` + +Example 2: + +``` +Input: n = 2 +Output: 20 +Explanation: All the valid number we can dial are [04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94] +``` + +Example 3: + +``` +Input: n = 3131 +Output: 136006598 +Explanation: Please take care of the mod. +``` + +  +**Constraints:** + + + +- `1 <= n <= 5000` + + + +## Solution + +```javascript +/** + * @param {number} n + * @return {number} + */ +var knightDialer = function(n) { + var res = 0; + var mod = Math.pow(10, 9) + 7; + var dp = Array(10).fill(0).map(() => Array(n + 1)); + for (var i = 0; i < 10; i++) { + res += helper(n, i, dp); + res %= mod; + } + return res; +}; + +var helper = function(n, i, dp) { + if (n === 1) return 1; + if (i === 5) return 0; + if (dp[i][n] !== undefined) return dp[i][n]; + var mod = Math.pow(10, 9) + 7; + var jumpMap = [ + [4,6], + [6,8], + [7,9], + [4,8], + [3,9,0], + [], + [1,7,0], + [2,6], + [1,3], + [2,4] + ]; + var res = 0; + for (var j = 0; j < jumpMap[i].length; j++) { + res += helper(n - 1, jumpMap[i][j], dp); + res %= mod; + } + dp[i][n] = res; + return res; +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* 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/967. Numbers With Same Consecutive Differences.md b/901-1000/967. Numbers With Same Consecutive Differences.md new file mode 100644 index 0000000..122b990 --- /dev/null +++ b/901-1000/967. Numbers With Same Consecutive Differences.md @@ -0,0 +1,85 @@ +# 967. Numbers With Same Consecutive Differences + +- Difficulty: Medium. +- Related Topics: Backtracking, Breadth-First Search. +- Similar Questions: . + +## Problem + +Given two integers n and k, return an array of all the integers of length ```n``` where the difference between every two consecutive digits is ```k```. You may return the answer in **any order**. + +Note that the integers should not have leading zeros. Integers as ```02``` and ```043``` are not allowed. + +  +Example 1: + +``` +Input: n = 3, k = 7 +Output: [181,292,707,818,929] +Explanation: Note that 070 is not a valid number, because it has leading zeroes. +``` + +Example 2: + +``` +Input: n = 2, k = 1 +Output: [10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98] +``` + +  +**Constraints:** + + + +- ```2 <= n <= 9``` + +- ```0 <= k <= 9``` + + + +## Solution + +```javascript +/** + * @param {number} n + * @param {number} k + * @return {number[]} + */ +var numsSameConsecDiff = function(n, k) { + var res = []; + for (var i = 1; i < 10; i++) { + helper([i], n - 1, k, res); + } + return res; +}; + +var helper = function(arr, n, k, res) { + if (n === 0) { + res.push(+arr.join('')); + return; + } + if (n < 0 || n > 9) { + return; + } + var last = arr[arr.length - 1]; + if (last - k >= 0) { + arr.push(last - k); + helper(arr, n - 1, k, res); + arr.pop(); + } + if (k !== 0 && last + k < 10) { + arr.push(last + k); + helper(arr, n - 1, k, res); + arr.pop(); + } +}; +``` + +**Explain:** + +Start with 1 ~ 9, dfs (top down) to get all answers. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). 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/901-1000/998. Maximum Binary Tree II.md b/901-1000/998. Maximum Binary Tree II.md new file mode 100644 index 0000000..ac4e521 --- /dev/null +++ b/901-1000/998. Maximum Binary Tree II.md @@ -0,0 +1,119 @@ +# 998. Maximum Binary Tree II + +- Difficulty: Medium. +- Related Topics: Tree, Binary Tree. +- Similar Questions: Maximum Binary Tree. + +## Problem + +A **maximum tree** is a tree where every node has a value greater than any other value in its subtree. + +You are given the `root` of a maximum binary tree and an integer `val`. + +Just as in the previous problem, the given tree was constructed from a list `a` (`root = Construct(a)`) recursively with the following `Construct(a)` routine: + + + +- If `a` is empty, return `null`. + +- Otherwise, let `a[i]` be the largest element of `a`. Create a `root` node with the value `a[i]`. + +- The left child of `root` will be `Construct([a[0], a[1], ..., a[i - 1]])`. + +- The right child of `root` will be `Construct([a[i + 1], a[i + 2], ..., a[a.length - 1]])`. + +- Return `root`. + + +Note that we were not given `a` directly, only a root node `root = Construct(a)`. + +Suppose `b` is a copy of `a` with the value `val` appended to it. It is guaranteed that `b` has unique values. + +Return `Construct(b)`. + +  +Example 1: + +![](https://assets.leetcode.com/uploads/2021/08/09/maxtree1.JPG) + +``` +Input: root = [4,1,3,null,null,2], val = 5 +Output: [5,4,null,1,3,null,null,2] +Explanation: a = [1,4,2,3], b = [1,4,2,3,5] +``` + +Example 2: + +![](https://assets.leetcode.com/uploads/2021/08/09/maxtree21.JPG) + +``` +Input: root = [5,2,4,null,1], val = 3 +Output: [5,2,4,null,1,null,3] +Explanation: a = [2,1,5,4], b = [2,1,5,4,3] +``` + +Example 3: + +![](https://assets.leetcode.com/uploads/2021/08/09/maxtree3.JPG) + +``` +Input: root = [5,2,3,null,1], val = 4 +Output: [5,2,4,null,1,3] +Explanation: a = [2,1,5,3], b = [2,1,5,3,4] +``` + +  +**Constraints:** + + + +- The number of nodes in the tree is in the range `[1, 100]`. + +- `1 <= Node.val <= 100` + +- All the values of the tree are **unique**. + +- `1 <= 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 + * @param {number} val + * @return {TreeNode} + */ +var insertIntoMaxTree = function(root, val) { + var nodes = []; + var now = root; + while (now) { + nodes.push(now); + now = now.right; + } + for (var i = nodes.length - 1; i >= 0; i--) { + if (nodes[i].val < val) continue; + nodes[i].right = new TreeNode(val, nodes[i].right); + return root; + } + return new TreeNode(val, root); +}; +``` + +**Explain:** + +nope. + +**Complexity:** + +* Time complexity : O(n). +* Space complexity : O(n). diff --git a/README.md b/README.md index 359fff3..2b9e26f 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,9 @@ npm install # create a solution file: npm run create $leetcodeProblemUrl npm run create https://leetcode.com/problems/two-sum +# or create a solution for random LeetCode problem +npm run create:random + # build npm run build ``` diff --git a/build/index.js b/build/index.js index ca8afc6..c7f15ba 100644 --- a/build/index.js +++ b/build/index.js @@ -1,6 +1,7 @@ const fs = require('fs'); const path = require('path'); const chalk = require('chalk'); +const fse = require('fs-extra'); const url = require('./scripts/url'); const meta = require('./scripts/meta'); @@ -16,7 +17,7 @@ const tagMap = {}; const tagList = []; function buildProblems () { - const pathReg = /^\d{3}-\d{3}$/; + const pathReg = /^\d+-\d+$/; const fileReg = /\.md$/; fs.readdirSync(path.resolve(__dirname, '../')).forEach(floder => { if (!pathReg.test(floder)) return; @@ -155,10 +156,18 @@ function buildDifficulties () { }); } +function copyStaticFile() { + fse.copySync( + path.resolve(__dirname, './static'), + path.resolve(__dirname, '../docs/static') + ); +} + buildProblems(); sortProblems(); buildPages(); buildTags(); buildDifficulties(); +copyStaticFile(); console.log(`\n${chalk.blue('Done!')}\n`); diff --git a/docs/static/css/app.css b/build/static/css/app.css similarity index 100% rename from docs/static/css/app.css rename to build/static/css/app.css diff --git a/docs/static/img/favicon.png b/build/static/img/favicon.png similarity index 100% rename from docs/static/img/favicon.png rename to build/static/img/favicon.png diff --git a/docs/static/img/github.png b/build/static/img/github.png similarity index 100% rename from docs/static/img/github.png rename to build/static/img/github.png diff --git a/create/index.js b/create/index.js index 4d50145..11a431b 100644 --- a/create/index.js +++ b/create/index.js @@ -4,14 +4,14 @@ const create = data => { const path = require('path'); const chalk = require('chalk'); const pageData = { - id: data.questionId, + id: data.questionFrontendId || data.questionId, name: data.questionTitle, difficulty: data.difficulty, relatedTopics: data.topicTags.map(t => t.name).join(', '), 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`); @@ -38,7 +38,7 @@ const getDescription = (description) => { }, { regexp: /(.*?)<\/code>/ig, - replacer: (_, $1) => `\`\`\`${$1}\`\`\`` + replacer: (_, $1) => `\`${$1}\`` }, { regexp: /(.*?)<\/i>/ig, @@ -90,12 +90,26 @@ const getName = url => { return res[1]; } -const axios = require('axios'); -const name = getName(process.argv[2]); -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%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`; +const queryAndCreate = name => { + const axios = require('axios'); + 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); + }); +} + +if (require.main === module) { + queryAndCreate(getName(process.argv[2])); +} + +module.exports = { + queryAndCreate, +}; -axios.get(url).then(res => { - create(res.data.data.question); -}).catch(err => { - console.error(err); -}); diff --git a/create/random.js b/create/random.js new file mode 100644 index 0000000..e29ec4d --- /dev/null +++ b/create/random.js @@ -0,0 +1,15 @@ +const axios = require('axios'); +const { queryAndCreate } = require('./index'); + +axios.post('https://leetcode.com/graphql/', { + operationName: "randomQuestion", + query: "\n query randomQuestion($categorySlug: String, $filters: QuestionListFilterInput) {\n randomQuestion(categorySlug: $categorySlug, filters: $filters) {\n titleSlug\n }\n}\n ", + variables: { + categorySlug: "", + filters: {}, + }, +}).then(res => { + queryAndCreate(res.data.data.randomQuestion.titleSlug); +}).catch(err => { + console.error(err); +}); diff --git a/docs/difficulty/easy/index.html b/docs/difficulty/easy/index.html deleted file mode 100644 index 5d53fa5..0000000 --- a/docs/difficulty/easy/index.html +++ /dev/null @@ -1 +0,0 @@ -LeetCode javascript solutions
Difficulty:
IDTitleDifficulty
1Two SumEasy
7Reverse IntegerEasy
9Palindrome NumberEasy
13Roman to IntegerEasy
14Longest Common PrefixEasy
20Valid ParenthesesEasy
21Merge Two Sorted ListsEasy
26Remove Duplicates from Sorted ArrayEasy
27Remove ElementEasy
28Implement strStr()Easy
35Search Insert PositionEasy
38Count and SayEasy
53Maximum SubarrayEasy
58Length of Last WordEasy
66Plus OneEasy
67Add BinaryEasy
69Sqrt(x)Easy
70Climbing StairsEasy
83Remove Duplicates from Sorted ListEasy
88Merge Sorted ArrayEasy
100Same TreeEasy
101Symmetric TreeEasy
104Maximum Depth of Binary TreeEasy
107Binary Tree Level Order Traversal IIEasy
108Convert Sorted Array to Binary Search TreeEasy
110Balanced Binary TreeEasy
111Minimum Depth of Binary TreeEasy
112Path SumEasy
118Pascal's TriangleEasy
119Pascal's Triangle IIEasy
github
\ No newline at end of file diff --git a/docs/difficulty/easy/page/2.html b/docs/difficulty/easy/page/2.html deleted file mode 100644 index 14f3483..0000000 --- a/docs/difficulty/easy/page/2.html +++ /dev/null @@ -1 +0,0 @@ -LeetCode javascript solutions
Difficulty:
IDTitleDifficulty
121Best Time to Buy and Sell StockEasy
122Best Time to Buy and Sell Stock IIEasy
125Valid PalindromeEasy
136Single NumberEasy
141Linked List CycleEasy
155Min StackEasy
160Intersection of Two Linked ListsEasy
167Two Sum II - Input array is sortedEasy
168Excel Sheet Column TitleEasy
169Majority ElementEasy
171Excel Sheet Column NumberEasy
172Factorial Trailing ZeroesEasy
175Combine Two TablesEasy
176Second Highest SalaryEasy
181Employees Earning More Than Their ManagersEasy
182Duplicate EmailsEasy
183Customers Who Never OrderEasy
198House RobberEasy
202Happy NumberEasy
206Reverse Linked ListEasy
226Invert Binary TreeEasy
234Palindrome Linked ListEasy
242Valid AnagramEasy
258Add DigitsEasy
263Ugly NumberEasy
283Move ZeroesEasy
292Nim GameEasy
401Binary WatchEasy
415Add StringsEasy
557Reverse Words in a String IIIEasy
github
\ No newline at end of file diff --git a/docs/difficulty/easy/page/3.html b/docs/difficulty/easy/page/3.html deleted file mode 100644 index 155d0bb..0000000 --- a/docs/difficulty/easy/page/3.html +++ /dev/null @@ -1 +0,0 @@ -LeetCode javascript solutions
Difficulty:
IDTitleDifficulty
566Reshape the MatrixEasy
617Merge Two Binary TreesEasy
669Trim a Binary Search TreeEasy
861Flipping an ImageEasy
github
\ No newline at end of file diff --git a/docs/difficulty/hard/index.html b/docs/difficulty/hard/index.html deleted file mode 100644 index c4f6b05..0000000 --- a/docs/difficulty/hard/index.html +++ /dev/null @@ -1 +0,0 @@ -LeetCode javascript solutions
Difficulty:
IDTitleDifficulty
4Median of Two Sorted ArraysHard
10Regular Expression MatchingHard
23Merge k Sorted ListsHard
25Reverse Nodes in k-GroupHard
30Substring with Concatenation of All WordsHard
32Longest Valid ParenthesesHard
37Sudoku SolverHard
41First Missing PositiveHard
42Trapping Rain WaterHard
44Wildcard MatchingHard
45Jump Game IIHard
51N-QueensHard
52N-Queens IIHard
57Insert IntervalHard
65Valid NumberHard
68Text JustificationHard
72Edit DistanceHard
76Minimum Window SubstringHard
84Largest Rectangle in HistogramHard
85Maximal RectangleHard
87Scramble StringHard
97Interleaving StringHard
99Recover Binary Search TreeHard
115Distinct SubsequencesHard
123Best Time to Buy and Sell Stock IIIHard
124Binary Tree Maximum Path SumHard
126Word Ladder IIHard
128Longest Consecutive SequenceHard
132Palindrome Partitioning IIHard
135CandyHard
github
\ No newline at end of file diff --git a/docs/difficulty/hard/page/2.html b/docs/difficulty/hard/page/2.html deleted file mode 100644 index c638080..0000000 --- a/docs/difficulty/hard/page/2.html +++ /dev/null @@ -1 +0,0 @@ -LeetCode javascript solutions
Difficulty:
IDTitleDifficulty
140Word Break IIHard
145Binary Tree Postorder TraversalHard
146LRU CacheHard
149Max Points on a LineHard
154Find Minimum in Rotated Sorted Array IIHard
164Maximum GapHard
174Dungeon GameHard
316Remove Duplicate LettersHard
823Split Array With Same AverageHard
github
\ No newline at end of file diff --git a/docs/difficulty/medium/index.html b/docs/difficulty/medium/index.html deleted file mode 100644 index a809091..0000000 --- a/docs/difficulty/medium/index.html +++ /dev/null @@ -1 +0,0 @@ -LeetCode javascript solutions
Difficulty:
IDTitleDifficulty
2Add Two NumbersMedium
3Longest Substring Without Repeating CharactersMedium
5Longest Palindromic SubstringMedium
6ZigZag ConversionMedium
8String to Integer (atoi)Medium
11Container With Most WaterMedium
12Integer to RomanMedium
153SumMedium
163Sum ClosestMedium
17Letter Combinations of a Phone NumberMedium
184SumMedium
19Remove Nth Node From End of ListMedium
22Generate ParenthesesMedium
24Swap Nodes in PairsMedium
29Divide Two IntegersMedium
31Next PermutationMedium
33Search in Rotated Sorted ArrayMedium
34Search for a RangeMedium
36Valid SudokuMedium
39Combination SumMedium
40Combination Sum IIMedium
43Multiply StringsMedium
46PermutationsMedium
47Permutations IIMedium
48Rotate ImageMedium
49Group AnagramsMedium
50Pow(x, n)Medium
54Spiral MatrixMedium
55Jump GameMedium
56Merge IntervalsMedium
github
\ No newline at end of file diff --git a/docs/difficulty/medium/page/2.html b/docs/difficulty/medium/page/2.html deleted file mode 100644 index e87f873..0000000 --- a/docs/difficulty/medium/page/2.html +++ /dev/null @@ -1 +0,0 @@ -LeetCode javascript solutions
Difficulty:
IDTitleDifficulty
59Spiral Matrix IIMedium
60Permutation SequenceMedium
61Rotate ListMedium
62Unique PathsMedium
63Unique Paths IIMedium
64Minimum Path SumMedium
71Simplify PathMedium
73Set Matrix ZeroesMedium
74Search a 2D MatrixMedium
75Sort ColorsMedium
77CombinationsMedium
78SubsetsMedium
79Word SearchMedium
80Remove Duplicates from Sorted Array IIMedium
81Search in Rotated Sorted Array IIMedium
82Remove Duplicates from Sorted List IIMedium
86Partition ListMedium
89Gray CodeMedium
90Subsets IIMedium
91Decode WaysMedium
92Reverse Linked List IIMedium
93Restore IP AddressesMedium
94Binary Tree Inorder TraversalMedium
95Unique Binary Search Trees IIMedium
96Unique Binary Search TreesMedium
98Validate Binary Search TreeMedium
102Binary Tree Level Order TraversalMedium
103Binary Tree Zigzag Level Order TraversalMedium
105Construct Binary Tree from Preorder and Inorder TraversalMedium
106Construct Binary Tree from Inorder and Postorder TraversalMedium
github
\ No newline at end of file diff --git a/docs/difficulty/medium/page/3.html b/docs/difficulty/medium/page/3.html deleted file mode 100644 index 586cbc3..0000000 --- a/docs/difficulty/medium/page/3.html +++ /dev/null @@ -1 +0,0 @@ -LeetCode javascript solutions
Difficulty:
IDTitleDifficulty
109Convert Sorted List to Binary Search TreeMedium
113Path Sum IIMedium
114Flatten Binary Tree to Linked ListMedium
116Populating Next Right Pointers in Each NodeMedium
117Populating Next Right Pointers in Each Node IIMedium
120TriangleMedium
127Word LadderMedium
129Sum Root to Leaf NumbersMedium
130Surrounded RegionsMedium
131Palindrome PartitioningMedium
133Clone GraphMedium
134Gas StationMedium
137Single Number IIMedium
138Copy List with Random PointerMedium
139Word BreakMedium
142Linked List Cycle IIMedium
143Reorder ListMedium
144Binary Tree Preorder TraversalMedium
147Insertion Sort ListMedium
148Sort ListMedium
150Evaluate Reverse Polish NotationMedium
151Reverse Words in a StringMedium
152Maximum Product SubarrayMedium
153Find Minimum in Rotated Sorted ArrayMedium
162Find Peak ElementMedium
165Compare Version NumbersMedium
166Fraction to Recurring DecimalMedium
173Binary Search Tree IteratorMedium
177Nth Highest SalaryMedium
178Rank ScoresMedium
github
\ No newline at end of file diff --git a/docs/difficulty/medium/page/4.html b/docs/difficulty/medium/page/4.html deleted file mode 100644 index 9e04fb5..0000000 --- a/docs/difficulty/medium/page/4.html +++ /dev/null @@ -1 +0,0 @@ -LeetCode javascript solutions
Difficulty:
IDTitleDifficulty
179Largest NumberMedium
180Consecutive NumbersMedium
199Binary Tree Right Side ViewMedium
200Number of IslandsMedium
207Course ScheduleMedium
208Implement Trie (Prefix Tree)Medium
215Kth Largest Element in an ArrayMedium
221Maximal SquareMedium
238Product of Array Except SelfMedium
240Search a 2D Matrix IIMedium
264Ugly Number IIMedium
322Coin ChangeMedium
4544Sum IIMedium
537Complex Number MultiplicationMedium
547Friend CirclesMedium
560Subarray Sum Equals KMedium
623Add One Row to TreeMedium
749Shortest Completing WordMedium
862Find And Replace in StringMedium
864Image OverlapMedium
github
\ No newline at end of file diff --git a/docs/index.html b/docs/index.html deleted file mode 100644 index b8f3744..0000000 --- a/docs/index.html +++ /dev/null @@ -1 +0,0 @@ -LeetCode javascript solutions
Difficulty:
IDTitleDifficulty
1Two SumEasy
2Add Two NumbersMedium
3Longest Substring Without Repeating CharactersMedium
4Median of Two Sorted ArraysHard
5Longest Palindromic SubstringMedium
6ZigZag ConversionMedium
7Reverse IntegerEasy
8String to Integer (atoi)Medium
9Palindrome NumberEasy
10Regular Expression MatchingHard
11Container With Most WaterMedium
12Integer to RomanMedium
13Roman to IntegerEasy
14Longest Common PrefixEasy
153SumMedium
163Sum ClosestMedium
17Letter Combinations of a Phone NumberMedium
184SumMedium
19Remove Nth Node From End of ListMedium
20Valid ParenthesesEasy
21Merge Two Sorted ListsEasy
22Generate ParenthesesMedium
23Merge k Sorted ListsHard
24Swap Nodes in PairsMedium
25Reverse Nodes in k-GroupHard
26Remove Duplicates from Sorted ArrayEasy
27Remove ElementEasy
28Implement strStr()Easy
29Divide Two IntegersMedium
30Substring with Concatenation of All WordsHard
github
\ No newline at end of file diff --git a/docs/page/2.html b/docs/page/2.html deleted file mode 100644 index 065df60..0000000 --- a/docs/page/2.html +++ /dev/null @@ -1 +0,0 @@ -LeetCode javascript solutions
Difficulty:
IDTitleDifficulty
31Next PermutationMedium
32Longest Valid ParenthesesHard
33Search in Rotated Sorted ArrayMedium
34Search for a RangeMedium
35Search Insert PositionEasy
36Valid SudokuMedium
37Sudoku SolverHard
38Count and SayEasy
39Combination SumMedium
40Combination Sum IIMedium
41First Missing PositiveHard
42Trapping Rain WaterHard
43Multiply StringsMedium
44Wildcard MatchingHard
45Jump Game IIHard
46PermutationsMedium
47Permutations IIMedium
48Rotate ImageMedium
49Group AnagramsMedium
50Pow(x, n)Medium
51N-QueensHard
52N-Queens IIHard
53Maximum SubarrayEasy
54Spiral MatrixMedium
55Jump GameMedium
56Merge IntervalsMedium
57Insert IntervalHard
58Length of Last WordEasy
59Spiral Matrix IIMedium
60Permutation SequenceMedium
github
\ No newline at end of file diff --git a/docs/page/3.html b/docs/page/3.html deleted file mode 100644 index 30b32be..0000000 --- a/docs/page/3.html +++ /dev/null @@ -1 +0,0 @@ -LeetCode javascript solutions
Difficulty:
IDTitleDifficulty
61Rotate ListMedium
62Unique PathsMedium
63Unique Paths IIMedium
64Minimum Path SumMedium
65Valid NumberHard
66Plus OneEasy
67Add BinaryEasy
68Text JustificationHard
69Sqrt(x)Easy
70Climbing StairsEasy
71Simplify PathMedium
72Edit DistanceHard
73Set Matrix ZeroesMedium
74Search a 2D MatrixMedium
75Sort ColorsMedium
76Minimum Window SubstringHard
77CombinationsMedium
78SubsetsMedium
79Word SearchMedium
80Remove Duplicates from Sorted Array IIMedium
81Search in Rotated Sorted Array IIMedium
82Remove Duplicates from Sorted List IIMedium
83Remove Duplicates from Sorted ListEasy
84Largest Rectangle in HistogramHard
85Maximal RectangleHard
86Partition ListMedium
87Scramble StringHard
88Merge Sorted ArrayEasy
89Gray CodeMedium
90Subsets IIMedium
github
\ No newline at end of file diff --git a/docs/page/4.html b/docs/page/4.html deleted file mode 100644 index 35a0c3d..0000000 --- a/docs/page/4.html +++ /dev/null @@ -1 +0,0 @@ -LeetCode javascript solutions
Difficulty:
IDTitleDifficulty
91Decode WaysMedium
92Reverse Linked List IIMedium
93Restore IP AddressesMedium
94Binary Tree Inorder TraversalMedium
95Unique Binary Search Trees IIMedium
96Unique Binary Search TreesMedium
97Interleaving StringHard
98Validate Binary Search TreeMedium
99Recover Binary Search TreeHard
100Same TreeEasy
101Symmetric TreeEasy
102Binary Tree Level Order TraversalMedium
103Binary Tree Zigzag Level Order TraversalMedium
104Maximum Depth of Binary TreeEasy
105Construct Binary Tree from Preorder and Inorder TraversalMedium
106Construct Binary Tree from Inorder and Postorder TraversalMedium
107Binary Tree Level Order Traversal IIEasy
108Convert Sorted Array to Binary Search TreeEasy
109Convert Sorted List to Binary Search TreeMedium
110Balanced Binary TreeEasy
111Minimum Depth of Binary TreeEasy
112Path SumEasy
113Path Sum IIMedium
114Flatten Binary Tree to Linked ListMedium
115Distinct SubsequencesHard
116Populating Next Right Pointers in Each NodeMedium
117Populating Next Right Pointers in Each Node IIMedium
118Pascal's TriangleEasy
119Pascal's Triangle IIEasy
120TriangleMedium
github
\ No newline at end of file diff --git a/docs/page/5.html b/docs/page/5.html deleted file mode 100644 index acd483f..0000000 --- a/docs/page/5.html +++ /dev/null @@ -1 +0,0 @@ -LeetCode javascript solutions
Difficulty:
IDTitleDifficulty
121Best Time to Buy and Sell StockEasy
122Best Time to Buy and Sell Stock IIEasy
123Best Time to Buy and Sell Stock IIIHard
124Binary Tree Maximum Path SumHard
125Valid PalindromeEasy
126Word Ladder IIHard
127Word LadderMedium
128Longest Consecutive SequenceHard
129Sum Root to Leaf NumbersMedium
130Surrounded RegionsMedium
131Palindrome PartitioningMedium
132Palindrome Partitioning IIHard
133Clone GraphMedium
134Gas StationMedium
135CandyHard
136Single NumberEasy
137Single Number IIMedium
138Copy List with Random PointerMedium
139Word BreakMedium
140Word Break IIHard
141Linked List CycleEasy
142Linked List Cycle IIMedium
143Reorder ListMedium
144Binary Tree Preorder TraversalMedium
145Binary Tree Postorder TraversalHard
146LRU CacheHard
147Insertion Sort ListMedium
148Sort ListMedium
149Max Points on a LineHard
150Evaluate Reverse Polish NotationMedium
github
\ No newline at end of file diff --git a/docs/page/6.html b/docs/page/6.html deleted file mode 100644 index 046ed54..0000000 --- a/docs/page/6.html +++ /dev/null @@ -1 +0,0 @@ -LeetCode javascript solutions
Difficulty:
IDTitleDifficulty
151Reverse Words in a StringMedium
152Maximum Product SubarrayMedium
153Find Minimum in Rotated Sorted ArrayMedium
154Find Minimum in Rotated Sorted Array IIHard
155Min StackEasy
160Intersection of Two Linked ListsEasy
162Find Peak ElementMedium
164Maximum GapHard
165Compare Version NumbersMedium
166Fraction to Recurring DecimalMedium
167Two Sum II - Input array is sortedEasy
168Excel Sheet Column TitleEasy
169Majority ElementEasy
171Excel Sheet Column NumberEasy
172Factorial Trailing ZeroesEasy
173Binary Search Tree IteratorMedium
174Dungeon GameHard
175Combine Two TablesEasy
176Second Highest SalaryEasy
177Nth Highest SalaryMedium
178Rank ScoresMedium
179Largest NumberMedium
180Consecutive NumbersMedium
181Employees Earning More Than Their ManagersEasy
182Duplicate EmailsEasy
183Customers Who Never OrderEasy
198House RobberEasy
199Binary Tree Right Side ViewMedium
200Number of IslandsMedium
202Happy NumberEasy
github
\ No newline at end of file diff --git a/docs/page/7.html b/docs/page/7.html deleted file mode 100644 index a615382..0000000 --- a/docs/page/7.html +++ /dev/null @@ -1 +0,0 @@ -LeetCode javascript solutions
Difficulty:
IDTitleDifficulty
206Reverse Linked ListEasy
207Course ScheduleMedium
208Implement Trie (Prefix Tree)Medium
215Kth Largest Element in an ArrayMedium
221Maximal SquareMedium
226Invert Binary TreeEasy
234Palindrome Linked ListEasy
238Product of Array Except SelfMedium
240Search a 2D Matrix IIMedium
242Valid AnagramEasy
258Add DigitsEasy
263Ugly NumberEasy
264Ugly Number IIMedium
283Move ZeroesEasy
292Nim GameEasy
316Remove Duplicate LettersHard
322Coin ChangeMedium
401Binary WatchEasy
415Add StringsEasy
4544Sum IIMedium
537Complex Number MultiplicationMedium
547Friend CirclesMedium
557Reverse Words in a String IIIEasy
560Subarray Sum Equals KMedium
566Reshape the MatrixEasy
617Merge Two Binary TreesEasy
623Add One Row to TreeMedium
669Trim a Binary Search TreeEasy
749Shortest Completing WordMedium
823Split Array With Same AverageHard
github
\ No newline at end of file diff --git a/docs/page/8.html b/docs/page/8.html deleted file mode 100644 index ec3ca11..0000000 --- a/docs/page/8.html +++ /dev/null @@ -1 +0,0 @@ -LeetCode javascript solutions
Difficulty:
IDTitleDifficulty
861Flipping an ImageEasy
862Find And Replace in StringMedium
864Image OverlapMedium
github
\ No newline at end of file diff --git a/docs/problem/3sum-closest.html b/docs/problem/3sum-closest.html deleted file mode 100644 index 503fe50..0000000 --- a/docs/problem/3sum-closest.html +++ /dev/null @@ -1,46 +0,0 @@ -3Sum Closest - LeetCode javascript solutions

16. 3Sum Closest

Difficulty:
Related Topics:
Similar Questions:

Problem

-

Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

-

Example:

-
Given array nums = [-1, 2, 1, -4], and target = 1.
-
-The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
-
-

Solution

-
/**
- * @param {number[]} nums
- * @param {number} target
- * @return {number}
- */
-var threeSumClosest = function(nums, target) {
-  var len = nums.length;
-  var res = nums[0] + nums[1] + nums[2];
-  var sum = 0;
-  var l = 0;
-  var r = 0;
-  nums.sort((a, b) => (a - b));
-  for (var i = 0; i < len - 2; i++) {
-    if (i > 0 && nums[i] === nums[i - 1]) continue;
-    l = i + 1;
-    r = len - 1;
-    while (l < r) {
-      sum = nums[i] + nums[l] + nums[r];
-      if (sum < target) {
-        l++;
-      } else if (sum > target) {
-        r--;
-      } else {
-        return sum;
-      }
-      if (Math.abs(sum - target) < Math.abs(res - target)) res = sum;
-    }
-  }
-  return res;
-};
-
-

Explain:

-

see 3Sum.

-

Complexity:

-
    -
  • Time complexity : O(n^2).
  • -
  • Space complexity : O(1).
  • -
github
\ No newline at end of file diff --git a/docs/problem/3sum.html b/docs/problem/3sum.html deleted file mode 100644 index a5ed96f..0000000 --- a/docs/problem/3sum.html +++ /dev/null @@ -1,52 +0,0 @@ -3Sum - LeetCode javascript solutions

15. 3Sum

Difficulty:
Related Topics:

Problem

-

Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

-

Note:

-

The solution set must not contain duplicate triplets.

-

Example:

-
Given array nums = [-1, 0, 1, 2, -1, -4],
-
-A solution set is:
-[
-  [-1, 0, 1],
-  [-1, -1, 2]
-]
-
-

Solution

-
/**
- * @param {number[]} nums
- * @return {number[][]}
- */
-var threeSum = function(nums) {
-  var len = nums.length;
-  var res = [];
-  var l = 0;
-  var r = 0;
-  nums.sort((a, b) => (a - b));
-  for (var i = 0; i < len; i++) {
-    if (i > 0 && nums[i] === nums[i - 1]) continue;
-    l = i + 1;
-    r = len - 1;
-    while (l < r) {
-      if (nums[i] + nums[l] + nums[r] < 0) {
-        l++;
-      } else if (nums[i] + nums[l] + nums[r] > 0) {
-        r--;
-      } else {
-        res.push([nums[i], nums[l], nums[r]]);
-        while (l < r && nums[l] === nums[l + 1]) l++;
-        while (l < r && nums[r] === nums[r - 1]) r--;
-        l++;
-        r--;
-      }
-    }
-  }
-  return res;
-};
-
-

Explain:

-

先排序,用双指针求解,注意重复的数字。

-

Complexity:

-
    -
  • Time complexity : O(n^2).
  • -
  • Space complexity : O(1).
  • -
github
\ No newline at end of file diff --git a/docs/problem/4sum-ii.html b/docs/problem/4sum-ii.html deleted file mode 100644 index b96f1b0..0000000 --- a/docs/problem/4sum-ii.html +++ /dev/null @@ -1,55 +0,0 @@ -4Sum II - LeetCode javascript solutions

454. 4Sum II

Difficulty:
Similar Questions:

Problem

-

Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero.

-

To make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 500. All integers are in the range of -228 to 228 - 1 and the result is guaranteed to be at most 231 - 1.

-

Example:

-
Input:
-A = [ 1, 2]
-B = [-2,-1]
-C = [-1, 2]
-D = [ 0, 2]
-
-Output:
-2
-
-Explanation:
-The two tuples are:
-1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0
-2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0
-
-

Solution

-
/**
- * @param {number[]} A
- * @param {number[]} B
- * @param {number[]} C
- * @param {number[]} D
- * @return {number}
- */
-var fourSumCount = function(A, B, C, D) {
-  var map = {};
-  var res = 0;
-  var key = 0;
-
-  for (var i = 0; i < A.length; i++) {
-    for (var j = 0; j < B.length; j++) {
-      key = A[i] + B[j];
-      map[key] = (map[key] || 0) + 1;
-    }
-  }
-
-  for (var i = 0; i < C.length; i++) {
-    for (var j = 0; j < D.length; j++) {
-      key = - (C[i] + D[j]);
-      res += (map[key] || 0);
-    }
-  }
-
-  return res;
-};
-
-

Explain:

-

nope.

-

Complexity:

-
    -
  • Time complexity : O(n^2).
  • -
  • Space complexity : O(1).
  • -
github
\ No newline at end of file diff --git a/docs/problem/4sum.html b/docs/problem/4sum.html deleted file mode 100644 index 7c47905..0000000 --- a/docs/problem/4sum.html +++ /dev/null @@ -1,72 +0,0 @@ -4Sum - LeetCode javascript solutions

18. 4Sum

Difficulty:
Similar Questions:

Problem

-

Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

-

Note:

-

The solution set must not contain duplicate quadruplets.

-

Example:

-
Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.
-
-A solution set is:
-[
-  [-1,  0, 0, 1],
-  [-2, -1, 1, 2],
-  [-2,  0, 0, 2]
-]
-
-

Solution

-
/**
- * @param {number[]} nums
- * @param {number} target
- * @return {number[][]}
- */
-var fourSum = function(nums, target) {
-  if (nums.length < 4) return [];
-
-  var len = nums.length;
-  var res = [];
-  var l = 0;
-  var r = 0;
-  var sum = 0;
-
-  nums.sort((a, b) => (a - b));
-
-  for (var i = 0; i < len - 3; i++) {
-    if (i > 0 && nums[i] === nums[i - 1]) continue;
-    if (nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target) break;
-    if (nums[i] + nums[len - 1] + nums[len - 2] + nums[len - 3] < target) continue;
-
-    for (var j = i + 1; j < len - 2; j++) {
-      if (j > i + 1 && nums[j] === nums[j - 1]) continue;
-      if (nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > target) break;
-      if (nums[i] + nums[j] + nums[len - 1] + nums[len - 2] < target) continue;
-
-      l = j + 1;
-      r = len - 1;
-
-      while (l < r) {
-        sum = nums[i] + nums[j] + nums[l] + nums[r];
-
-        if (sum < target) {
-          l++;
-        } else if (sum > target) {
-          r--;
-        } else {
-          res.push([nums[i], nums[j], nums[l], nums[r]]);
-          while (l < r && nums[l] === nums[l + 1]) l++;
-          while (l < r && nums[r] === nums[r - 1]) r--;
-          l++;
-          r--;
-        }
-      }
-    }
-  }
-
-  return res;
-};
-
-

Explain:

-

see 3Sum.

-

Complexity:

-
    -
  • Time complexity : O(n^3).
  • -
  • Space complexity : O(1).
  • -
github
\ No newline at end of file diff --git a/docs/problem/add-binary.html b/docs/problem/add-binary.html deleted file mode 100644 index e30717e..0000000 --- a/docs/problem/add-binary.html +++ /dev/null @@ -1,43 +0,0 @@ -Add Binary - LeetCode javascript solutions

67. Add Binary

Difficulty:
Related Topics:

Problem

-

Given two binary strings, return their sum (also a binary string).

-

The input strings are both non-empty and contains only characters 1 or 0.

-

Example 1:

-
Input: a = "11", b = "1"
-Output: "100"
-
-

Example 2:

-
Input: a = "1010", b = "1011"
-Output: "10101"
-
-

Solution

-
/**
- * @param {string} a
- * @param {string} b
- * @return {string}
- */
-var addBinary = function(a, b) {
-  var len1 = a.length;
-  var len2 = b.length;
-  var max = Math.max(len1, len2);
-  var res = '';
-  var carry = 0;
-  var val = 0;
-
-  for (var i = 0; i < max; i++) {
-    val = Number(a[len1 - 1 - i] || 0) + Number(b[len2 - 1 - i] || 0) + carry;
-    carry = Math.floor(val / 2);
-    res = (val % 2) + res;
-  }
-
-  if (carry) res = 1 + res;
-
-  return res;
-};
-
-

Explain:

-

nope.

-

Complexity:

-
    -
  • Time complexity : O(n).
  • -
  • Space complexity : O(1).
  • -
github
\ No newline at end of file diff --git a/docs/problem/add-digits.html b/docs/problem/add-digits.html deleted file mode 100644 index e708869..0000000 --- a/docs/problem/add-digits.html +++ /dev/null @@ -1,26 +0,0 @@ -Add Digits - LeetCode javascript solutions

258. Add Digits

Difficulty:
Related Topics:
Similar Questions:

Problem

-

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

-

Example:

-
Input: 38
-Output: 2 
-Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2. 
-             Since 2 has only one digit, return it.
-
-

Follow up: -Could you do it without any loop/recursion in O(1) runtime?

-

Solution

-
/**
- * @param {number} num
- * @return {number}
- */
-var addDigits = function(num) {
-  return 1 + (num - 1) % 9;
-};
-
-

Explain:

-

结果只有一个数字,就是 1~9 ,不断循环,找规律即可。

-

Complexity:

-
    -
  • Time complexity : O(1).
  • -
  • Space complexity : O(1).
  • -
github
\ No newline at end of file diff --git a/docs/problem/add-one-row-to-tree.html b/docs/problem/add-one-row-to-tree.html deleted file mode 100644 index 67161c2..0000000 --- a/docs/problem/add-one-row-to-tree.html +++ /dev/null @@ -1,98 +0,0 @@ -Add One Row to Tree - LeetCode javascript solutions

623. Add One Row to Tree

Difficulty:
Related Topics:
Similar Questions:

    Problem

    -

    Given the root of a binary tree, then value v and depth d, you need to add a row of nodes with value v at the given depth d. The root node is at depth 1.

    -

    The adding rule is: given a positive integer depth d, for each NOT null tree nodes N in depth d-1, create two tree nodes with value v as N's left subtree root and right subtree root. And N's original left subtree should be the left subtree of the new left subtree root, its original right subtree should be the right subtree of the new right subtree root. If depth d is 1 that means there is no depth d-1 at all, then create a tree node with value v as the new root of the whole original tree, and the original tree is the new root's left subtree.

    -

    Example 1:

    -
    Input: 
    -A binary tree as following:
    -       4
    -     /   \
    -    2     6
    -   / \   / 
    -  3   1 5   
    -
    -v = 1
    -
    -d = 2
    -
    -Output: 
    -       4
    -      / \
    -     1   1
    -    /     \
    -   2       6
    -  / \     / 
    - 3   1   5   
    -
    -
    -

    Example 2:

    -
    Input: 
    -A binary tree as following:
    -      4
    -     /   
    -    2    
    -   / \   
    -  3   1    
    -
    -v = 1
    -
    -d = 3
    -
    -Output: 
    -      4
    -     /   
    -    2
    -   / \    
    -  1   1
    - /     \  
    -3       1
    -
    -

    Note:

    -
      -
    • The given d is in range [1, maximum depth of the given tree + 1].
    • -
    • The given binary tree has at least one tree node.
    • -
    -

    Solution

    -
    /**
    - * Definition for a binary tree node.
    - * function TreeNode(val) {
    - *     this.val = val;
    - *     this.left = this.right = null;
    - * }
    - */
    -/**
    - * @param {TreeNode} root
    - * @param {number} v
    - * @param {number} d
    - * @return {TreeNode}
    - */
    -var addOneRow = function(root, v, d) {
    -  var head = new TreeNode(0);
    -  head.left = root;
    -  helper(head, v, d, 1);
    -  return head.left;
    -};
    -
    -var helper = function (root, v, d, depth) {
    -  if (!root) return;
    -  if (depth === d) {
    -    insert(root, v, 'left');
    -    insert(root, v, 'right');
    -  } else {
    -    helper(root.left, v, d, depth + 1);
    -    helper(root.right, v, d, depth + 1);
    -  }
    -};
    -
    -var insert = function (root, val, type) {
    -  var node = new TreeNode(val);
    -  node[type] = root[type];
    -  root[type] = node;
    -};
    -
    -

    Explain:

    -

    nope.

    -

    Complexity:

    -
      -
    • Time complexity : O(n).
    • -
    • Space complexity : O(1).
    • -
    github
    \ No newline at end of file diff --git a/docs/problem/add-strings.html b/docs/problem/add-strings.html deleted file mode 100644 index 85dbb60..0000000 --- a/docs/problem/add-strings.html +++ /dev/null @@ -1,39 +0,0 @@ -Add Strings - LeetCode javascript solutions

    415. Add Strings

    Difficulty:
    Related Topics:

    Problem

    -

    Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.

    -

    Note:

    -
      -
    • The length of both num1 and num2 is < 5100.
    • -
    • Both num1 and num2 contains only digits 0-9.
    • -
    • Both num1 and num2 does not contain any leading zero.
    • -
    • You must not use any built-in BigInteger library or convert the inputs to integer directly.
    • -
    -

    Solution

    -
    /**
    - * @param {string} num1
    - * @param {string} num2
    - * @return {string}
    - */
    -var addStrings = function(num1, num2) {
    -    var len1 = num1.length;
    -    var len2 = num2.length;
    -    var max = Math.max(len1, len2);
    -    var res = Array(max);
    -    var carry = 0;
    -    var val = 0;
    -
    -    for (var i = 0; i < max; i++) {
    -        val = Number(num1[len1 - 1 - i] || 0) + Number(num2[len2 - 1 - i] || 0) + carry;
    -        carry = Math.floor(val / 10);
    -        res[max - 1 - i] = val % 10;
    -    }
    -
    -    return (carry || '') + res.join('');
    -};
    -
    -

    Explain:

    -

    nope.

    -

    Complexity:

    -
      -
    • Time complexity :
    • -
    • Space complexity :
    • -
    github
    \ No newline at end of file diff --git a/docs/problem/add-two-numbers.html b/docs/problem/add-two-numbers.html deleted file mode 100644 index 4f9dcaf..0000000 --- a/docs/problem/add-two-numbers.html +++ /dev/null @@ -1,47 +0,0 @@ -Add Two Numbers - LeetCode javascript solutions

    2. Add Two Numbers

    Difficulty:
    Related Topics:

    Problem

    -

    You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

    -

    You may assume the two numbers do not contain any leading zero, except the number 0 itself.

    -

    Example

    -
    Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
    -Output: 7 -> 0 -> 8
    -Explanation: 342 + 465 = 807.
    -
    -

    Solution

    -
    /**
    - * Definition for singly-linked list.
    - * function ListNode(val) {
    - *     this.val = val;
    - *     this.next = null;
    - * }
    - */
    -/**
    - * @param {ListNode} l1
    - * @param {ListNode} l2
    - * @return {ListNode}
    - */
    -var addTwoNumbers = function(l1, l2) {
    -  var carry = 0;
    -  var sum = 0;
    -  var head = new ListNode(0);
    -  var now = head;
    -  var a = l1;
    -  var b = l2;
    -  while (a !== null || b !== null) {
    -    sum = (a ? a.val : 0) + (b ? b.val : 0) + carry;
    -    carry = Math.floor(sum / 10);
    -    now.next = new ListNode(sum % 10);
    -    now = now.next;
    -    a = a ? a.next : null;
    -    b = b ? b.next : null;
    -  }
    -  if (carry) now.next = new ListNode(carry);
    -  return head.next;
    -};
    -
    -

    Explain:

    -

    nope.

    -

    Complexity:

    -
      -
    • Time complexity : O(max(m,n)).
    • -
    • Space complexity : O(max(m,n)).
    • -
    github
    \ No newline at end of file diff --git a/docs/problem/balanced-binary-tree.html b/docs/problem/balanced-binary-tree.html deleted file mode 100644 index 664a2b3..0000000 --- a/docs/problem/balanced-binary-tree.html +++ /dev/null @@ -1,55 +0,0 @@ -Balanced Binary Tree - LeetCode javascript solutions

    110. Balanced Binary Tree

    Difficulty:
    Related Topics:

    Problem

    -

    Given a binary tree, determine if it is height-balanced.

    -

    For this problem, a height-balanced binary tree is defined as:

    -

    a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

    -

    Example 1:

    -

    Given the following tree [3,9,20,null,null,15,7]:

    -
        3
    -   / \
    -  9  20
    -    /  \
    -   15   7
    -
    -

    Return true.

    -

    Example 2:

    -

    Given the following tree [1,2,2,3,3,null,null,4,4]:

    -
           1
    -      / \
    -     2   2
    -    / \
    -   3   3
    -  / \
    - 4   4
    -
    -

    Return false.

    -

    Solution

    -
    /**
    - * Definition for a binary tree node.
    - * function TreeNode(val) {
    - *     this.val = val;
    - *     this.left = this.right = null;
    - * }
    - */
    -/**
    - * @param {TreeNode} root
    - * @return {boolean}
    - */
    -var isBalanced = function(root) {
    -  return helper(root, 0) >= 0;
    -};
    -
    -var helper = function (root, depth) {
    -  if (!root) return depth;
    -  var left = helper(root.left, depth + 1);
    -  var right = helper(root.right, depth + 1);
    -  if (left === -1 || right === -1 || Math.abs(left - right) > 1) return -1;
    -  return Math.max(left, right);
    -};
    -
    -

    Explain:

    -

    nope.

    -

    Complexity:

    -
      -
    • Time complexity : O(n).
    • -
    • Space complexity : O(n).
    • -
    github
    \ No newline at end of file diff --git a/docs/problem/best-time-to-buy-and-sell-stock-ii.html b/docs/problem/best-time-to-buy-and-sell-stock-ii.html deleted file mode 100644 index 949151a..0000000 --- a/docs/problem/best-time-to-buy-and-sell-stock-ii.html +++ /dev/null @@ -1,43 +0,0 @@ -Best Time to Buy and Sell Stock II - LeetCode javascript solutions

    122. Best Time to Buy and Sell Stock II

    Difficulty:
    Related Topics:

    Problem

    -

    Say you have an array for which the ith element is the price of a given stock on day i.

    -

    Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).

    -

    Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

    -

    Example 1:

    -
    Input: [7,1,5,3,6,4]
    -Output: 7
    -Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
    -             Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
    -
    -

    Example 2:

    -
    Input: [1,2,3,4,5]
    -Output: 4
    -Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
    -             Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
    -             engaging multiple transactions at the same time. You must sell before buying again.
    -
    -

    Example 3:

    -
    Input: [7,6,4,3,1]
    -Output: 0
    -Explanation: In this case, no transaction is done, i.e. max profit = 0.
    -
    -

    Solution

    -
    /**
    - * @param {number[]} prices
    - * @return {number}
    - */
    -var maxProfit = function(prices) {
    -  var max = 0;
    -  var len = prices.length;
    -  for (var i = 1; i < len; i++) {
    -    if (prices[i] > prices[i - 1]) max += prices[i] - prices[i - 1];
    -  }
    -  return max;
    -};
    -
    -

    Explain:

    -

    无限次的买入抛出,把所有上升的价格当做利润就好。即每次低的时候买入,高的时候抛出。

    -

    Complexity:

    -
      -
    • Time complexity : O(n).
    • -
    • Space complexity : O(1).
    • -
    github
    \ No newline at end of file diff --git a/docs/problem/best-time-to-buy-and-sell-stock-iii.html b/docs/problem/best-time-to-buy-and-sell-stock-iii.html deleted file mode 100644 index 8c8234e..0000000 --- a/docs/problem/best-time-to-buy-and-sell-stock-iii.html +++ /dev/null @@ -1,49 +0,0 @@ -Best Time to Buy and Sell Stock III - LeetCode javascript solutions

    123. Best Time to Buy and Sell Stock III

    Difficulty:

    Problem

    -

    Say you have an array for which the ith element is the price of a given stock on day i.

    -

    Design an algorithm to find the maximum profit. You may complete at most two transactions.

    -

    **Note: **You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

    -

    Example 1:

    -
    Input: [3,3,5,0,0,3,1,4]
    -Output: 6
    -Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
    -             Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.
    -
    -

    Example 2:

    -
    Input: [1,2,3,4,5]
    -Output: 4
    -Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
    -             Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
    -             engaging multiple transactions at the same time. You must sell before buying again.
    -
    -

    Example 3:

    -
    Input: [7,6,4,3,1]
    -Output: 0
    -Explanation: In this case, no transaction is done, i.e. max profit = 0.
    -
    -

    Solution

    -
    /**
    - * @param {number[]} prices
    - * @return {number}
    - */
    -var maxProfit = function(prices) {
    -  var buy1 = Number.MIN_SAFE_INTEGER;
    -  var sell1 = 0;
    -  var buy2 = Number.MIN_SAFE_INTEGER;
    -  var sell2 = 0;
    -  var len = prices.length;
    -  for (var i = 0; i < len; i++) {
    -    buy1 = Math.max(buy1, -prices[i]);
    -    sell1 = Math.max(sell1, buy1 + prices[i]);
    -    buy2 = Math.max(buy2, sell1 - prices[i]);
    -    sell2 = Math.max(sell2, buy2 + prices[i]);
    -  }
    -  return sell2;
    -};
    -
    -

    Explain:

    -

    重点就是让 -buy1 + sell1 - buy2 + sell2 最大。

    -

    Complexity:

    -
      -
    • Time complexity : O(n).
    • -
    • Space complexity : O(1).
    • -
    github
    \ No newline at end of file diff --git a/docs/problem/best-time-to-buy-and-sell-stock.html b/docs/problem/best-time-to-buy-and-sell-stock.html deleted file mode 100644 index 90aad6e..0000000 --- a/docs/problem/best-time-to-buy-and-sell-stock.html +++ /dev/null @@ -1,38 +0,0 @@ -Best Time to Buy and Sell Stock - LeetCode javascript solutions

    121. Best Time to Buy and Sell Stock

    Difficulty:

    Problem

    -

    Say you have an array for which the ith element is the price of a given stock on day i.

    -

    If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

    -

    Note that you cannot sell a stock before you buy one.

    -

    Example 1:

    -
    Input: [7,1,5,3,6,4]
    -Output: 5
    -Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
    -             Not 7-1 = 6, as selling price needs to be larger than buying price.
    -
    -

    Example 2:

    -
    Input: [7,6,4,3,1]
    -Output: 0
    -Explanation: In this case, no transaction is done, i.e. max profit = 0.
    -
    -

    Solution

    -
    /**
    - * @param {number[]} prices
    - * @return {number}
    - */
    -var maxProfit = function(prices) {
    -  var n = prices.length;
    -  var minPrice = Number.MAX_SAFE_INTEGER;
    -  var maxProfit = 0;
    -  for (var i = 0; i < n; i++) {
    -    if (prices[i] < minPrice) minPrice = prices[i];
    -    else if (prices[i] - minPrice > maxProfit) maxProfit = prices[i] - minPrice;
    -  }
    -  return maxProfit;
    -};
    -
    -

    Explain:

    -

    nope.

    -

    Complexity:

    -
      -
    • Time complexity : O(n).
    • -
    • Space complexity : O(1).
    • -
    github
    \ No newline at end of file diff --git a/docs/problem/binary-search-tree-iterator.html b/docs/problem/binary-search-tree-iterator.html deleted file mode 100644 index 08f2348..0000000 --- a/docs/problem/binary-search-tree-iterator.html +++ /dev/null @@ -1,62 +0,0 @@ -Binary Search Tree Iterator - LeetCode javascript solutions

    173. Binary Search Tree Iterator

    Difficulty:
    Related Topics:

    Problem

    -

    Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.

    -

    Calling next() will return the next smallest number in the BST.

    -

    Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.

    -

    Credits:Special thanks to @ts for adding this problem and creating all test cases.

    -

    Solution

    -
    /**
    - * Definition for binary tree
    - * function TreeNode(val) {
    - *     this.val = val;
    - *     this.left = this.right = null;
    - * }
    - */
    -
    -/**
    - * @constructor
    - * @param {TreeNode} root - root of the binary search tree
    - */
    -var BSTIterator = function(root) {
    -  this.stack = [];
    -  this.pushAll(root);
    -};
    -
    -
    -/**
    - * @this BSTIterator
    - * @returns {boolean} - whether we have a next smallest number
    - */
    -BSTIterator.prototype.hasNext = function() {
    -  return this.stack.length !== 0;
    -};
    -
    -/**
    - * @this BSTIterator
    - * @returns {number} - the next smallest number
    - */
    -BSTIterator.prototype.next = function() {
    -  var node = this.stack.pop();
    -  this.pushAll(node.right);
    -  return node.val;
    -};
    -
    -/**
    - * Your BSTIterator will be called like this:
    - * var i = new BSTIterator(root), a = [];
    - * while (i.hasNext()) a.push(i.next());
    -*/
    -
    -BSTIterator.prototype.pushAll = function (node) {
    -  while (node) {
    -    this.stack.push(node);
    -    node = node.left;
    -  }
    -};
    -
    -

    Explain:

    -

    nope.

    -

    Complexity:

    -
      -
    • Time complexity :
    • -
    • Space complexity :
    • -
    github
    \ No newline at end of file diff --git a/docs/problem/binary-tree-inorder-traversal.html b/docs/problem/binary-tree-inorder-traversal.html deleted file mode 100644 index 94385be..0000000 --- a/docs/problem/binary-tree-inorder-traversal.html +++ /dev/null @@ -1,82 +0,0 @@ -Binary Tree Inorder Traversal - LeetCode javascript solutions

    94. Binary Tree Inorder Traversal

    Difficulty:
    Related Topics:

    Problem

    -

    Given a binary tree, return the inorder traversal of its nodes' values.

    -

    Example:

    -
    Input: [1,null,2,3]
    -   1
    -    \
    -     2
    -    /
    -   3
    -
    -Output: [1,3,2]
    -
    -

    Follow up: Recursive solution is trivial, could you do it iteratively?

    -

    Solution 1

    -
    /**
    - * Definition for a binary tree node.
    - * function TreeNode(val) {
    - *     this.val = val;
    - *     this.left = this.right = null;
    - * }
    - */
    -/**
    - * @param {TreeNode} root
    - * @return {number[]}
    - */
    -var inorderTraversal = function(root) {
    -  var res = [];
    -  helper(root, res);
    -  return res;
    -};
    -
    -var helper = function (root, res) {
    -  if (!root) return;
    -  if (root.left) helper(root.left, res);
    -  res.push(root.val);
    -  if (root.right) helper(root.right, res);
    -};
    -
    -

    Explain:

    -

    nope.

    -

    Complexity:

    -
      -
    • Time complexity : O(n).
    • -
    • Space complexity : O(n).
    • -
    -

    Solution 2

    -
    /**
    - * Definition for a binary tree node.
    - * function TreeNode(val) {
    - *     this.val = val;
    - *     this.left = this.right = null;
    - * }
    - */
    -/**
    - * @param {TreeNode} root
    - * @return {number[]}
    - */
    -var inorderTraversal = function(root) {
    -  var stack = [];
    -  var now = root;
    -  var res = [];
    -
    -  while (now || stack.length) {
    -    while (now) {
    -      stack.push(now);
    -      now = now.left;
    -    }
    -    now = stack.pop();
    -    res.push(now.val);
    -    now = now.right;
    -  }
    -
    -  return res;
    -};
    -
    -

    Explain:

    -

    nope.

    -

    Complexity:

    -
      -
    • Time complexity : O(n).
    • -
    • Space complexity : O(n).
    • -
    github
    \ No newline at end of file diff --git a/docs/problem/binary-tree-level-order-traversal-ii.html b/docs/problem/binary-tree-level-order-traversal-ii.html deleted file mode 100644 index b0d7e44..0000000 --- a/docs/problem/binary-tree-level-order-traversal-ii.html +++ /dev/null @@ -1,159 +0,0 @@ -Binary Tree Level Order Traversal II - LeetCode javascript solutions

    107. Binary Tree Level Order Traversal II

    Difficulty:

    Problem

    -

    Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).

    -

    For example: -Given binary tree [3,9,20,null,null,15,7],

    -
        3
    -   / \
    -  9  20
    -    /  \
    -   15   7
    -
    -

    return its bottom-up level order traversal as:

    -
    [
    -  [15,7],
    -  [9,20],
    -  [3]
    -]
    -
    -

    Solution 1

    -
    /**
    - * Definition for a binary tree node.
    - * function TreeNode(val) {
    - *     this.val = val;
    - *     this.left = this.right = null;
    - * }
    - */
    -/**
    - * @param {TreeNode} root
    - * @return {number[][]}
    - */
    -var levelOrderBottom = function(root) {
    -  var res = [];
    -  helper(root, 0, res);
    -  return res.reverse();
    -};
    -
    -var helper = function (root, level, res) {
    -  if (!root) return;
    -  if (!res[level]) res[level] = [];
    -  res[level].push(root.val);
    -  helper(root.left, level + 1, res);
    -  helper(root.right, level + 1, res);
    -};
    -
    -

    Explain:

    -

    nope.

    -

    Complexity:

    -
      -
    • Time complexity : O(n).
    • -
    • Space complexity : O(n).
    • -
    -

    Solution 2

    -
    /**
    - * Definition for a binary tree node.
    - * function TreeNode(val) {
    - *     this.val = val;
    - *     this.left = this.right = null;
    - * }
    - */
    -/**
    - * @param {TreeNode} root
    - * @return {number[][]}
    - */
    -var levelOrderBottom = function(root) {
    -  var res = [];
    -  helper(root, 0, res);
    -  return res;
    -};
    -
    -var helper = function (root, level, res) {
    -  if (!root) return;
    -  if (res.length < level + 1) res.unshift([]);
    -  res[res.length - level - 1].push(root.val);
    -  helper(root.left, level + 1, res);
    -  helper(root.right, level + 1, res);
    -};
    -
    -

    Explain:

    -

    nope.

    -

    Complexity:

    -
      -
    • Time complexity : O(n).
    • -
    • Space complexity : O(n).
    • -
    -

    Solution 3

    -
    /**
    - * Definition for a binary tree node.
    - * function TreeNode(val) {
    - *     this.val = val;
    - *     this.left = this.right = null;
    - * }
    - */
    -/**
    - * @param {TreeNode} root
    - * @return {number[][]}
    - */
    -var levelOrderBottom = function(root) {
    -  var res = [];
    -  var stack = [[root, 0]];
    -  var level = 0;
    -  var node = null;
    -
    -  while (stack.length) {
    -    [node, level] = stack.pop();
    -    if (node) {
    -      if (res.length < level + 1) res.unshift([]);
    -      res[res.length - level - 1].push(node.val);
    -      stack.push([node.right, level + 1]);
    -      stack.push([node.left, level + 1]);
    -    }
    -  }
    -
    -  return res;
    -};
    -
    -

    Explain:

    -

    nope.

    -

    Complexity:

    -
      -
    • Time complexity : O(n).
    • -
    • Space complexity : O(n).
    • -
    -

    Solution 4

    -
    /**
    - * Definition for a binary tree node.
    - * function TreeNode(val) {
    - *     this.val = val;
    - *     this.left = this.right = null;
    - * }
    - */
    -/**
    - * @param {TreeNode} root
    - * @return {number[][]}
    - */
    -var levelOrderBottom = function(root) {
    -  var res = [];
    -  var queue = [[root, 0]];
    -  var level = 0;
    -  var node = null;
    -
    -  while (queue.length) {
    -    [node, level] = queue.shift();
    -    if (node) {
    -      if (res.length < level + 1) res.unshift([]);
    -      res[res.length - level - 1].push(node.val);
    -      queue.push([node.left, level + 1]);
    -      queue.push([node.right, level + 1]);
    -    }
    -  }
    -
    -  return res;
    -};
    -
    -

    Explain:

    -

    nope.

    -

    Complexity:

    -
      -
    • Time complexity : O(n).
    • -
    • Space complexity : O(n).
    • -
    github
    \ No newline at end of file diff --git a/docs/problem/binary-tree-level-order-traversal.html b/docs/problem/binary-tree-level-order-traversal.html deleted file mode 100644 index 454f0ef..0000000 --- a/docs/problem/binary-tree-level-order-traversal.html +++ /dev/null @@ -1,92 +0,0 @@ -Binary Tree Level Order Traversal - LeetCode javascript solutions

    102. Binary Tree Level Order Traversal

    Difficulty:

    Problem

    -

    Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

    -

    For example: -Given binary tree [3,9,20,null,null,15,7],

    -
        3
    -   / \
    -  9  20
    -    /  \
    -   15   7
    -
    -

    return its level order traversal as:

    -
    [
    -  [3],
    -  [9,20],
    -  [15,7]
    -]
    -
    -

    Solution 1

    -
    /**
    - * Definition for a binary tree node.
    - * function TreeNode(val) {
    - *     this.val = val;
    - *     this.left = this.right = null;
    - * }
    - */
    -/**
    - * @param {TreeNode} root
    - * @return {number[][]}
    - */
    -var levelOrder = function(root) {
    -  if (!root) return [];
    -  return helper([[root]], 0);
    -};
    -
    -var helper = function (res, level) {
    -  var now = res[level];
    -  var next = [];
    -
    -  for (var i = 0; i < now.length; i++) {
    -    if (now[i].left) next.push(now[i].left);
    -    if (now[i].right) next.push(now[i].right);
    -    now[i] = now[i].val;
    -  }
    -
    -  if (next.length) {
    -    res.push(next);
    -    helper(res, level + 1);
    -  }
    -
    -  return res;
    -};
    -
    -

    Explain:

    -

    bfs

    -

    Complexity:

    -
      -
    • Time complexity : O(n).
    • -
    • Space complexity : O(n).
    • -
    -

    Solution 2

    -
    /**
    - * Definition for a binary tree node.
    - * function TreeNode(val) {
    - *     this.val = val;
    - *     this.left = this.right = null;
    - * }
    - */
    -/**
    - * @param {TreeNode} root
    - * @return {number[][]}
    - */
    -var levelOrder = function(root) {
    -  return helper([], root, 0);
    -};
    -
    -var helper = function (res, root, level) {
    -  if (root) {
    -    if (!res[level]) res[level] = [];
    -    res[level].push(root.val);
    -    helper(res, root.left, level + 1);
    -    helper(res, root.right, level + 1);
    -  }
    -  return res;
    -};
    -
    -

    Explain:

    -

    dfs

    -

    Complexity:

    -
      -
    • Time complexity : O(n).
    • -
    • Space complexity : O(n).
    • -
    github
    \ No newline at end of file diff --git a/docs/problem/binary-tree-maximum-path-sum.html b/docs/problem/binary-tree-maximum-path-sum.html deleted file mode 100644 index 0a2ee5d..0000000 --- a/docs/problem/binary-tree-maximum-path-sum.html +++ /dev/null @@ -1,56 +0,0 @@ -Binary Tree Maximum Path Sum - LeetCode javascript solutions

    124. Binary Tree Maximum Path Sum

    Difficulty:
    Related Topics:

    Problem

    -

    Given a non-empty binary tree, find the maximum path sum.

    -

    For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.

    -

    Example 1:

    -
    Input: [1,2,3]
    -
    -       1
    -      / \
    -     2   3
    -
    -Output: 6
    -
    -

    Example 2:

    -
    Input: [-10,9,20,null,null,15,7]
    -
    -   -10
    -   / \
    -  9  20
    -    /  \
    -   15   7
    -
    -Output: 42
    -
    -

    Solution

    -
    /**
    - * Definition for a binary tree node.
    - * function TreeNode(val) {
    - *     this.val = val;
    - *     this.left = this.right = null;
    - * }
    - */
    -/**
    - * @param {TreeNode} root
    - * @return {number}
    - */
    -var maxPathSum = function(root) {
    -  var max = Number.MIN_SAFE_INTEGER;
    -  var maxSum = function (node) {
    -    if (!node) return 0;
    -    var left = Math.max(maxSum(node.left), 0);
    -    var right = Math.max(maxSum(node.right), 0);
    -    max = Math.max(left + right + node.val, max);
    -    return Math.max(left, right) + node.val;
    -  };
    -  maxSum(root);
    -  return max;
    -};
    -
    -

    Explain:

    -

    注意此题找的是路径 path,你用到的节点需要连通在一条路上。 -所以 return Math.max(left, right) + node.val 而不是 return left + right + node.val

    -

    Complexity:

    -
      -
    • Time complexity : O(n).
    • -
    • Space complexity : O(n).
    • -
    github
    \ No newline at end of file diff --git a/docs/problem/binary-tree-postorder-traversal.html b/docs/problem/binary-tree-postorder-traversal.html deleted file mode 100644 index 05f1ac2..0000000 --- a/docs/problem/binary-tree-postorder-traversal.html +++ /dev/null @@ -1,82 +0,0 @@ -Binary Tree Postorder Traversal - LeetCode javascript solutions

    145. Binary Tree Postorder Traversal

    Difficulty:
    Related Topics:

    Problem

    -

    Given a binary tree, return the postorder traversal of its nodes' values.

    -

    Example:

    -
    Input: [1,null,2,3]
    -   1
    -    \
    -     2
    -    /
    -   3
    -
    -Output: [3,2,1]
    -
    -

    Follow up: Recursive solution is trivial, could you do it iteratively?

    -

    Solution 1

    -
    /**
    - * Definition for a binary tree node.
    - * function TreeNode(val) {
    - *     this.val = val;
    - *     this.left = this.right = null;
    - * }
    - */
    -/**
    - * @param {TreeNode} root
    - * @return {number[]}
    - */
    -var postorderTraversal = function(root) {
    -  var res = [];
    -  helper(root, res);
    -  return res;
    -};
    -
    -var helper = function (root, res) {
    -  if (!root) return;
    -  helper(root.left, res);
    -  helper(root.right, res);
    -  res.push(root.val);
    -};
    -
    -

    Explain:

    -

    nope.

    -

    Complexity:

    -
      -
    • Time complexity : O(n).
    • -
    • Space complexity : O(n).
    • -
    -

    Solution 2

    -
    /**
    - * Definition for a binary tree node.
    - * function TreeNode(val) {
    - *     this.val = val;
    - *     this.left = this.right = null;
    - * }
    - */
    -/**
    - * @param {TreeNode} root
    - * @return {number[]}
    - */
    -var postorderTraversal = function(root) {
    -  if (!root) return [];
    -  var res = [];
    -  var stack = [];
    -  var node = root;
    -  while (node || stack.length) {
    -    if (node) {
    -      stack.push(node);
    -      res.unshift(node.val);
    -      node = node.right;
    -    } else {
    -      node = stack.pop();
    -      node = node.left;
    -    }
    -  }
    -  return res;
    -};
    -
    -

    Explain:

    -

    nope.

    -

    Complexity:

    -
      -
    • Time complexity : O(n).
    • -
    • Space complexity : O(n).
    • -
    github
    \ No newline at end of file diff --git a/docs/problem/binary-tree-preorder-traversal.html b/docs/problem/binary-tree-preorder-traversal.html deleted file mode 100644 index bcf6474..0000000 --- a/docs/problem/binary-tree-preorder-traversal.html +++ /dev/null @@ -1,78 +0,0 @@ -Binary Tree Preorder Traversal - LeetCode javascript solutions

    144. Binary Tree Preorder Traversal

    Difficulty:
    Related Topics:

    Problem

    -

    Given a binary tree, return the preorder traversal of its nodes' values.

    -

    Example:

    -
    Input: [1,null,2,3]
    -   1
    -    \
    -     2
    -    /
    -   3
    -
    -Output: [1,2,3]
    -
    -

    Follow up: Recursive solution is trivial, could you do it iteratively?

    -

    Solution 1

    -
    /**
    - * Definition for a binary tree node.
    - * function TreeNode(val) {
    - *     this.val = val;
    - *     this.left = this.right = null;
    - * }
    - */
    -/**
    - * @param {TreeNode} root
    - * @return {number[]}
    - */
    -var preorderTraversal = function(root) {
    -  var res = [];
    -  helper(root, res);
    -  return res;
    -};
    -
    -var helper = function (root, res) {
    -  if (!root) return;
    -  res.push(root.val);
    -  helper(root.left, res);
    -  helper(root.right, res);
    -};
    -
    -

    Explain:

    -

    nope.

    -

    Complexity:

    -
      -
    • Time complexity : O(n).
    • -
    • Space complexity : O(n).
    • -
    -

    Solution 2

    -
    /**
    - * Definition for a binary tree node.
    - * function TreeNode(val) {
    - *     this.val = val;
    - *     this.left = this.right = null;
    - * }
    - */
    -/**
    - * @param {TreeNode} root
    - * @return {number[]}
    - */
    -var preorderTraversal = function(root) {
    -  if (!root) return [];
    -  var res = [];
    -  var queue = [root];
    -  var node = null;
    -  while (queue.length) {
    -    node = queue.pop();
    -    res.push(node.val);
    -    if (node.right) queue.push(node.right);
    -    if (node.left) queue.push(node.left);
    -  }
    -  return res;
    -};
    -
    -

    Explain:

    -

    nope.

    -

    Complexity:

    -
      -
    • Time complexity : O(n).
    • -
    • Space complexity : O(n).
    • -
    github
    \ No newline at end of file diff --git a/docs/problem/binary-tree-right-side-view.html b/docs/problem/binary-tree-right-side-view.html deleted file mode 100644 index f430fe2..0000000 --- a/docs/problem/binary-tree-right-side-view.html +++ /dev/null @@ -1,77 +0,0 @@ -Binary Tree Right Side View - LeetCode javascript solutions

    199. Binary Tree Right Side View

    Difficulty:

    Problem

    -

    Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

    -

    Example:

    -
    Input: [1,2,3,null,5,null,4]
    -Output: [1, 3, 4]
    -Explanation:
    -
    -   1            <---
    - /   \
    -2     3         <---
    - \     \
    -  5     4       <---
    -
    -

    Solution 1

    -
    /**
    - * Definition for a binary tree node.
    - * function TreeNode(val) {
    - *     this.val = val;
    - *     this.left = this.right = null;
    - * }
    - */
    -/**
    - * @param {TreeNode} root
    - * @return {number[]}
    - */
    -var rightSideView = function(root) {
    -  var queue = [{ node: root, level: 0 }];
    -  var result = [];
    -  var now = null;
    -  while (now = queue.shift()) {
    -    if (!now.node) continue;
    -    result[now.level] = now.node.val;
    -    queue.push({ node: now.node.left, level: now.level + 1 });
    -    queue.push({ node: now.node.right, level: now.level + 1 });
    -  }
    -  return result;
    -};
    -
    -

    Explain:

    -

    nope.

    -

    Complexity:

    -
      -
    • Time complexity : O(n).
    • -
    • Space complexity : O(n).
    • -
    -

    Solution 2

    -
    /**
    - * Definition for a binary tree node.
    - * function TreeNode(val) {
    - *     this.val = val;
    - *     this.left = this.right = null;
    - * }
    - */
    -/**
    - * @param {TreeNode} root
    - * @return {number[]}
    - */
    -var rightSideView = function(root) {
    -  var result = [];
    -  helper(root, 0, result);
    -  return result;
    -};
    -
    -var helper = function (node, level, result) {
    -  if (!node) return;
    -  result[level] = node.val;
    -  helper(node.left, level + 1, result);
    -  helper(node.right, level + 1, result);
    -};
    -
    -

    Explain:

    -

    nope.

    -

    Complexity:

    -
      -
    • Time complexity : O(n).
    • -
    • Space complexity : O(n).
    • -
    github
    \ No newline at end of file diff --git a/docs/problem/binary-tree-zigzag-level-order-traversal.html b/docs/problem/binary-tree-zigzag-level-order-traversal.html deleted file mode 100644 index 4e2eb64..0000000 --- a/docs/problem/binary-tree-zigzag-level-order-traversal.html +++ /dev/null @@ -1,65 +0,0 @@ -Binary Tree Zigzag Level Order Traversal - LeetCode javascript solutions

    103. Binary Tree Zigzag Level Order Traversal

    Difficulty:

    Problem

    -

    Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).

    -

    For example: -Given binary tree [3,9,20,null,null,15,7],

    -
        3
    -   / \
    -  9  20
    -    /  \
    -   15   7
    -
    -

    return its zigzag level order traversal as:

    -
    [
    -  [3],
    -  [20,9],
    -  [15,7]
    -]
    -
    -

    Solution

    -
    /**
    - * Definition for a binary tree node.
    - * function TreeNode(val) {
    - *     this.val = val;
    - *     this.left = this.right = null;
    - * }
    - */
    -/**
    - * @param {TreeNode} root
    - * @return {number[][]}
    - */
    -var zigzagLevelOrder = function(root) {
    -  if (!root) return [];
    -  return helper([[root]], 0);
    -};
    -
    -var helper = function (res, level) {
    -  var now = res[level];
    -  var next = [];
    -
    -  for (var i = now.length - 1; i >= 0; i--) {
    -    if (level % 2) {
    -      if (now[i].left) next.push(now[i].left);
    -      if (now[i].right) next.push(now[i].right);
    -    } else {
    -      if (now[i].right) next.push(now[i].right);
    -      if (now[i].left) next.push(now[i].left);
    -    }
    -
    -    now[i] = now[i].val;
    -  }
    -
    -  if (next.length) {
    -    res.push(next);
    -    helper(res, level + 1);
    -  }
    -
    -  return res;
    -};
    -
    -

    Explain:

    -

    nope.

    -

    Complexity:

    -
      -
    • Time complexity : O(n).
    • -
    • Space complexity : O(n).
    • -
    github
    \ No newline at end of file diff --git a/docs/problem/binary-watch.html b/docs/problem/binary-watch.html deleted file mode 100644 index 6129f4b..0000000 --- a/docs/problem/binary-watch.html +++ /dev/null @@ -1,84 +0,0 @@ -Binary Watch - LeetCode javascript solutions

    401. Binary Watch

    Difficulty:

    Problem

    -

    A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59). -Each LED represents a zero or one, with the least significant bit on the right.

    -

    -

    For example, the above binary watch reads "3:25".

    -

    Given a non-negative integer n which represents the number of LEDs that are currently on, return all possible times the watch could represent.

    -

    Example:

    -
    Input: n = 1Return: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"]
    -
    -

    Note:

    -
      -
    • The order of output does not matter.
    • -
    • The hour must not contain a leading zero, for example "01:00" is not valid, it should be "1:00".
    • -
    • The minute must be consist of two digits and may contain a leading zero, for example "10:2" is not valid, it should be "10:02".
    • -
    -

    Solution 1

    -
    /**
    - * @param {number} num
    - * @return {string[]}
    - */
    -var readBinaryWatch = function(num) {
    -  var res = [];
    -  helper(num, 0, 0, res, 0);
    -  return res;
    -};
    -
    -var helper = function (num, hours, minute, res, index) {
    -  if (num < 0 || index > 10 || hours > 11 || minute > 59) {
    -    return;
    -  } else if (num === 0) {
    -    res.push(hours + ':' + (minute < 10 ? ('0' + minute) : minute));
    -  } else if (index < 4) {
    -    helper(num - 1, hours + Math.pow(2, index), minute, res, index + 1);
    -    helper(num, hours, minute, res, index + 1);
    -  } else if (index >= 4) {
    -    helper(num - 1, hours, minute + Math.pow(2, index - 4), res, index + 1);
    -    helper(num, hours, minute, res, index + 1);
    -  }
    -};
    -
    -

    Explain:

    -

    nope.

    -

    Complexity:

    -
      -
    • Time complexity :
    • -
    • Space complexity :
    • -
    -

    Solution 2

    -
    /**
    - * @param {number} num
    - * @return {string[]}
    - */
    -var readBinaryWatch = function(num) {
    -  var res = [];
    -  for (var i = 0; i < 12; i++) {
    -    for (var j = 0; j < 60; j++) {
    -      if (numberOfDigit(i) + numberOfDigit(j) === num) {
    -        res.push(i + ':' + (j < 10 ? ('0' + j) : j));
    -      }
    -    }
    -  }
    -  return res;
    -};
    -
    -var numberOfDigit = function (num) {
    -  var n = 0;
    -  var tmp = 0;
    -  for (var i = 5; i >= 0; i--) {
    -    tmp = 1 << i;
    -    if (num >= tmp) {
    -      n++;
    -      num -= tmp;
    -    }
    -  }
    -  return n;
    -};
    -
    -

    Explain:

    -

    nope.

    -

    Complexity:

    -
      -
    • Time complexity :
    • -
    • Space complexity :
    • -
    github
    \ No newline at end of file diff --git a/docs/problem/candy.html b/docs/problem/candy.html deleted file mode 100644 index 6d05cec..0000000 --- a/docs/problem/candy.html +++ /dev/null @@ -1,47 +0,0 @@ -Candy - LeetCode javascript solutions

    135. Candy

    Difficulty:
    Related Topics:
    Similar Questions:

      Problem

      -

      There are N children standing in a line. Each child is assigned a rating value.

      -

      You are giving candies to these children subjected to the following requirements:

      -
        -
      • Each child must have at least one candy.
      • -
      • Children with a higher rating get more candies than their neighbors.
      • -
      -

      What is the minimum candies you must give?

      -

      Example 1:

      -
      Input: [1,0,2]
      -Output: 5
      -Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.
      -
      -

      Example 2:

      -
      Input: [1,2,2]
      -Output: 4
      -Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
      -             The third child gets 1 candy because it satisfies the above two conditions.
      -
      -

      Solution

      -
      /**
      - * @param {number[]} ratings
      - * @return {number}
      - */
      -var candy = function(ratings) {
      -  var len = ratings.length;
      -  var res = [];
      -  var sum = 0;
      -  for (var i = 0; i < len; i++) {
      -    res.push((i !== 0 && ratings[i] > ratings[i - 1]) ? (res[i - 1] + 1) : 1);
      -  }
      -  for (var j = len - 1; j >= 0; j--) {
      -    if (j !== len - 1 && ratings[j] > ratings[j + 1]) res[j] = Math.max(res[j], res[j + 1] + 1);
      -    sum += res[j];
      -  }
      -  return sum;
      -};
      -
      -

      Explain:

      -

      分两次循环:第一次从左到右,上升的依次加 1,下降或者相等的填 1; 第二次从右到左,上升的依次加 1,下降或者相等的不管。

      -

      注意最高点可能之前填充过,需要取 max 值,才能同时满足两边的需求

      -

      第二次处理完后计算总和,省得另开一个循环

      -

      Complexity:

      -
        -
      • Time complexity : O(n).
      • -
      • Space complexity : O(n).
      • -
      github
      \ No newline at end of file diff --git a/docs/problem/climbing-stairs.html b/docs/problem/climbing-stairs.html deleted file mode 100644 index 34ba5c3..0000000 --- a/docs/problem/climbing-stairs.html +++ /dev/null @@ -1,39 +0,0 @@ -Climbing Stairs - LeetCode javascript solutions

      70. Climbing Stairs

      Difficulty:
      Related Topics:
      Similar Questions:

      Problem

      -

      You are climbing a stair case. It takes n steps to reach to the top.

      -

      Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

      -

      Note: Given n will be a positive integer.

      -

      Example 1:

      -
      Input: 2
      -Output: 2
      -Explanation: There are two ways to climb to the top.
      -1. 1 step + 1 step
      -2. 2 steps
      -
      -

      Example 2:

      -
      Input: 3
      -Output: 3
      -Explanation: There are three ways to climb to the top.
      -1. 1 step + 1 step + 1 step
      -2. 1 step + 2 steps
      -3. 2 steps + 1 step
      -
      -

      Solution

      -
      /**
      - * @param {number} n
      - * @return {number}
      - */
      -var climbStairs = function(n) {
      -  var dp = [0, 1];
      -  for (var i = 0; i < n; i++) {
      -    dp = [dp[1], dp[0] + dp[1]];
      -  }
      -  return dp[1];
      -};
      -
      -

      Explain:

      -

      f(x) = f(x - 1) + f(x - 2)。这里用了滚动数组,只保留前两个值,注意处理 n = 0, 1, 2 时的特殊情况。

      -

      Complexity:

      -
        -
      • Time complexity : O(n).
      • -
      • Space complexity : O(n).
      • -
      github
      \ No newline at end of file diff --git a/docs/problem/clone-graph.html b/docs/problem/clone-graph.html deleted file mode 100644 index 79ff917..0000000 --- a/docs/problem/clone-graph.html +++ /dev/null @@ -1,60 +0,0 @@ -Clone Graph - LeetCode javascript solutions

      133. Clone Graph

      Difficulty:

      Problem

      -

      Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.

      -

      OJ's undirected graph serialization:

      -

      Nodes are labeled uniquely.

      -

      We use # as a separator for each node, and , as a separator for node label and each neighbor of the node.

      -

      As an example, consider the serialized graph {0,1,2#1,2#2,2}.

      -

      The graph has a total of three nodes, and therefore contains three parts as separated by #.

      -
        -
      • First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
      • -
      • Second node is labeled as 1. Connect node 1 to node 2.
      • -
      • Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle.
      • -
      -

      Visually, the graph looks like the following:

      -
             1
      -      / \
      -     /   \
      -    0 --- 2
      -         / \
      -         \_/
      -
      -

      Solution

      -
      /**
      - * Definition for undirected graph.
      - * function UndirectedGraphNode(label) {
      - *     this.label = label;
      - *     this.neighbors = [];   // Array of UndirectedGraphNode
      - * }
      - */
      -
      -/**
      - * @param {UndirectedGraphNode} graph
      - * @return {UndirectedGraphNode}
      - */
      -var cloneGraph = function(graph) {
      -  return clone(graph, {});
      -};
      -
      -var clone = function (node, map) {
      -  if (!node) return null;
      -  if (map[node.label]) return map[node.label];
      -
      -  var cloneNode = new UndirectedGraphNode(node.label);
      -
      -  map[node.label] = cloneNode;
      -
      -  for (var i = 0; i < node.neighbors.length; i++) {
      -    cloneNode.neighbors.push(clone(node.neighbors[i], map));
      -  }
      -
      -  return cloneNode;
      -};
      -
      -

      Explain:

      -

      不用管描述里的 # , 什么的,题意就是复制一个无向图,不要想复杂了。

      -

      注意有重复节点的话,存个引用就行,用哈希表判断是否重复。

      -

      Complexity:

      -
        -
      • Time complexity : O(n).
      • -
      • Space complexity : O(n).
      • -
      github
      \ No newline at end of file diff --git a/docs/problem/coin-change.html b/docs/problem/coin-change.html deleted file mode 100644 index 8f3b13c..0000000 --- a/docs/problem/coin-change.html +++ /dev/null @@ -1,80 +0,0 @@ -Coin Change - LeetCode javascript solutions

      322. Coin Change

      Difficulty:
      Related Topics:
      Similar Questions:

        Problem

        -

        You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.

        -

        Example 1: -coins = [1, 2, 5], amount = 11 -return 3 (11 = 5 + 5 + 1)

        -

        Example 2: -coins = [2], amount = 3 -return -1.

        -

        Note: -You may assume that you have an infinite number of each kind of coin.

        -

        Credits:

        -

        Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

        -

        Solution 1

        -
        /**
        - * @param {number[]} coins
        - * @param {number} amount
        - * @return {number}
        - */
        -var coinChange = function(coins, amount) {
        -  var dp = [];
        -  return coin(coins, amount, dp);
        -};
        -
        -var coin = function (coins, amount, dp) {
        -  if (dp[amount - 1] !== undefined) return dp[amount - 1];
        -  if (amount < 0) return -1;
        -  if (amount === 0) return 0;
        -
        -  var count = Number.MAX_SAFE_INTEGER;
        -  var tmp = 0;
        -
        -  for (var i = 0; i < coins.length; i++) {
        -    tmp = coin(coins, amount - coins[i], dp);
        -    if (tmp !== -1) count = Math.min(count, tmp + 1);
        -  }
        -
        -  dp[amount - 1] = count === Number.MAX_SAFE_INTEGER ? -1 : count;
        -
        -  return dp[amount - 1];
        -};
        -
        -

        Explain:

        -

        动态规划,从上到下。

        -

        Complexity:

        -
          -
        • Time complexity : O(m*n). mamountncoin 数量。
        • -
        • Space complexity : O(m).
        • -
        -

        Solution 2

        -
        /**
        - * @param {number[]} coins
        - * @param {number} amount
        - * @return {number}
        - */
        -var coinChange = function(coins, amount) {
        -  var dp = Array(amount + 1).fill(amount + 1);
        -
        -  if (amount < 0) return -1;
        -  if (amount === 0) return 0;
        -
        -  dp[0] = 0;
        -
        -  for (var i = 1; i <= amount; i++) {
        -    for (var j = 0; j < coins.length; j++) {
        -      if (i >= coins[j]) {
        -        dp[i] = Math.min(dp[i], dp[i - coins[j]] + 1);
        -      }
        -    }
        -  }
        -
        -  return dp[amount] > amount ? -1 : dp[amount];
        -};
        -
        -

        Explain:

        -

        动态规划,从下到上。

        -

        Complexity:

        -
          -
        • Time complexity : O(m*n). mamountncoin 数量。
        • -
        • Space complexity : O(m).
        • -
        github
        \ No newline at end of file diff --git a/docs/problem/combination-sum-ii.html b/docs/problem/combination-sum-ii.html deleted file mode 100644 index afe02c7..0000000 --- a/docs/problem/combination-sum-ii.html +++ /dev/null @@ -1,64 +0,0 @@ -Combination Sum II - LeetCode javascript solutions

        40. Combination Sum II

        Difficulty:
        Related Topics:
        Similar Questions:

        Problem

        -

        Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

        -

        Each number in candidates may only be used once in the combination.

        -

        Note:

        -
          -
        • All numbers (including target) will be positive integers.
        • -
        • The solution set must not contain duplicate combinations.
        • -
        -

        Example 1:

        -
        Input: candidates = [10,1,2,7,6,1,5], target = 8,
        -A solution set is:
        -[
        -  [1, 7],
        -  [1, 2, 5],
        -  [2, 6],
        -  [1, 1, 6]
        -]
        -
        -

        Example 2:

        -
        Input: candidates = [2,5,2,1,2], target = 5,
        -A solution set is:
        -[
        -  [1,2,2],
        -  [5]
        -]
        -
        -

        Solution

        -
        /**
        - * @param {number[]} candidates
        - * @param {number} target
        - * @return {number[][]}
        - */
        -var combinationSum2 = function(candidates, target) {
        -  var res = [];
        -  var len = candidates.length;
        -  candidates.sort((a, b) => (a - b));
        -  dfs(res, [], 0, len, candidates, target);
        -  return res;
        -};
        -
        -var dfs = function (res, stack, index, len, candidates, target) {
        -  var tmp = null;
        -  if (target < 0) return;
        -  if (target === 0) return res.push(stack);
        -  for (var i = index; i < len; i++) {
        -    if (candidates[i] > target) break;
        -    if (i > index && candidates[i] === candidates[i - 1]) continue;
        -    tmp = Array.from(stack);
        -    tmp.push(candidates[i]);
        -    dfs(res, tmp, i + 1, len, candidates, target - candidates[i]);
        -  }
        -};
        -
        -

        Explain:

        -

        与之前一题不同的地方是:

        -
          -
        1. 候选数字可能有重复的
        2. -
        3. 单个候选数字不能重复使用
        4. -
        -

        Complexity:

        -
          -
        • Time complexity : O(n^2).
        • -
        • Space complexity : O(n^2).
        • -
        github
        \ No newline at end of file diff --git a/docs/problem/combination-sum.html b/docs/problem/combination-sum.html deleted file mode 100644 index 0d31216..0000000 --- a/docs/problem/combination-sum.html +++ /dev/null @@ -1,58 +0,0 @@ -Combination Sum - LeetCode javascript solutions

        39. Combination Sum

        Difficulty:
        Related Topics:

        Problem

        -

        Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

        -

        The same repeated number may be chosen from candidates unlimited number of times.

        -

        Note:

        -
          -
        • All numbers (including target) will be positive integers.
        • -
        • The solution set must not contain duplicate combinations.
        • -
        -

        Example 1:

        -
        Input: candidates = [2,3,6,7], target = 7,
        -A solution set is:
        -[
        -  [7],
        -  [2,2,3]
        -]
        -
        -

        Example 2:

        -
        Input: candidates = [2,3,5], target = 8,
        -A solution set is:
        -[
        -  [2,2,2,2],
        -  [2,3,3],
        -  [3,5]
        -]
        -
        -

        Solution

        -
        /**
        - * @param {number[]} candidates
        - * @param {number} target
        - * @return {number[][]}
        - */
        -var combinationSum = function(candidates, target) {
        -  var res = [];
        -  var len = candidates.length;
        -  candidates.sort((a, b) => (a - b));
        -  dfs(res, [], 0, len, candidates, target);
        -  return res;
        -};
        -
        -var dfs = function (res, stack, index, len, candidates, target) {
        -  var tmp = null;
        -  if (target < 0) return;
        -  if (target === 0) return res.push(stack);
        -  for (var i = index; i < len; i++) {
        -    if (candidates[i] > target) break;
        -    tmp = Array.from(stack);
        -    tmp.push(candidates[i]);
        -    dfs(res, tmp, i, len, candidates, target - candidates[i]);
        -  }
        -};
        -
        -

        Explain:

        -

        对树进行深度优先的搜索。注意解法不能重复,即下次搜索从 index 开始

        -

        Complexity:

        -
          -
        • Time complexity : O(n^2).
        • -
        • Space complexity : O(n^2).
        • -
        github
        \ No newline at end of file diff --git a/docs/problem/combinations.html b/docs/problem/combinations.html deleted file mode 100644 index 8894031..0000000 --- a/docs/problem/combinations.html +++ /dev/null @@ -1,50 +0,0 @@ -Combinations - LeetCode javascript solutions

        77. Combinations

        Difficulty:
        Related Topics:
        Similar Questions:

        Problem

        -

        Given two integers n and k, return all possible combinations of k numbers out of 1 … n.

        -

        Example:

        -
        Input: n = 4, k = 2
        -Output:
        -[
        -  [2,4],
        -  [3,4],
        -  [2,3],
        -  [1,2],
        -  [1,3],
        -  [1,4],
        -]
        -
        -

        Solution

        -
        /**
        - * @param {number} n
        - * @param {number} k
        - * @return {number[][]}
        - */
        -var combine = function(n, k) {
        -  if (n < k || k < 1) return [];
        -
        -  var res = [];
        -
        -  helper(res, [], 0, n, k);
        -
        -  return res;
        -};
        -
        -var helper = function (res, now, start, n, k) {
        -  if (k === 0) {
        -    res.push(Array.from(now));
        -    return;
        -  }
        -
        -  for (var i = start; i < n; i++) {
        -    now.push(i + 1)
        -    helper(res, now, i + 1, n, k - 1);
        -    now.pop();
        -  }
        -};
        -
        -

        Explain:

        -

        nope.

        -

        Complexity:

        -
          -
        • Time complexity :
        • -
        • Space complexity :
        • -
        github
        \ No newline at end of file diff --git a/docs/problem/combine-two-tables.html b/docs/problem/combine-two-tables.html deleted file mode 100644 index a904598..0000000 --- a/docs/problem/combine-two-tables.html +++ /dev/null @@ -1,36 +0,0 @@ -Combine Two Tables - LeetCode javascript solutions

        175. Combine Two Tables

        Difficulty:
        Related Topics:
          Similar Questions:

          Problem

          -

          Table: Person

          -
          +-------------+---------+
          -| Column Name | Type    |
          -+-------------+---------+
          -| PersonId    | int     |
          -| FirstName   | varchar |
          -| LastName    | varchar |
          -+-------------+---------+
          -PersonId is the primary key column for this table.
          -
          -

          Table: Address

          -
          +-------------+---------+
          -| Column Name | Type    |
          -+-------------+---------+
          -| AddressId   | int     |
          -| PersonId    | int     |
          -| City        | varchar |
          -| State       | varchar |
          -+-------------+---------+
          -AddressId is the primary key column for this table.
          -
          -

          Write a SQL query for a report that provides the following information for each person in the Person table, regardless if there is an address for each of those people:

          -
          FirstName, LastName, City, State
          -
          -

          Solution

          -
          # Write your MySQL query statement below
          -select a.FirstName, a.LastName, b.City, b.State from Person a left join Address b on a.PersonId = b.PersonId;
          -
          -

          Explain:

          -

          nope.

          -

          Complexity:

          -
            -
          • Time complexity :
          • -
          • Space complexity :
          • -
          github
          \ No newline at end of file diff --git a/docs/problem/compare-version-numbers.html b/docs/problem/compare-version-numbers.html deleted file mode 100644 index d700865..0000000 --- a/docs/problem/compare-version-numbers.html +++ /dev/null @@ -1,46 +0,0 @@ -Compare Version Numbers - LeetCode javascript solutions

          165. Compare Version Numbers

          Difficulty:
          Related Topics:
          Similar Questions:

            Problem

            -

            Compare two version numbers version1 and version2. -If **version1** > **version2** return 1; if **version1** < **version2** return -1;otherwise return 0.

            -

            You may assume that the version strings are non-empty and contain only digits and the . character. -The . character does not represent a decimal point and is used to separate number sequences. -For instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision.

            -

            Example 1:

            -
            Input: version1 = "0.1", version2 = "1.1"
            -Output: -1
            -
            -

            Example 2:

            -
            Input: version1 = "1.0.1", version2 = "1"
            -Output: 1
            -
            -

            Example 3:

            -
            Input: version1 = "7.5.2.4", version2 = "7.5.3"
            -Output: -1
            -
            -

            Solution

            -
            /**
            - * @param {string} version1
            - * @param {string} version2
            - * @return {number}
            - */
            -var compareVersion = function(version1, version2) {
            -  var v1 = version1.split('.');
            -  var v2 = version2.split('.');
            -  var len = Math.max(v1.length, v2.length);
            -  var t1 = 0;
            -  var t2 = 0;
            -  for (var i = 0; i < len; i++) {
            -    t1 = parseInt(v1[i] || 0);
            -    t2 = parseInt(v2[i] || 0);
            -    if (t1 > t2) return 1;
            -    if (t1 < t2) return -1;
            -  }
            -  return 0;
            -};
            -
            -

            Explain:

            -

            nope.

            -

            Complexity:

            -
              -
            • Time complexity : O(n).
            • -
            • Space complexity : O(1).
            • -
            github
            \ No newline at end of file diff --git a/docs/problem/complex-number-multiplication.html b/docs/problem/complex-number-multiplication.html deleted file mode 100644 index 2bdc8bb..0000000 --- a/docs/problem/complex-number-multiplication.html +++ /dev/null @@ -1,80 +0,0 @@ -Complex Number Multiplication - LeetCode javascript solutions

            537. Complex Number Multiplication

            Difficulty:
            Related Topics:
            Similar Questions:

              Problem

              -

              Given two strings representing two complex numbers.

              -

              You need to return a string representing their multiplication. Note i2 = -1 according to the definition.

              -

              Example 1:

              -
              Input: "1+1i", "1+1i"
              -Output: "0+2i"
              -Explanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i.
              -
              -

              Example 2:

              -
              Input: "1+-1i", "1+-1i"
              -Output: "0+-2i"
              -Explanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i.
              -
              -

              Note:

              -
                -
              • The input strings will not have extra blank.
              • -
              • The input strings will be given in the form of a+bi, where the integer a and b will both belong to the range of [-100, 100]. And the output should be also in this form.
              • -
              -

              Solution 1

              -
              /**
              - * @param {string} a
              - * @param {string} b
              - * @return {string}
              - */
              -var complexNumberMultiply = function(a, b) {
              -  var a = parse(a);
              -  var b = parse(b);
              -  var x = (a.x * b.x) - (a.y * b.y);
              -  var y = (a.x * b.y) + (a.y * b.x);
              -  return stringify(x, y);
              -};
              -
              -var parse = function (str) {
              -  var res = /^(-?\d+)\+(-?\d+)i$/.exec(str);
              -  return { x: Number(res[1]), y: Number(res[2]) };
              -};
              -
              -var stringify = function (x, y) {
              -  return `${x}+${y}i`
              -};
              -
              -

              Explain:

              -

              nope.

              -

              Complexity:

              -
                -
              • Time complexity :
              • -
              • Space complexity :
              • -
              -

              Solution 2

              -
              /**
              - * @param {string} a
              - * @param {string} b
              - * @return {string}
              - */
              -var complexNumberMultiply = function(a, b) {
              -  var a = parse(a);
              -  var b = parse(b);
              -  var x = (a.x * b.x) - (a.y * b.y);
              -  var y = (a.x * b.y) + (a.y * b.x);
              -  return stringify(x, y);
              -};
              -
              -var parse = function (str) {
              -  var index = str.indexOf('+');
              -  var x = Number(str.substring(0, index));
              -  var y = Number(str.substring(index + 1, str.length - 1));
              -  return { x: x, y: y };
              -};
              -
              -var stringify = function (x, y) {
              -  return `${x}+${y}i`
              -}
              -
              -

              Explain:

              -

              nope.

              -

              Complexity:

              -
                -
              • Time complexity :
              • -
              • Space complexity :
              • -
              github
              \ No newline at end of file diff --git a/docs/problem/consecutive-numbers.html b/docs/problem/consecutive-numbers.html deleted file mode 100644 index 5107cd8..0000000 --- a/docs/problem/consecutive-numbers.html +++ /dev/null @@ -1,55 +0,0 @@ -Consecutive Numbers - LeetCode javascript solutions

              180. Consecutive Numbers

              Difficulty:
              Related Topics:
                Similar Questions:

                  Problem

                  -

                  Write a SQL query to find all numbers that appear at least three times consecutively.

                  -
                  +----+-----+
                  -| Id | Num |
                  -+----+-----+
                  -| 1  |  1  |
                  -| 2  |  1  |
                  -| 3  |  1  |
                  -| 4  |  2  |
                  -| 5  |  1  |
                  -| 6  |  2  |
                  -| 7  |  2  |
                  -+----+-----+
                  -
                  -

                  For example, given the above Logs table, 1 is the only number that appears consecutively for at least three times.

                  -
                  +-----------------+
                  -| ConsecutiveNums |
                  -+-----------------+
                  -| 1               |
                  -+-----------------+
                  -
                  -

                  Solution 1

                  -
                  # Write your MySQL query statement below
                  -select distinct A.Num as ConsecutiveNums
                  -  from Logs A
                  -  left join logs B
                  -    on A.Id = B.Id - 1
                  -  left join logs C
                  -    on B.Id = C.Id - 1
                  -  where A.Num = B.Num
                  -    and B.Num = C.Num
                  -
                  -

                  Explain:

                  -

                  nope.

                  -

                  Complexity:

                  -
                    -
                  • Time complexity :
                  • -
                  • Space complexity :
                  • -
                  -

                  Solution 2

                  -
                  # Write your MySQL query statement below
                  -select distinct A.Num as ConsecutiveNums
                  -  from Logs A, logs B, logs C
                  -  where A.Num = B.Num
                  -    and B.Num = C.Num
                  -    and A.Id = B.Id - 1
                  -    and B.Id = C.Id - 1
                  -
                  -

                  Explain:

                  -

                  nope.

                  -

                  Complexity:

                  -
                    -
                  • Time complexity :
                  • -
                  • Space complexity :
                  • -
                  github
                  \ No newline at end of file diff --git a/docs/problem/construct-binary-tree-from-inorder-and-postorder-traversal.html b/docs/problem/construct-binary-tree-from-inorder-and-postorder-traversal.html deleted file mode 100644 index 1d38f70..0000000 --- a/docs/problem/construct-binary-tree-from-inorder-and-postorder-traversal.html +++ /dev/null @@ -1,58 +0,0 @@ -Construct Binary Tree from Inorder and Postorder Traversal - LeetCode javascript solutions

                  106. Construct Binary Tree from Inorder and Postorder Traversal

                  Difficulty:

                  Problem

                  -

                  Given inorder and postorder traversal of a tree, construct the binary tree.

                  -

                  Note:

                  -

                  You may assume that duplicates do not exist in the tree.

                  -

                  For example, given

                  -
                  inorder = [9,3,15,20,7]
                  -postorder = [9,15,7,20,3]
                  -
                  -

                  Return the following binary tree:

                  -
                      3
                  -   / \
                  -  9  20
                  -    /  \
                  -   15   7
                  -
                  -

                  Solution

                  -
                  /**
                  - * Definition for a binary tree node.
                  - * function TreeNode(val) {
                  - *     this.val = val;
                  - *     this.left = this.right = null;
                  - * }
                  - */
                  -/**
                  - * @param {number[]} inorder
                  - * @param {number[]} postorder
                  - * @return {TreeNode}
                  - */
                  -var buildTree = function(inorder, postorder) {
                  -  return helper(inorder, postorder, 0, inorder.length - 1, postorder.length - 1);
                  -};
                  -
                  -var helper = function (inorder, postorder, inStart, inEnd, postIndex) {
                  -  if (inStart > inEnd || postIndex < 0) return null;
                  -
                  -  var index = 0;
                  -  var root = new TreeNode(postorder[postIndex]);
                  -
                  -  for (var i = inStart; i <= inEnd; i++) {
                  -    if (inorder[i] === root.val) {
                  -      index = i;
                  -      break;
                  -    }
                  -  }
                  -
                  -  root.right = helper(inorder, postorder, index + 1, inEnd, postIndex - 1);
                  -  root.left = helper(inorder, postorder, inStart, index - 1, postIndex - 1 - (inEnd - index));
                  -
                  -  return root;
                  -};
                  -
                  -

                  Explain:

                  -

                  see Construct Binary Tree from Preorder and Inorder Traversal.

                  -

                  Complexity:

                  -
                    -
                  • Time complexity : O(n).
                  • -
                  • Space complexity : O(n).
                  • -
                  github
                  \ No newline at end of file diff --git a/docs/problem/construct-binary-tree-from-preorder-and-inorder-traversal.html b/docs/problem/construct-binary-tree-from-preorder-and-inorder-traversal.html deleted file mode 100644 index c93bbb0..0000000 --- a/docs/problem/construct-binary-tree-from-preorder-and-inorder-traversal.html +++ /dev/null @@ -1,62 +0,0 @@ -Construct Binary Tree from Preorder and Inorder Traversal - LeetCode javascript solutions

                  105. Construct Binary Tree from Preorder and Inorder Traversal

                  Difficulty:

                  Problem

                  -

                  Given preorder and inorder traversal of a tree, construct the binary tree.

                  -

                  Note: -You may assume that duplicates do not exist in the tree.

                  -

                  For example, given

                  -
                  preorder = [3,9,20,15,7]
                  -inorder = [9,3,15,20,7]
                  -
                  -

                  Return the following binary tree:

                  -
                      3
                  -   / \
                  -  9  20
                  -    /  \
                  -   15   7
                  -
                  -

                  Solution

                  -
                  /**
                  - * Definition for a binary tree node.
                  - * function TreeNode(val) {
                  - *     this.val = val;
                  - *     this.left = this.right = null;
                  - * }
                  - */
                  -/**
                  - * @param {number[]} preorder
                  - * @param {number[]} inorder
                  - * @return {TreeNode}
                  - */
                  -var buildTree = function(preorder, inorder) {
                  -  return helper(preorder, inorder, 0, 0, inorder.length - 1);
                  -};
                  -
                  -var helper = function (preorder, inorder, preIndex, inStart, inEnd) {
                  -  if (preIndex >= preorder.length || inStart > inEnd) return null;
                  -
                  -  var index = 0;
                  -  var root = new TreeNode(preorder[preIndex]);
                  -
                  -  for (var i = inStart; i <= inEnd; i++) {
                  -    if (inorder[i] === root.val) {
                  -      index = i;
                  -      break;
                  -    }
                  -  }
                  -
                  -  if (index > inStart) root.left = helper(preorder, inorder, preIndex + 1, inStart, index - 1);
                  -  if (index < inEnd) root.right = helper(preorder, inorder, preIndex + index - inStart + 1, index + 1, inEnd);
                  -
                  -  return root;
                  -};
                  -
                  -

                  Explain:

                  -
                    -
                  1. preorder[0]root
                  2. -
                  3. inorder 里找到 root,左边是 root.left,右边是 root.right
                  4. -
                  5. 递归
                  6. -
                  -

                  Complexity:

                  -
                    -
                  • Time complexity :
                  • -
                  • Space complexity :
                  • -
                  github
                  \ No newline at end of file diff --git a/docs/problem/container-with-most-water.html b/docs/problem/container-with-most-water.html deleted file mode 100644 index 48cd37a..0000000 --- a/docs/problem/container-with-most-water.html +++ /dev/null @@ -1,30 +0,0 @@ -Container With Most Water - LeetCode javascript solutions

                  11. Container With Most Water

                  Difficulty:
                  Related Topics:
                  Similar Questions:

                  Problem

                  -

                  Given n non-negative integers a1, a2, …, an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

                  -

                  Note: You may not slant the container and n is at least 2.

                  -

                  Solution

                  -
                  /**
                  - * @param {number[]} height
                  - * @return {number}
                  - */
                  -var maxArea = function(height) {
                  -  var max = 0;
                  -  var l = 0;
                  -  var r = height.length - 1;
                  -  while (l < r) {
                  -    max = Math.max(max, Math.min(height[l], height[r]) * (r - l));
                  -    if (height[l] < height[r]) {
                  -      l++;
                  -    } else {
                  -      r--;
                  -    }
                  -  }
                  -  return max;
                  -};
                  -
                  -

                  Explain:

                  -

                  双指针从两头开始,判断哪边更高。积水量是矮的那边决定的,移动高的那边不可能提升积水量,所以移动矮的那边。

                  -

                  Complexity:

                  -
                    -
                  • Time complexity : O(n).
                  • -
                  • Space complexity : O(1).
                  • -
                  github
                  \ No newline at end of file diff --git a/docs/problem/convert-sorted-array-to-binary-search-tree.html b/docs/problem/convert-sorted-array-to-binary-search-tree.html deleted file mode 100644 index 518b36c..0000000 --- a/docs/problem/convert-sorted-array-to-binary-search-tree.html +++ /dev/null @@ -1,46 +0,0 @@ -Convert Sorted Array to Binary Search Tree - LeetCode javascript solutions

                  108. Convert Sorted Array to Binary Search Tree

                  Difficulty:
                  Related Topics:

                  Problem

                  -

                  Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

                  -

                  For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

                  -

                  Example:

                  -
                  Given the sorted array: [-10,-3,0,5,9],
                  -
                  -One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
                  -
                  -      0
                  -     / \
                  -   -3   9
                  -   /   /
                  - -10  5
                  -
                  -

                  Solution

                  -
                  /**
                  - * Definition for a binary tree node.
                  - * function TreeNode(val) {
                  - *     this.val = val;
                  - *     this.left = this.right = null;
                  - * }
                  - */
                  -/**
                  - * @param {number[]} nums
                  - * @return {TreeNode}
                  - */
                  -var sortedArrayToBST = function(nums) {
                  -  return helper(nums, 0, nums.length - 1);
                  -};
                  -
                  -var helper = function (nums, ll, rr) {
                  -  if (ll > rr) return null;
                  -  var mid = Math.ceil((ll + rr) / 2);
                  -  var root = new TreeNode(nums[mid]);
                  -  root.left = helper(nums, ll, mid - 1);
                  -  root.right = helper(nums, mid + 1, rr);
                  -  return root;
                  -};
                  -
                  -

                  Explain:

                  -

                  nope.

                  -

                  Complexity:

                  -
                    -
                  • Time complexity : O(n).
                  • -
                  • Space complexity : O(n).
                  • -
                  github
                  \ No newline at end of file diff --git a/docs/problem/convert-sorted-list-to-binary-search-tree.html b/docs/problem/convert-sorted-list-to-binary-search-tree.html deleted file mode 100644 index efda357..0000000 --- a/docs/problem/convert-sorted-list-to-binary-search-tree.html +++ /dev/null @@ -1,63 +0,0 @@ -Convert Sorted List to Binary Search Tree - LeetCode javascript solutions

                  109. Convert Sorted List to Binary Search Tree

                  Difficulty:

                  Problem

                  -

                  Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

                  -

                  For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

                  -

                  Example:

                  -
                  Given the sorted linked list: [-10,-3,0,5,9],
                  -
                  -One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
                  -
                  -      0
                  -     / \
                  -   -3   9
                  -   /   /
                  - -10  5
                  -
                  -

                  Solution

                  -
                  /**
                  - * Definition for singly-linked list.
                  - * function ListNode(val) {
                  - *     this.val = val;
                  - *     this.next = null;
                  - * }
                  - */
                  -/**
                  - * Definition for a binary tree node.
                  - * function TreeNode(val) {
                  - *     this.val = val;
                  - *     this.left = this.right = null;
                  - * }
                  - */
                  -/**
                  - * @param {ListNode} head
                  - * @return {TreeNode}
                  - */
                  -var sortedListToBST = function(head) {
                  -  return helper(head, null);
                  -};
                  -
                  -var helper = function (head, foot) {
                  -  var fast = head;
                  -  var slow = head;
                  -  var node = null;
                  -
                  -  if (head === foot) return null;
                  -
                  -  while (fast !== foot && fast.next !== foot) {
                  -    fast = fast.next.next;
                  -    slow = slow.next;
                  -  }
                  -
                  -  node = new TreeNode(slow.val);
                  -  node.left = helper(head, slow);
                  -  node.right = helper(slow.next, foot);
                  -
                  -  return node;
                  -};
                  -
                  -

                  Explain:

                  -

                  nope.

                  -

                  Complexity:

                  -
                    -
                  • Time complexity : O(log(n)).
                  • -
                  • Space complexity : O(n).
                  • -
                  github
                  \ No newline at end of file diff --git a/docs/problem/copy-list-with-random-pointer.html b/docs/problem/copy-list-with-random-pointer.html deleted file mode 100644 index 0900f3d..0000000 --- a/docs/problem/copy-list-with-random-pointer.html +++ /dev/null @@ -1,45 +0,0 @@ -Copy List with Random Pointer - LeetCode javascript solutions

                  138. Copy List with Random Pointer

                  Difficulty:
                  Related Topics:
                  Similar Questions:

                  Problem

                  -

                  A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

                  -

                  Return a deep copy of the list.

                  -

                  Solution

                  -
                  /**
                  - * Definition for singly-linked list with a random pointer.
                  - * function RandomListNode(label) {
                  - *     this.label = label;
                  - *     this.next = this.random = null;
                  - * }
                  - */
                  -
                  -/**
                  - * @param {RandomListNode} head
                  - * @return {RandomListNode}
                  - */
                  -var copyRandomList = function(head) {
                  -  if (!head) return null;
                  -
                  -  var map = new Map();
                  -  var now = null;
                  -
                  -  now = head;
                  -  while (now) {
                  -    map.set(now, new RandomListNode(now.label));
                  -    now = now.next;
                  -  }
                  -
                  -  now = head;
                  -  while (now) {
                  -    map.get(now).next = map.get(now.next) || null;
                  -    map.get(now).random = map.get(now.random) || null;
                  -    now = now.next;
                  -  }
                  -
                  -  return map.get(head);
                  -};
                  -
                  -

                  Explain:

                  -

                  ES6Map 可以用任意类型的 key。如果用 labelkey 的话,可能重复,直接 objectkey 就好。

                  -

                  Complexity:

                  -
                    -
                  • Time complexity : O(n).
                  • -
                  • Space complexity : O(n).
                  • -
                  github
                  \ No newline at end of file diff --git a/docs/problem/count-and-say.html b/docs/problem/count-and-say.html deleted file mode 100644 index 36049d2..0000000 --- a/docs/problem/count-and-say.html +++ /dev/null @@ -1,71 +0,0 @@ -Count and Say - LeetCode javascript solutions

                  38. Count and Say

                  Difficulty:
                  Related Topics:

                  Problem

                  -

                  The count-and-say sequence is the sequence of integers with the first five terms as following:

                  -
                  1.     1
                  -2.     11
                  -3.     21
                  -4.     1211
                  -5.     111221
                  -
                  -

                  1 is read off as "one 1" or 11. -11 is read off as "two 1s" or 21. -21 is read off as "one 2, then one 1" or 1211.

                  -

                  Given an integer n, generate the nth term of the count-and-say sequence.

                  -

                  Note: Each term of the sequence of integers will be represented as a string.

                  -

                  Example 1:

                  -
                  Input: 1
                  -Output: "1"
                  -
                  -

                  Example 2:

                  -
                  Input: 4
                  -Output: "1211"
                  -
                  -

                  Solution

                  -
                  /**
                  - * @param {number} n
                  - * @return {string}
                  - */
                  -var countAndSay = function(n) {
                  -  var str = '1';
                  -  var tmp = '';
                  -  var last = '';
                  -  var count = 0;
                  -  var len = 0;
                  -
                  -  for (var i = 1; i < n; i++) {
                  -    tmp = '';
                  -    last = '';
                  -    count = 0;
                  -    len = str.length;
                  -
                  -    for (var j = 0; j < len; j++) {
                  -      if (last === '') {
                  -        last = str[j];
                  -        count = 1;
                  -        continue;
                  -      }
                  -      if (str[j] === last) {
                  -        count += 1;
                  -      } else {
                  -        tmp += '' + count + last;
                  -        last = str[j];
                  -        count = 1;
                  -      }
                  -    }
                  -
                  -    if (last) {
                  -      tmp += '' + count + last;
                  -    }
                  -
                  -    str = tmp;
                  -  }
                  -
                  -  return str;
                  -};
                  -
                  -

                  Explain:

                  -

                  nope.

                  -

                  Complexity:

                  -
                    -
                  • Time complexity :
                  • -
                  • Space complexity :
                  • -
                  github
                  \ No newline at end of file diff --git a/docs/problem/course-schedule.html b/docs/problem/course-schedule.html deleted file mode 100644 index 85c0433..0000000 --- a/docs/problem/course-schedule.html +++ /dev/null @@ -1,69 +0,0 @@ -Course Schedule - LeetCode javascript solutions

                  207. Course Schedule

                  Difficulty:

                  Problem

                  -

                  There are a total of n courses you have to take, labeled from 0 to n-1.

                  -

                  Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

                  -

                  Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?

                  -

                  Example 1:

                  -
                  Input: 2, [[1,0]] 
                  -Output: true
                  -Explanation: There are a total of 2 courses to take. 
                  -             To take course 1 you should have finished course 0. So it is possible.
                  -
                  -

                  Example 2:

                  -
                  Input: 2, [[1,0],[0,1]]
                  -Output: false
                  -Explanation: There are a total of 2 courses to take. 
                  -             To take course 1 you should have finished course 0, and to take course 0 you should
                  -             also have finished course 1. So it is impossible.
                  -
                  -

                  Note:

                  -
                    -
                  • The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
                  • -
                  • You may assume that there are no duplicate edges in the input prerequisites.
                  • -
                  -

                  Solution

                  -
                  /**
                  - * @param {number} numCourses
                  - * @param {number[][]} prerequisites
                  - * @return {boolean}
                  - */
                  -var canFinish = function(numCourses, prerequisites) {
                  -  var edges = Array(numCourses).fill(0).map(_ => Array(numCourses).fill(0));
                  -  var incoming = Array(numCourses).fill(0);
                  -  var len = prerequisites.length;
                  -  var post = 0;
                  -  var prev = 0;
                  -  var queue = [];
                  -  var num = 0;
                  -  var count = 0;
                  -
                  -  for (var i = 0; i < len; i++) {
                  -    prev = prerequisites[i][1];
                  -    post = prerequisites[i][0];
                  -    if (edges[prev][post] === 0) {
                  -      incoming[post]++;
                  -      edges[prev][post] = 1;
                  -    }
                  -  }
                  -
                  -  for (var j = 0; j < numCourses; j++) {
                  -    if (incoming[j] === 0) queue.push(j);
                  -  }
                  -
                  -  while (queue.length) {
                  -    count++;
                  -    num = queue.pop()
                  -    for (var k = 0; k < numCourses; k++) {
                  -      if (edges[num][k] === 1 && --incoming[k] === 0) queue.push(k);
                  -    }
                  -  }
                  -
                  -  return count === numCourses;
                  -};
                  -
                  -

                  Explain:

                  -

                  nope.

                  -

                  Complexity:

                  -
                    -
                  • Time complexity : O(n^2).
                  • -
                  • Space complexity : O(n^2).
                  • -
                  github
                  \ No newline at end of file diff --git a/docs/problem/customers-who-never-order.html b/docs/problem/customers-who-never-order.html deleted file mode 100644 index 068a4af..0000000 --- a/docs/problem/customers-who-never-order.html +++ /dev/null @@ -1,73 +0,0 @@ -Customers Who Never Order - LeetCode javascript solutions

                  183. Customers Who Never Order

                  Difficulty:
                  Related Topics:
                    Similar Questions:

                      Problem

                      -

                      Suppose that a website contains two tables, the Customers table and the Orders table. Write a SQL query to find all customers who never order anything.

                      -

                      Table: Customers.

                      -
                      +----+-------+
                      -| Id | Name  |
                      -+----+-------+
                      -| 1  | Joe   |
                      -| 2  | Henry |
                      -| 3  | Sam   |
                      -| 4  | Max   |
                      -+----+-------+
                      -
                      -

                      Table: Orders.

                      -
                      +----+------------+
                      -| Id | CustomerId |
                      -+----+------------+
                      -| 1  | 3          |
                      -| 2  | 1          |
                      -+----+------------+
                      -
                      -

                      Using the above tables as example, return the following:

                      -
                      +-----------+
                      -| Customers |
                      -+-----------+
                      -| Henry     |
                      -| Max       |
                      -+-----------+
                      -
                      -

                      Solution 1

                      -
                      # Write your MySQL query statement below
                      -select a.Name as Customers
                      -  from Customers a
                      -  where a.Id not in (
                      -    select b.CustomerId from Orders b
                      -  )
                      -
                      -

                      Explain:

                      -

                      nope.

                      -

                      Complexity:

                      -
                        -
                      • Time complexity :
                      • -
                      • Space complexity :
                      • -
                      -

                      Solution 2

                      -
                      # Write your MySQL query statement below
                      -select a.Name as Customers
                      -  from Customers a
                      -  where not exists (
                      -    select Id from Orders b where a.Id = b.CustomerId
                      -  )
                      -
                      -

                      Explain:

                      -

                      nope.

                      -

                      Complexity:

                      -
                        -
                      • Time complexity :
                      • -
                      • Space complexity :
                      • -
                      -

                      Solution 3

                      -
                      # Write your MySQL query statement below
                      -select a.Name as Customers
                      -  from Customers a
                      -  left join Orders b
                      -  on a.Id = b.CustomerId
                      -  where b.CustomerId is null
                      -
                      -

                      Explain:

                      -

                      nope.

                      -

                      Complexity:

                      -
                        -
                      • Time complexity :
                      • -
                      • Space complexity :
                      • -
                      github
                      \ No newline at end of file diff --git a/docs/problem/decode-ways.html b/docs/problem/decode-ways.html deleted file mode 100644 index 690c7c4..0000000 --- a/docs/problem/decode-ways.html +++ /dev/null @@ -1,53 +0,0 @@ -Decode Ways - LeetCode javascript solutions

                      91. Decode Ways

                      Difficulty:
                      Similar Questions:

                      Problem

                      -

                      A message containing letters from A-Z is being encoded to numbers using the following mapping:

                      -
                      'A' -> 1
                      -'B' -> 2
                      -...
                      -'Z' -> 26
                      -
                      -

                      Given a non-empty string containing only digits, determine the total number of ways to decode it.

                      -

                      Example 1:

                      -
                      Input: "12"
                      -Output: 2
                      -Explanation: It could be decoded as "AB" (1 2) or "L" (12).
                      -
                      -

                      Example 2:

                      -
                      Input: "226"
                      -Output: 3
                      -Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).
                      -
                      -

                      Solution

                      -
                      /**
                      - * @param {string} s
                      - * @return {number}
                      - */
                      -var numDecodings = function(s) {
                      -  var len = s.length;
                      -  var tmp = 0;
                      -  var tmp1 = 1;
                      -  var tmp2 = 0;
                      -  var num1 = 0;
                      -  var num2 = 0;
                      -
                      -  if (s === '' || s[0] === '0') return 0;
                      -
                      -  for (var i = 1; i <= len; i++) {
                      -    num1 = Number(s.substr(i - 1, 1));
                      -    num2 = Number(s.substr(i - 2, 2));
                      -    if (num1 !== 0) tmp += tmp1;
                      -    if (10 <= num2 && num2 <= 26) tmp += tmp2;
                      -    tmp2 = tmp1;
                      -    tmp1 = tmp;
                      -    tmp = 0;
                      -  }
                      -
                      -  return tmp1;
                      -};
                      -
                      -

                      Explain:

                      -

                      每个点可由前面一个点 decode 1 一个数字到达或前面两个点 decode 2 个数字到达。

                      -

                      Complexity:

                      -
                        -
                      • Time complexity : O(n).
                      • -
                      • Space complexity : O(1).
                      • -
                      github
                      \ No newline at end of file diff --git a/docs/problem/distinct-subsequences.html b/docs/problem/distinct-subsequences.html deleted file mode 100644 index 4b4fea5..0000000 --- a/docs/problem/distinct-subsequences.html +++ /dev/null @@ -1,68 +0,0 @@ -Distinct Subsequences - LeetCode javascript solutions

                      115. Distinct Subsequences

                      Difficulty:
                      Similar Questions:

                        Problem

                        -

                        Given a string S and a string T, count the number of distinct subsequences of S which equals T.

                        -

                        A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not).

                        -

                        Example 1:

                        -
                        Input: S = "rabbbit", T = "rabbit"
                        -Output: 3
                        -Explanation:
                        -
                        -As shown below, there are 3 ways you can generate "rabbit" from S.
                        -(The caret symbol ^ means the chosen letters)
                        -
                        -rabbbit
                        -^^^^ ^^
                        -rabbbit
                        -^^ ^^^^
                        -rabbbit
                        -^^^ ^^^
                        -
                        -

                        Example 2:

                        -
                        Input: S = "babgbag", T = "bag"
                        -Output: 5
                        -Explanation:
                        -
                        -As shown below, there are 5 ways you can generate "bag" from S.
                        -(The caret symbol ^ means the chosen letters)
                        -
                        -babgbag
                        -^^ ^
                        -babgbag
                        -^^    ^
                        -babgbag
                        -^    ^^
                        -babgbag
                        -  ^  ^^
                        -babgbag
                        -    ^^^
                        -
                        -

                        Solution

                        -
                        /**
                        - * @param {string} s
                        - * @param {string} t
                        - * @return {number}
                        - */
                        -var numDistinct = function(s, t) {
                        -  var dp = Array(s.length).fill(0).map(_ => Array(t.length));
                        -  return helper(s, t, 0, 0, dp);
                        -};
                        -
                        -var helper = function (s, t, sIndex, tIndex, dp) {
                        -  if (tIndex === t.length) return 1;
                        -  if (sIndex === s.length) return 0;
                        -  if (dp[sIndex][tIndex] === undefined) {
                        -    if (s[sIndex] === t[tIndex]) {
                        -      dp[sIndex][tIndex] = helper(s, t, sIndex + 1, tIndex + 1, dp) + helper(s, t, sIndex + 1, tIndex, dp);
                        -    } else {
                        -      dp[sIndex][tIndex] = helper(s, t, sIndex + 1, tIndex, dp);
                        -    }
                        -  }
                        -  return dp[sIndex][tIndex];
                        -};
                        -
                        -

                        Explain:

                        -

                        nope.

                        -

                        Complexity:

                        -
                          -
                        • Time complexity : O(m*n).
                        • -
                        • Space complexity : O(m*n).
                        • -
                        github
                        \ No newline at end of file diff --git a/docs/problem/divide-two-integers.html b/docs/problem/divide-two-integers.html deleted file mode 100644 index 8b47629..0000000 --- a/docs/problem/divide-two-integers.html +++ /dev/null @@ -1,58 +0,0 @@ -Divide Two Integers - LeetCode javascript solutions

                        29. Divide Two Integers

                        Difficulty:
                        Related Topics:
                        Similar Questions:

                          Problem

                          -

                          Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.

                          -

                          Return the quotient after dividing dividend by divisor.

                          -

                          The integer division should truncate toward zero.

                          -

                          Example 1:

                          -
                          Input: dividend = 10, divisor = 3
                          -Output: 3
                          -
                          -

                          Example 2:

                          -
                          Input: dividend = 7, divisor = -3
                          -Output: -2
                          -
                          -

                          Note:

                          -
                            -
                          • Both dividend and divisor will be 32-bit signed integers.
                          • -
                          • The divisor will never be 0.
                          • -
                          • Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 231 − 1 when the division result overflows.
                          • -
                          -

                          Solution

                          -
                          /**
                          - * @param {number} dividend
                          - * @param {number} divisor
                          - * @return {number}
                          - */
                          -var divide = function(dividend, divisor) {
                          -  var did = Math.abs(dividend);
                          -  var dis = Math.abs(divisor);
                          -  var sign = (divisor > 0 && dividend > 0) || (divisor < 0 && dividend < 0);
                          -  var res = 0;
                          -  var arr = [dis];
                          -
                          -  if (dividend === 0 || did < dis) return 0;
                          -  if (divisor === -1 && dividend === -2147483648) return 2147483647;
                          -  if (dis === 1) return divisor > 0 ? dividend : -dividend;
                          -
                          -  while (arr[arr.length - 1] < did) arr.push(arr[arr.length - 1] + arr[arr.length - 1]);
                          -
                          -  for (var i = arr.length - 1; i >= 0; i--) {
                          -    if (did >= arr[i]) {
                          -      did -= arr[i];
                          -      res += i === 0 ? 1 : 2 << (i - 1);
                          -    }
                          -  }
                          -
                          -  return sign ? res : -res;
                          -};
                          -
                          -

                          Explain:

                          -
                            -
                          1. 要注意 -2147483648 / -1 越界的情况
                          2. -
                          3. 核心就是 dividend -= divisor << i; result += 2 << (i - 1);
                          4. -
                          5. 其它语言有 longlong long 类型可以保证 divisor << i 不越界,但是 js 没有。比如 2 << 2910737418242 << 30 就越界了,不会得到预期的结果。我这里是用加法提前计算好 divisor << i
                          6. -
                          -

                          Complexity:

                          -
                            -
                          • Time complexity : O(log(n)).
                          • -
                          • Space complexity : O(log(n)).
                          • -
                          github
                          \ No newline at end of file diff --git a/docs/problem/dungeon-game.html b/docs/problem/dungeon-game.html deleted file mode 100644 index e5a09ef..0000000 --- a/docs/problem/dungeon-game.html +++ /dev/null @@ -1,69 +0,0 @@ -Dungeon Game - LeetCode javascript solutions

                          174. Dungeon Game

                          Difficulty:

                          Problem

                          -

                          The demons had captured the princess (P) and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of M x N rooms laid out in a 2D grid. Our valiant knight (K) was initially positioned in the top-left room and must fight his way through the dungeon to rescue the princess.

                          -

                          The knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately.

                          -

                          Some of the rooms are guarded by demons, so the knight loses health (negative integers) upon entering these rooms; other rooms are either empty (0's) or contain magic orbs that increase the knight's health (positive integers).

                          -

                          In order to reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step.

                          -

                          Write a function to determine the knight's minimum initial health so that he is able to rescue the princess.

                          -

                          For example, given the dungeon below, the initial health of the knight must be at least 7 if he follows the optimal path RIGHT-> RIGHT -> DOWN -> DOWN.

                          - - - - - - - - - - - - - - - - - - - - - - - - - -
                          -2 (K)-33
                          -5-101
                          1030-5 (P)
                          -

                          Note:

                          -
                            -
                          • The knight's health has no upper bound.
                          • -
                          • Any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned.
                          • -
                          -

                          Solution

                          -
                          /**
                          - * @param {number[][]} dungeon
                          - * @return {number}
                          - */
                          -var calculateMinimumHP = function(dungeon) {
                          -  var m = dungeon.length;
                          -  var n = dungeon[0].length;
                          -  var dp = Array(m + 1).fill(0).map(_ => Array(n + 1).fill(Number.MAX_SAFE_INTEGER));
                          -  var tmp = 0;
                          -
                          -  dp[m][ n - 1] = 1;
                          -  dp[m - 1][n] = 1;
                          -
                          -  for (var i = m - 1; i >= 0; i--) {
                          -    for (var j = n - 1; j >= 0; j--) {
                          -      tmp = Math.min(dp[i][j + 1], dp[i + 1][j]) - dungeon[i][j];
                          -      dp[i][j] = tmp <= 0 ? 1 : tmp;
                          -    }
                          -  }
                          -
                          -  return dp[0][0];
                          -};
                          -
                          -

                          Explain:

                          -

                          nope.

                          -

                          Complexity:

                          -
                            -
                          • Time complexity : O(m*n).
                          • -
                          • Space complexity : O(m*n).
                          • -
                          github
                          \ No newline at end of file diff --git a/docs/problem/duplicate-emails.html b/docs/problem/duplicate-emails.html deleted file mode 100644 index 10a94c2..0000000 --- a/docs/problem/duplicate-emails.html +++ /dev/null @@ -1,47 +0,0 @@ -Duplicate Emails - LeetCode javascript solutions

                          182. Duplicate Emails

                          Difficulty:
                          Related Topics:
                            Similar Questions:

                              Problem

                              -

                              Write a SQL query to find all duplicate emails in a table named Person.

                              -
                              +----+---------+
                              -| Id | Email   |
                              -+----+---------+
                              -| 1  | a@b.com |
                              -| 2  | c@d.com |
                              -| 3  | a@b.com |
                              -+----+---------+
                              -
                              -

                              For example, your query should return the following for the above table:

                              -
                              +---------+
                              -| Email   |
                              -+---------+
                              -| a@b.com |
                              -+---------+
                              -
                              -

                              Note: All emails are in lowercase.

                              -

                              Solution 1

                              -
                              # Write your MySQL query statement below
                              -select Email
                              -  from Person
                              -  group by Email
                              -  having count(Id) > 1
                              -
                              -

                              Explain:

                              -

                              nope.

                              -

                              Complexity:

                              -
                                -
                              • Time complexity :
                              • -
                              • Space complexity :
                              • -
                              -

                              Solution 2

                              -
                              # Write your MySQL query statement below
                              -select
                              -  distinct a.Email as Email
                              -  from Person a, Person b
                              -  where a.Id <> b.Id
                              -    and a.Email = b.Email
                              -
                              -

                              Explain:

                              -

                              nope.

                              -

                              Complexity:

                              -
                                -
                              • Time complexity :
                              • -
                              • Space complexity :
                              • -
                              github
                              \ No newline at end of file diff --git a/docs/problem/edit-distance.html b/docs/problem/edit-distance.html deleted file mode 100644 index b5348ec..0000000 --- a/docs/problem/edit-distance.html +++ /dev/null @@ -1,66 +0,0 @@ -Edit Distance - LeetCode javascript solutions

                              72. Edit Distance

                              Difficulty:

                              Problem

                              -

                              Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.

                              -

                              You have the following 3 operations permitted on a word:

                              -
                                -
                              • Insert a character
                              • -
                              • Delete a character
                              • -
                              • Replace a character
                              • -
                              -

                              Example 1:

                              -
                              Input: word1 = "horse", word2 = "ros"
                              -Output: 3
                              -Explanation: 
                              -horse -> rorse (replace 'h' with 'r')
                              -rorse -> rose (remove 'r')
                              -rose -> ros (remove 'e')
                              -
                              -

                              Example 2:

                              -
                              Input: word1 = "intention", word2 = "execution"
                              -Output: 5
                              -Explanation: 
                              -intention -> inention (remove 't')
                              -inention -> enention (replace 'i' with 'e')
                              -enention -> exention (replace 'n' with 'x')
                              -exention -> exection (replace 'n' with 'c')
                              -exection -> execution (insert 'u')
                              -
                              -

                              Solution

                              -
                              /**
                              - * @param {string} word1
                              - * @param {string} word2
                              - * @return {number}
                              - */
                              -var minDistance = function(word1, word2) {
                              -  var n = word1.length;
                              -  var m = word2.length;
                              -  var dp = Array(n);
                              -
                              -  for (var i = 0; i < n; i++) {
                              -    dp[i] = Array(m);
                              -    for (var j = 0; j < m; j++) {
                              -      dp[i][j] = Math.min(
                              -        getDp(i - 1, j, dp) + 1,
                              -        getDp(i, j - 1, dp) + 1,
                              -        getDp(i - 1, j - 1, dp) + (word1[i] === word2[j] ? 0 : 1)
                              -      );
                              -    }
                              -  }
                              -
                              -  return getDp(n - 1, m - 1, dp);
                              -};
                              -
                              -var getDp = function (i, j, dp) {
                              -  if (i < 0 && j < 0) return 0;
                              -  if (i < 0) return j + 1;
                              -  if (j < 0) return i + 1;
                              -  return dp[i][j];
                              -};
                              -
                              -

                              Explain:

                              -

                              dp[i][j] 代表 word10 ~ i 转为 word20 ~ j 的最少步骤

                              -

                              dp[i][j] = min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + (word1[i] === word2[j] ? 0 : 1));

                              -

                              Complexity:

                              -
                                -
                              • Time complexity : O(m*n).
                              • -
                              • Space complexity : Om*(n).
                              • -
                              github
                              \ No newline at end of file diff --git a/docs/problem/employees-earning-more-than-their-managers.html b/docs/problem/employees-earning-more-than-their-managers.html deleted file mode 100644 index 924166e..0000000 --- a/docs/problem/employees-earning-more-than-their-managers.html +++ /dev/null @@ -1,49 +0,0 @@ -Employees Earning More Than Their Managers - LeetCode javascript solutions

                              181. Employees Earning More Than Their Managers

                              Difficulty:
                              Related Topics:
                                Similar Questions:

                                  Problem

                                  -

                                  The Employee table holds all employees including their managers. Every employee has an Id, and there is also a column for the manager Id.

                                  -
                                  +----+-------+--------+-----------+
                                  -| Id | Name  | Salary | ManagerId |
                                  -+----+-------+--------+-----------+
                                  -| 1  | Joe   | 70000  | 3         |
                                  -| 2  | Henry | 80000  | 4         |
                                  -| 3  | Sam   | 60000  | NULL      |
                                  -| 4  | Max   | 90000  | NULL      |
                                  -+----+-------+--------+-----------+
                                  -
                                  -

                                  Given the Employee table, write a SQL query that finds out employees who earn more than their managers. For the above table, Joe is the only employee who earns more than his manager.

                                  -
                                  +----------+
                                  -| Employee |
                                  -+----------+
                                  -| Joe      |
                                  -+----------+
                                  -
                                  -

                                  Solution 1

                                  -
                                  # Write your MySQL query statement below
                                  -select
                                  -  a.Name as Employee
                                  -  from Employee a
                                  -  left join Employee b
                                  -  on a.ManagerId = b.Id
                                  -  where a.Salary > b.Salary
                                  -
                                  -

                                  Explain:

                                  -

                                  nope.

                                  -

                                  Complexity:

                                  -
                                    -
                                  • Time complexity :
                                  • -
                                  • Space complexity :
                                  • -
                                  -

                                  Solution 2

                                  -
                                  # Write your MySQL query statement below
                                  -select
                                  -  a.Name as Employee
                                  -  from Employee a, Employee b
                                  -  where a.ManagerId = b.Id
                                  -    and a.Salary > b.Salary
                                  -
                                  -

                                  Explain:

                                  -

                                  nope.

                                  -

                                  Complexity:

                                  -
                                    -
                                  • Time complexity :
                                  • -
                                  • Space complexity :
                                  • -
                                  github
                                  \ No newline at end of file diff --git a/docs/problem/evaluate-reverse-polish-notation.html b/docs/problem/evaluate-reverse-polish-notation.html deleted file mode 100644 index 100e3f1..0000000 --- a/docs/problem/evaluate-reverse-polish-notation.html +++ /dev/null @@ -1,76 +0,0 @@ -Evaluate Reverse Polish Notation - LeetCode javascript solutions

                                  150. Evaluate Reverse Polish Notation

                                  Difficulty:
                                  Related Topics:

                                  Problem

                                  -

                                  Evaluate the value of an arithmetic expression in Reverse Polish Notation.

                                  -

                                  Valid operators are +, -, *, /. Each operand may be an integer or another expression.

                                  -

                                  Note:

                                  -
                                    -
                                  • Division between two integers should truncate toward zero.
                                  • -
                                  • The given RPN expression is always valid. That means the expression would always evaluate to a result and there won't be any divide by zero operation.
                                  • -
                                  -

                                  Example 1:

                                  -
                                  Input: ["2", "1", "+", "3", "*"]
                                  -Output: 9
                                  -Explanation: ((2 + 1) * 3) = 9
                                  -
                                  -

                                  Example 2:

                                  -
                                  Input: ["4", "13", "5", "/", "+"]
                                  -Output: 6
                                  -Explanation: (4 + (13 / 5)) = 6
                                  -
                                  -

                                  Example 3:

                                  -
                                  Input: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
                                  -Output: 22
                                  -Explanation: 
                                  -  ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
                                  -= ((10 * (6 / (12 * -11))) + 17) + 5
                                  -= ((10 * (6 / -132)) + 17) + 5
                                  -= ((10 * 0) + 17) + 5
                                  -= (0 + 17) + 5
                                  -= 17 + 5
                                  -= 22
                                  -
                                  -

                                  Solution

                                  -
                                  /**
                                  - * @param {string[]} tokens
                                  - * @return {number}
                                  - */
                                  -var evalRPN = function(tokens) {
                                  -  var stack = [];
                                  -  var len = tokens.length;
                                  -  var n1 = 0;
                                  -  var n2 = 0;
                                  -  var n3 = 0;
                                  -  var token = '';
                                  -  for (var i = 0; i < len; i++) {
                                  -    token = tokens[i];
                                  -    switch (token) {
                                  -      case '+':
                                  -        stack.push(stack.pop() + stack.pop());
                                  -        break;
                                  -      case '-':
                                  -        n1 = stack.pop();
                                  -        n2 = stack.pop();
                                  -        stack.push(n2 - n1);
                                  -        break;
                                  -      case '*':
                                  -        stack.push(stack.pop() * stack.pop());
                                  -        break;
                                  -      case '/':
                                  -        n1 = stack.pop();
                                  -        n2 = stack.pop();
                                  -        n3 = n2 / n1;
                                  -        stack.push(n3 > 0 ? Math.floor(n3) : Math.ceil(n3));
                                  -        break;
                                  -      default:
                                  -        stack.push(Number(token));
                                  -    }
                                  -  }
                                  -  return stack.pop();
                                  -};
                                  -
                                  -

                                  Explain:

                                  -

                                  nope.

                                  -

                                  Complexity:

                                  -
                                    -
                                  • Time complexity : O(n).
                                  • -
                                  • Space complexity : O(n).
                                  • -
                                  github
                                  \ No newline at end of file diff --git a/docs/problem/excel-sheet-column-number.html b/docs/problem/excel-sheet-column-number.html deleted file mode 100644 index da82771..0000000 --- a/docs/problem/excel-sheet-column-number.html +++ /dev/null @@ -1,52 +0,0 @@ -Excel Sheet Column Number - LeetCode javascript solutions

                                  171. Excel Sheet Column Number

                                  Difficulty:
                                  Related Topics:
                                  Similar Questions:

                                  Problem

                                  -

                                  Given a column title as appear in an Excel sheet, return its corresponding column number.

                                  -

                                  For example:

                                  -
                                      A -> 1
                                  -    B -> 2
                                  -    C -> 3
                                  -    ...
                                  -    Z -> 26
                                  -    AA -> 27
                                  -    AB -> 28 
                                  -    ...
                                  -
                                  -

                                  Example 1:

                                  -
                                  Input: "A"
                                  -Output: 1
                                  -
                                  -

                                  Example 2:

                                  -
                                  Input: "AB"
                                  -Output: 28
                                  -
                                  -

                                  Example 3:

                                  -
                                  Input: "ZY"
                                  -Output: 701
                                  -
                                  -

                                  Solution

                                  -
                                  /**
                                  - * @param {string} s
                                  - * @return {number}
                                  - */
                                  -var titleToNumber = function(s) {
                                  -  var res = 0;
                                  -  var num = 0;
                                  -  var len = s.length;
                                  -  for (var i = 0; i < len; i++) {
                                  -    num = getNum(s[len - 1 - i]);
                                  -    res += Math.pow(26, i) * num;
                                  -  }
                                  -  return res;
                                  -};
                                  -
                                  -var getNum = function (char) {
                                  -  var start = 'A'.charCodeAt(0) - 1;
                                  -  return char.charCodeAt(0) - start;
                                  -};
                                  -
                                  -

                                  Explain:

                                  -

                                  nope.

                                  -

                                  Complexity:

                                  -
                                    -
                                  • Time complexity : O(n).
                                  • -
                                  • Space complexity : O(1).
                                  • -
                                  github
                                  \ No newline at end of file diff --git a/docs/problem/excel-sheet-column-title.html b/docs/problem/excel-sheet-column-title.html deleted file mode 100644 index b885a32..0000000 --- a/docs/problem/excel-sheet-column-title.html +++ /dev/null @@ -1,54 +0,0 @@ -Excel Sheet Column Title - LeetCode javascript solutions

                                  168. Excel Sheet Column Title

                                  Difficulty:
                                  Related Topics:
                                  Similar Questions:

                                  Problem

                                  -

                                  Given a positive integer, return its corresponding column title as appear in an Excel sheet.

                                  -

                                  For example:

                                  -
                                      1 -> A
                                  -    2 -> B
                                  -    3 -> C
                                  -    ...
                                  -    26 -> Z
                                  -    27 -> AA
                                  -    28 -> AB 
                                  -    ...
                                  -
                                  -

                                  Example 1:

                                  -
                                  Input: 1
                                  -Output: "A"
                                  -
                                  -

                                  Example 2:

                                  -
                                  Input: 28
                                  -Output: "AB"
                                  -
                                  -

                                  Example 3:

                                  -
                                  Input: 701
                                  -Output: "ZY"
                                  -
                                  -

                                  Solution

                                  -
                                  /**
                                  - * @param {number} n
                                  - * @return {string}
                                  - */
                                  -var convertToTitle = function(n) {
                                  -  var num = n;
                                  -  var tmp = 0;
                                  -  var res = '';
                                  -  while (num > 0) {
                                  -    tmp = num % 26;
                                  -    if (tmp === 0) tmp = 26;
                                  -    res = getChar(tmp) + res;
                                  -    num = (num - tmp) / 26;
                                  -  }
                                  -  return res;
                                  -};
                                  -
                                  -var getChar = function (num) {
                                  -  var start = 'A'.charCodeAt(0);
                                  -  return String.fromCharCode(start + num - 1);
                                  -};
                                  -
                                  -

                                  Explain:

                                  -

                                  nope.

                                  -

                                  Complexity:

                                  -
                                    -
                                  • Time complexity : O(log(n)).
                                  • -
                                  • Space complexity : O(1).
                                  • -
                                  github
                                  \ No newline at end of file diff --git a/docs/problem/factorial-trailing-zeroes.html b/docs/problem/factorial-trailing-zeroes.html deleted file mode 100644 index 4743900..0000000 --- a/docs/problem/factorial-trailing-zeroes.html +++ /dev/null @@ -1,30 +0,0 @@ -Factorial Trailing Zeroes - LeetCode javascript solutions

                                  172. Factorial Trailing Zeroes

                                  Difficulty:
                                  Related Topics:

                                  Problem

                                  -

                                  Given an integer n, return the number of trailing zeroes in n!.

                                  -

                                  Example 1:

                                  -
                                  Input: 3
                                  -Output: 0
                                  -Explanation: 3! = 6, no trailing zero.
                                  -
                                  -

                                  Example 2:

                                  -
                                  Input: 5
                                  -Output: 1
                                  -Explanation: 5! = 120, one trailing zero.
                                  -
                                  -

                                  **Note: **Your solution should be in logarithmic time complexity.

                                  -

                                  Solution

                                  -
                                  /**
                                  - * @param {number} n
                                  - * @return {number}
                                  - */
                                  -var trailingZeroes = function(n) {
                                  -  if (n === 0) return 0;
                                  -  return Math.floor(n / 5) + trailingZeroes(Math.floor(n / 5));
                                  -};
                                  -
                                  -

                                  Explain:

                                  -

                                  nope.

                                  -

                                  Complexity:

                                  -
                                    -
                                  • Time complexity : O(log(n)).
                                  • -
                                  • Space complexity : O(1).
                                  • -
                                  github
                                  \ No newline at end of file diff --git a/docs/problem/find-and-replace-in-string.html b/docs/problem/find-and-replace-in-string.html deleted file mode 100644 index 0a076d9..0000000 --- a/docs/problem/find-and-replace-in-string.html +++ /dev/null @@ -1,105 +0,0 @@ -Find And Replace in String - LeetCode javascript solutions

                                  862. Find And Replace in String

                                  Difficulty:
                                  Related Topics:
                                  Similar Questions:

                                    Problem

                                    -

                                    To some string S, we will perform some replacement operations that replace groups of letters with new ones (not necessarily the same size).

                                    -

                                    Each replacement operation has 3 parameters: a starting index i, a source word x and a target word y. The rule is that if x starts at position i in the original string S, then we will replace that occurrence of x with y. If not, we do nothing.

                                    -

                                    For example, if we have S = "abcd" and we have some replacement operation i = 2, x = "cd", y = "ffff", then because "cd" starts at position 2 in the original string S, we will replace it with "ffff".

                                    -

                                    Using another example on S = "abcd", if we have both the replacement operation i = 0, x = "ab", y = "eee", as well as another replacement operation i = 2, x = "ec", y = "ffff", this second operation does nothing because in the original string S[2] = 'c', which doesn't match x[0] = 'e'.

                                    -

                                    All these operations occur simultaneously. It's guaranteed that there won't be any overlap in replacement: for example, S = "abc", indexes = [0, 1], sources = ["ab","bc"] is not a valid test case.

                                    -

                                    Example 1:

                                    -
                                    Input: S = "abcd", indexes = [0,2], sources = ["a","cd"], targets = ["eee","ffff"]
                                    -Output: "eeebffff"
                                    -Explanation: "a" starts at index 0 in S, so it's replaced by "eee".
                                    -"cd" starts at index 2 in S, so it's replaced by "ffff".
                                    -
                                    -

                                    Example 2:

                                    -
                                    Input: S = "abcd", indexes = [0,2], sources = ["ab","ec"], targets = ["eee","ffff"]
                                    -Output: "eeecd"
                                    -Explanation: "ab" starts at index 0 in S, so it's replaced by "eee". 
                                    -"ec" doesn't starts at index 2 in the original S, so we do nothing.
                                    -
                                    -

                                    Notes:

                                    -
                                      -
                                    • 0 <= indexes.length = sources.length = targets.length <= 100
                                    • -
                                    • 0 < indexes[i] < S.length <= 1000
                                    • -
                                    • All characters in given inputs are lowercase letters.
                                    • -
                                    -

                                    Solution 1

                                    -
                                    /**
                                    - * @param {string} S
                                    - * @param {number[]} indexes
                                    - * @param {string[]} sources
                                    - * @param {string[]} targets
                                    - * @return {string}
                                    - */
                                    -var findReplaceString = function(S, indexes, sources, targets) {
                                    -  var len = S.length;
                                    -  var len2 = indexes.length;
                                    -  var map = {};
                                    -  var res = '';
                                    -  var i = 0;
                                    -
                                    -  if (len2 === 0) return S;
                                    -
                                    -  for (var k = 0; k < len2; k++) {
                                    -    map[indexes[k]] = [sources[k], targets[k]];
                                    -  }
                                    -
                                    -  while (i < len) {
                                    -    if (map[i] && S.substr(i, map[i][0].length) === map[i][0]) {
                                    -      res += map[i][1];
                                    -      i += Math.max(map[i][0].length, 1);
                                    -    } else {
                                    -      res += S[i];
                                    -      i += 1;
                                    -    }
                                    -  }
                                    -
                                    -  return res;
                                    -};
                                    -
                                    -

                                    Explain:

                                    -

                                    nope.

                                    -

                                    Complexity:

                                    -
                                      -
                                    • Time complexity : O(n). nS.length
                                    • -
                                    • Space complexity : O(n).
                                    • -
                                    -

                                    Solution 2

                                    -
                                    /**
                                    - * @param {string} S
                                    - * @param {number[]} indexes
                                    - * @param {string[]} sources
                                    - * @param {string[]} targets
                                    - * @return {string}
                                    - */
                                    -var findReplaceString = function(S, indexes, sources, targets) {
                                    -  var len = indexes.length;
                                    -  var sorted = [];
                                    -  var map = {};
                                    -  var index = 0;
                                    -
                                    -  if (len === 0) return S;
                                    -
                                    -  for (var i = 0; i < len; i++) {
                                    -    map[indexes[i]] = i;
                                    -    sorted.push(indexes[i]);
                                    -  }
                                    -
                                    -  sorted.sort((a, b) => a - b);
                                    -
                                    -  for (var j = len - 1; j >= 0; j--) {
                                    -    index = map[sorted[j]];
                                    -    if (S.substr(sorted[j], sources[index].length) === sources[index]) {
                                    -      S = S.substr(0, sorted[j]) + targets[index] + S.substr(sorted[j] + sources[index].length);
                                    -    }
                                    -  }
                                    -
                                    -  return S;
                                    -};
                                    -
                                    -

                                    Explain:

                                    -

                                    indexes 排序,然后从后往前依次替换。

                                    -

                                    Complexity:

                                    -
                                      -
                                    • Time complexity : O(n * log(n)). nindexes.length
                                    • -
                                    • Space complexity : O(n).
                                    • -
                                    github
                                    \ No newline at end of file diff --git a/docs/problem/find-minimum-in-rotated-sorted-array-ii.html b/docs/problem/find-minimum-in-rotated-sorted-array-ii.html deleted file mode 100644 index 8088ffe..0000000 --- a/docs/problem/find-minimum-in-rotated-sorted-array-ii.html +++ /dev/null @@ -1,47 +0,0 @@ -Find Minimum in Rotated Sorted Array II - LeetCode javascript solutions

                                    154. Find Minimum in Rotated Sorted Array II

                                    Difficulty:
                                    Related Topics:

                                    Problem

                                    -

                                    Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

                                    -

                                    (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).

                                    -

                                    Find the minimum element.

                                    -

                                    The array may contain duplicates.

                                    -

                                    Example 1:

                                    -
                                    Input: [1,3,5]
                                    -Output: 1
                                    -
                                    -

                                    Example 2:

                                    -
                                    Input: [2,2,2,0,1]
                                    -Output: 0
                                    -
                                    -

                                    Note:

                                    -
                                      -
                                    • This is a follow up problem to Find Minimum in Rotated Sorted Array.
                                    • -
                                    • Would allow duplicates affect the run-time complexity? How and why?
                                    • -
                                    -

                                    Solution

                                    -
                                    /**
                                    - * @param {number[]} nums
                                    - * @return {number}
                                    - */
                                    -var findMin = function(nums) {
                                    -  var left = 0;
                                    -  var right = nums.length - 1;
                                    -  var mid = 0;
                                    -  while (left < right) {
                                    -    mid = Math.floor((left + right) / 2);
                                    -    if (nums[mid] > nums[right]) {
                                    -      left = mid + 1;
                                    -    } else if (nums[mid] < nums[right]) {
                                    -      right = mid;
                                    -    } else {
                                    -      right--;
                                    -    }
                                    -  }
                                    -  return nums[left];
                                    -};
                                    -
                                    -

                                    Explain:

                                    -

                                    nope.

                                    -

                                    Complexity:

                                    -
                                      -
                                    • Time complexity : O(n).
                                    • -
                                    • Space complexity : O(n).
                                    • -
                                    github
                                    \ No newline at end of file diff --git a/docs/problem/find-minimum-in-rotated-sorted-array.html b/docs/problem/find-minimum-in-rotated-sorted-array.html deleted file mode 100644 index 74d1f0c..0000000 --- a/docs/problem/find-minimum-in-rotated-sorted-array.html +++ /dev/null @@ -1,41 +0,0 @@ -Find Minimum in Rotated Sorted Array - LeetCode javascript solutions

                                    153. Find Minimum in Rotated Sorted Array

                                    Difficulty:
                                    Related Topics:

                                    Problem

                                    -

                                    Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

                                    -

                                    (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).

                                    -

                                    Find the minimum element.

                                    -

                                    You may assume no duplicate exists in the array.

                                    -

                                    Example 1:

                                    -
                                    Input: [3,4,5,1,2] 
                                    -Output: 1
                                    -
                                    -

                                    Example 2:

                                    -
                                    Input: [4,5,6,7,0,1,2]
                                    -Output: 0
                                    -
                                    -

                                    Solution

                                    -
                                    /**
                                    - * @param {number[]} nums
                                    - * @return {number}
                                    - */
                                    -var findMin = function(nums) {
                                    -  var left = 0;
                                    -  var right = nums.length - 1;
                                    -  var mid = 0;
                                    -  while (left < right) {
                                    -    mid = Math.floor((left + right) / 2);
                                    -    if (nums[mid - 1] > nums[mid]) return nums[mid];
                                    -    if (nums[mid] < nums[left] || nums[mid] < nums[right]) {
                                    -      right = mid - 1;
                                    -    } else {
                                    -      left = mid + 1;
                                    -    }
                                    -  }
                                    -  return nums[left];
                                    -};
                                    -
                                    -

                                    Explain:

                                    -

                                    nope.

                                    -

                                    Complexity:

                                    -
                                      -
                                    • Time complexity : O(log(n)).
                                    • -
                                    • Space complexity : O(1).
                                    • -
                                    github
                                    \ No newline at end of file diff --git a/docs/problem/find-peak-element.html b/docs/problem/find-peak-element.html deleted file mode 100644 index 1dc406f..0000000 --- a/docs/problem/find-peak-element.html +++ /dev/null @@ -1,48 +0,0 @@ -Find Peak Element - LeetCode javascript solutions

                                    162. Find Peak Element

                                    Difficulty:
                                    Related Topics:

                                    Problem

                                    -

                                    A peak element is an element that is greater than its neighbors.

                                    -

                                    Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index.

                                    -

                                    The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.

                                    -

                                    You may imagine that nums[-1] = nums[n] = -∞.

                                    -

                                    Example 1:

                                    -
                                    Input: nums = [1,2,3,1]
                                    -Output: 2
                                    -Explanation: 3 is a peak element and your function should return the index number 2.
                                    -
                                    -

                                    Example 2:

                                    -
                                    Input: nums = [1,2,1,3,5,6,4]
                                    -Output: 1 or 5 
                                    -Explanation: Your function can return either index number 1 where the peak element is 2, 
                                    -             or index number 5 where the peak element is 6.
                                    -
                                    -

                                    Note:

                                    -

                                    Your solution should be in logarithmic complexity.

                                    -

                                    Solution

                                    -
                                    /**
                                    - * @param {number[]} nums
                                    - * @return {number}
                                    - */
                                    -var findPeakElement = function(nums) {
                                    -  if (!nums.length) return -1;
                                    -  var left = 0;
                                    -  var right = nums.length - 1;
                                    -  var mid1 = 0;
                                    -  var mid2 = 0;
                                    -  while (left < right) {
                                    -    mid1 = Math.floor((left + right) / 2);
                                    -    mid2 = mid1 + 1;
                                    -    if (nums[mid1] < nums[mid2]) {
                                    -      left = mid2;
                                    -    } else {
                                    -      right = mid1;
                                    -    }
                                    -  }
                                    -  return left;
                                    -};
                                    -
                                    -

                                    Explain:

                                    -

                                    nope.

                                    -

                                    Complexity:

                                    -
                                      -
                                    • Time complexity : O(n).
                                    • -
                                    • Space complexity : O(n).
                                    • -
                                    github
                                    \ No newline at end of file diff --git a/docs/problem/first-missing-positive.html b/docs/problem/first-missing-positive.html deleted file mode 100644 index 41a055e..0000000 --- a/docs/problem/first-missing-positive.html +++ /dev/null @@ -1,50 +0,0 @@ -First Missing Positive - LeetCode javascript solutions

                                    41. First Missing Positive

                                    Difficulty:
                                    Related Topics:

                                    Problem

                                    -

                                    Given an unsorted integer array, find the smallest missing positive integer.

                                    -

                                    Example 1:

                                    -
                                    Input: [1,2,0]
                                    -Output: 3
                                    -
                                    -

                                    Example 2:

                                    -
                                    Input: [3,4,-1,1]
                                    -Output: 2
                                    -
                                    -

                                    Example 3:

                                    -
                                    Input: [7,8,9,11,12]
                                    -Output: 1
                                    -
                                    -

                                    Note:

                                    -

                                    Your algorithm should run in O(n) time and uses constant extra space.

                                    -

                                    Solution

                                    -
                                    /**
                                    - * @param {number[]} nums
                                    - * @return {number}
                                    - */
                                    -var firstMissingPositive = function(nums) {
                                    -    var len = nums.length;
                                    -    var tmp = 0;
                                    -    var i = 0;
                                    -    while (i < len) {
                                    -        tmp = nums[i];
                                    -        if (tmp > 0 && tmp !== i + 1 && tmp !== nums[tmp - 1]) swap(nums, i, tmp - 1);
                                    -        else i++;
                                    -    }
                                    -    for (var j = 0; j < len; j++) {
                                    -        if (nums[j] !== j + 1) return j + 1;
                                    -    }
                                    -    return len + 1;
                                    -};
                                    -
                                    -var swap = function (arr, i, j) {
                                    -    var tmp = arr[i];
                                    -    arr[i] = arr[j];
                                    -    arr[j] = tmp;
                                    -};
                                    -
                                    -

                                    Explain:

                                    -

                                    循环把 nums[i] 放到 nums[nums[i] - 1] 那里,最后 nums[i] !== i + 1 就是不对的

                                    -

                                    即比如 [3, 4, -2, 1] => [1, -2, 3, 4],即缺 2

                                    -

                                    Complexity:

                                    -
                                      -
                                    • Time complexity : O(n).
                                    • -
                                    • Space complexity : O(1).
                                    • -
                                    github
                                    \ No newline at end of file diff --git a/docs/problem/flatten-binary-tree-to-linked-list.html b/docs/problem/flatten-binary-tree-to-linked-list.html deleted file mode 100644 index 398ce8c..0000000 --- a/docs/problem/flatten-binary-tree-to-linked-list.html +++ /dev/null @@ -1,61 +0,0 @@ -Flatten Binary Tree to Linked List - LeetCode javascript solutions

                                    114. Flatten Binary Tree to Linked List

                                    Difficulty:
                                    Related Topics:
                                    Similar Questions:

                                      Problem

                                      -

                                      Given a binary tree, flatten it to a linked list in-place.

                                      -

                                      For example, given the following tree:

                                      -
                                          1
                                      -   / \
                                      -  2   5
                                      - / \   \
                                      -3   4   6
                                      -
                                      -

                                      The flattened tree should look like:

                                      -
                                      1
                                      - \
                                      -  2
                                      -   \
                                      -    3
                                      -     \
                                      -      4
                                      -       \
                                      -        5
                                      -         \
                                      -          6
                                      -
                                      -

                                      Solution

                                      -
                                      /**
                                      - * Definition for a binary tree node.
                                      - * function TreeNode(val) {
                                      - *     this.val = val;
                                      - *     this.left = this.right = null;
                                      - * }
                                      - */
                                      -/**
                                      - * @param {TreeNode} root
                                      - * @return {void} Do not return anything, modify root in-place instead.
                                      - */
                                      -var flatten = function (root) {
                                      -  helper(root);
                                      -};
                                      -
                                      -var helper = function (root) {
                                      -  if (!root) return null;
                                      -
                                      -  var leftLast = helper(root.left);
                                      -  var rightLast = helper(root.right);
                                      -
                                      -  if (root.left) {
                                      -    leftLast.right = root.right;
                                      -    root.right = root.left;
                                      -  }
                                      -
                                      -  root.left = null;
                                      -
                                      -  return rightLast || leftLast || root;
                                      -};
                                      -
                                      -

                                      Explain:

                                      -

                                      nope.

                                      -

                                      Complexity:

                                      -
                                        -
                                      • Time complexity : O(n).
                                      • -
                                      • Space complexity : O(1).
                                      • -
                                      github
                                      \ No newline at end of file diff --git a/docs/problem/flipping-an-image.html b/docs/problem/flipping-an-image.html deleted file mode 100644 index 3e77946..0000000 --- a/docs/problem/flipping-an-image.html +++ /dev/null @@ -1,58 +0,0 @@ -Flipping an Image - LeetCode javascript solutions

                                      861. Flipping an Image

                                      Difficulty:
                                      Related Topics:
                                      Similar Questions:

                                        Problem

                                        -

                                        Given a binary matrix A, we want to flip the image horizontally, then invert it, and return the resulting image.

                                        -

                                        To flip an image horizontally means that each row of the image is reversed. For example, flipping [1, 1, 0] horizontally results in [0, 1, 1].

                                        -

                                        To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0. For example, inverting [0, 1, 1] results in [1, 0, 0].

                                        -

                                        Example 1:

                                        -
                                        Input: [[1,1,0],[1,0,1],[0,0,0]]
                                        -Output: [[1,0,0],[0,1,0],[1,1,1]]
                                        -Explanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]].
                                        -Then, invert the image: [[1,0,0],[0,1,0],[1,1,1]]
                                        -
                                        -

                                        Example 2:

                                        -
                                        Input: [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]
                                        -Output: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
                                        -Explanation: First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]].
                                        -Then invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
                                        -
                                        -

                                        Notes:

                                        -
                                          -
                                        • 1 <= A.length = A[0].length <= 20
                                        • -
                                        • 0 <= A[i][j] <= 1
                                        • -
                                        -

                                        Solution

                                        -
                                        /**
                                        - * @param {number[][]} A
                                        - * @return {number[][]}
                                        - */
                                        -var flipAndInvertImage = function(A) {
                                        -  var len = A.length;
                                        -  var len2 = Math.ceil(len / 2);
                                        -  for (var i = 0; i < len; i++) {
                                        -    for (var j = 0; j < len2; j++) {
                                        -      if (j !== len - j - 1) {
                                        -        swap(A[i], j, len - j - 1);
                                        -        reverse(A[i], len - j - 1);
                                        -      }
                                        -      reverse(A[i], j);
                                        -    }
                                        -  }
                                        -  return A;
                                        -};
                                        -
                                        -var swap = function (arr, i, j) {
                                        -  var tmp = arr[i];
                                        -  arr[i] = arr[j];
                                        -  arr[j] = tmp;
                                        -};
                                        -
                                        -var reverse = function (arr, i) {
                                        -  arr[i] = arr[i] ? 0 : 1;
                                        -};
                                        -
                                        -

                                        Explain:

                                        -

                                        nope.

                                        -

                                        Complexity:

                                        -
                                          -
                                        • Time complexity : O(n^2). nA.length
                                        • -
                                        • Space complexity : O(1).
                                        • -
                                        github
                                        \ No newline at end of file diff --git a/docs/problem/fraction-to-recurring-decimal.html b/docs/problem/fraction-to-recurring-decimal.html deleted file mode 100644 index 107c393..0000000 --- a/docs/problem/fraction-to-recurring-decimal.html +++ /dev/null @@ -1,61 +0,0 @@ -Fraction to Recurring Decimal - LeetCode javascript solutions

                                        166. Fraction to Recurring Decimal

                                        Difficulty:
                                        Related Topics:
                                        Similar Questions:

                                          Problem

                                          -

                                          Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.

                                          -

                                          If the fractional part is repeating, enclose the repeating part in parentheses.

                                          -

                                          Example 1:

                                          -
                                          Input: numerator = 1, denominator = 2
                                          -Output: "0.5"
                                          -
                                          -

                                          Example 2:

                                          -
                                          Input: numerator = 2, denominator = 1
                                          -Output: "2"
                                          -
                                          -

                                          Example 3:

                                          -
                                          Input: numerator = 2, denominator = 3
                                          -Output: "0.(6)"
                                          -
                                          -

                                          Solution

                                          -
                                          /**
                                          - * @param {number} numerator
                                          - * @param {number} denominator
                                          - * @return {string}
                                          - */
                                          -var fractionToDecimal = function(numerator, denominator) {
                                          -  if (denominator === 0) return 'NaN';
                                          -
                                          -  var sign = numerator !== 0 && ((numerator > 0) ^ (denominator > 0));
                                          -  var num = Math.abs(numerator);
                                          -  var de = Math.abs(denominator);
                                          -  var result = sign ? '-' : '';
                                          -  var map = {};
                                          -
                                          -  result += Math.floor(num / de);
                                          -  num %= de;
                                          -
                                          -  if (num === 0) return result;
                                          -
                                          -  result += '.';
                                          -
                                          -  while (num > 0) {
                                          -    num *= 10;
                                          -
                                          -    if (map[num] !== undefined) {
                                          -      result = result.substr(0, map[num]) + '(' + result.substr(map[num]) + ')';
                                          -      break;
                                          -    } else {
                                          -      map[num] = result.length;
                                          -    }
                                          -
                                          -    result += Math.floor(num / de);
                                          -    num %= de;
                                          -  }
                                          -
                                          -  return result;
                                          -};
                                          -
                                          -

                                          Explain:

                                          -

                                          nope.

                                          -

                                          Complexity:

                                          -
                                            -
                                          • Time complexity : O(n).
                                          • -
                                          • Space complexity : O(n).
                                          • -
                                          github
                                          \ No newline at end of file diff --git a/docs/problem/friend-circles.html b/docs/problem/friend-circles.html deleted file mode 100644 index 7b5fc16..0000000 --- a/docs/problem/friend-circles.html +++ /dev/null @@ -1,62 +0,0 @@ -Friend Circles - LeetCode javascript solutions

                                          547. Friend Circles

                                          Difficulty:

                                          Problem

                                          -

                                          There are N students in a class. Some of them are friends, while some are not. Their friendship is transitive in nature. For example, if A is a direct friend of B, and B is a direct friend of C, then A is an indirect friend of C. And we defined a friend circle is a group of students who are direct or indirect friends.

                                          -

                                          Given a N*N matrix M representing the friend relationship between students in the class. If M[i][j] = 1, then the ith and jth students are direct friends with each other, otherwise not. And you have to output the total number of friend circles among all the students.

                                          -

                                          Example 1:

                                          -
                                          Input: 
                                          -[[1,1,0],
                                          - [1,1,0],
                                          - [0,0,1]]
                                          -Output: 2
                                          -Explanation:The 0th and 1st students are direct friends, so they are in a friend circle. The 2nd student himself is in a friend circle. So return 2.
                                          -
                                          -

                                          Example 2:

                                          -
                                          Input: 
                                          -[[1,1,0],
                                          - [1,1,1],
                                          - [0,1,1]]
                                          -Output: 1
                                          -Explanation:The 0th and 1st students are direct friends, the 1st and 2nd students are direct friends, so the 0th and 2nd students are indirect friends. All of them are in the same friend circle, so return 1.
                                          -
                                          -

                                          Note:

                                          -
                                            -
                                          • N is in range [1,200].
                                          • -
                                          • M[i][i] = 1 for all students.
                                          • -
                                          • If M[i][j] = 1, then M[j][i] = 1.
                                          • -
                                          -

                                          Solution

                                          -
                                          /**
                                          - * @param {number[][]} M
                                          - * @return {number}
                                          - */
                                          -
                                          -var findCircleNum = function(M) {
                                          -  var count = 0;
                                          -  var n = M.length;
                                          -  var map = Array(n);
                                          -
                                          -  for (var i = 0; i < n; i++) {
                                          -    if (!map[i]) {
                                          -      find(map, i, M);
                                          -      count++;
                                          -    }
                                          -  }
                                          -
                                          -  return count;
                                          -};
                                          -
                                          -var find = function (map, i, M) {
                                          -  for (var j = 0; j < M.length; j++) {
                                          -    if (i !== j && M[i][j] === 1 && !map[j]) {
                                          -      map[j] = 1;
                                          -      find(map, j, M);
                                          -    }
                                          -  }
                                          -};
                                          -
                                          -

                                          Explain:

                                          -

                                          nope.

                                          -

                                          Complexity:

                                          -
                                            -
                                          • Time complexity : O(n^2).
                                          • -
                                          • Space complexity : O(n).
                                          • -
                                          github
                                          \ No newline at end of file diff --git a/docs/problem/gas-station.html b/docs/problem/gas-station.html deleted file mode 100644 index eb264dc..0000000 --- a/docs/problem/gas-station.html +++ /dev/null @@ -1,73 +0,0 @@ -Gas Station - LeetCode javascript solutions

                                          134. Gas Station

                                          Difficulty:
                                          Related Topics:
                                          Similar Questions:

                                            Problem

                                            -

                                            There are N gas stations along a circular route, where the amount of gas at station i is gas[i].

                                            -

                                            You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.

                                            -

                                            Return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1.

                                            -

                                            Note:

                                            -
                                              -
                                            • If there exists a solution, it is guaranteed to be unique.
                                            • -
                                            • Both input arrays are non-empty and have the same length.
                                            • -
                                            • Each element in the input arrays is a non-negative integer.
                                            • -
                                            -

                                            Example 1:

                                            -
                                            Input: 
                                            -gas  = [1,2,3,4,5]
                                            -cost = [3,4,5,1,2]
                                            -
                                            -Output: 3
                                            -
                                            -Explanation:
                                            -Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
                                            -Travel to station 4. Your tank = 4 - 1 + 5 = 8
                                            -Travel to station 0. Your tank = 8 - 2 + 1 = 7
                                            -Travel to station 1. Your tank = 7 - 3 + 2 = 6
                                            -Travel to station 2. Your tank = 6 - 4 + 3 = 5
                                            -Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.
                                            -Therefore, return 3 as the starting index.
                                            -
                                            -

                                            Example 2:

                                            -
                                            Input: 
                                            -gas  = [2,3,4]
                                            -cost = [3,4,3]
                                            -
                                            -Output: -1
                                            -
                                            -Explanation:
                                            -You can't start at station 0 or 1, as there is not enough gas to travel to the next station.
                                            -Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
                                            -Travel to station 0. Your tank = 4 - 3 + 2 = 3
                                            -Travel to station 1. Your tank = 3 - 3 + 3 = 3
                                            -You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.
                                            -Therefore, you can't travel around the circuit once no matter where you start.
                                            -
                                            -

                                            Solution

                                            -
                                            /**
                                            - * @param {number[]} gas
                                            - * @param {number[]} cost
                                            - * @return {number}
                                            - */
                                            -var canCompleteCircuit = function(gas, cost) {
                                            -  var len = gas.length;
                                            -  var tank = 0;
                                            -  var total = 0;
                                            -  var start = 0;
                                            -  for (var i = 0; i < len; i++) {
                                            -    tank += gas[i] - cost[i];
                                            -    if (tank < 0) {
                                            -      start = i + 1;
                                            -      total += tank;
                                            -      tank = 0;
                                            -    }
                                            -  }
                                            -  return tank + total >= 0 ? start : -1;
                                            -};
                                            -
                                            -

                                            Explain:

                                            -
                                              -
                                            1. n 点到不了 m 点,则其间所有点都到不了 m
                                            2. -
                                            3. 总和大于等于 0 说明有解
                                            4. -
                                            -

                                            Complexity:

                                            -
                                              -
                                            • Time complexity : O(n).
                                            • -
                                            • Space complexity : O(1).
                                            • -
                                            github
                                            \ No newline at end of file diff --git a/docs/problem/generate-parentheses.html b/docs/problem/generate-parentheses.html deleted file mode 100644 index 85e15be..0000000 --- a/docs/problem/generate-parentheses.html +++ /dev/null @@ -1,43 +0,0 @@ -Generate Parentheses - LeetCode javascript solutions

                                            22. Generate Parentheses

                                            Difficulty:
                                            Related Topics:

                                            Problem

                                            -

                                            Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

                                            -

                                            For example, given n = 3, a solution set is:

                                            -
                                            [
                                            -  "((()))",
                                            -  "(()())",
                                            -  "(())()",
                                            -  "()(())",
                                            -  "()()()"
                                            -]
                                            -
                                            -

                                            Solution

                                            -
                                            /**
                                            - * @param {number} n
                                            - * @return {string[]}
                                            - */
                                            -var generateParenthesis = function(n) {
                                            -  var res = [];
                                            -  if (n < 1) return res;
                                            -  generate(res, '', n, n);
                                            -  return res;
                                            -};
                                            -
                                            -var generate = function (res, str, ll, rr) {
                                            -  if (ll || rr) {
                                            -    if (rr > ll) generate(res, str + ')', ll, rr - 1);
                                            -    if (ll) generate(res, str + '(', ll - 1, rr);
                                            -  } else {
                                            -    res.push(str);
                                            -  }
                                            -};
                                            -
                                            -

                                            Explain:

                                            -

                                            每一层最多两种情况:

                                            -
                                              -
                                            1. 右括号比左括号多,加右括号
                                            2. -
                                            3. 还有左括号,加左括号
                                            4. -
                                            -

                                            Complexity:

                                            -
                                              -
                                            • Time complexity : O((4^n)/(n^(-1))).
                                            • -
                                            • Space complexity : O((4^n)/(n^(-1))).
                                            • -
                                            github
                                            \ No newline at end of file diff --git a/docs/problem/gray-code.html b/docs/problem/gray-code.html deleted file mode 100644 index b8406ec..0000000 --- a/docs/problem/gray-code.html +++ /dev/null @@ -1,67 +0,0 @@ -Gray Code - LeetCode javascript solutions

                                            89. Gray Code

                                            Difficulty:
                                            Related Topics:
                                            Similar Questions:

                                            Problem

                                            -

                                            The gray code is a binary numeral system where two successive values differ in only one bit.

                                            -

                                            Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.

                                            -

                                            For example, given n = 2, return [0,1,3,2]. Its gray code sequence is:

                                            -
                                            00 - 0
                                            -01 - 1
                                            -11 - 3
                                            -10 - 2
                                            -
                                            -

                                            Note:

                                            -

                                            For a given n, a gray code sequence is not uniquely defined.

                                            -

                                            For example, [0,2,3,1] is also a valid gray code sequence according to the above definition.

                                            -

                                            For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that.

                                            -

                                            Solution 1

                                            -
                                            /**
                                            - * @param {number} n
                                            - * @return {number[]}
                                            - */
                                            -var grayCode = function(n) {
                                            -  var res = [0];
                                            -  helper(n, res, 0);
                                            -  return res;
                                            -};
                                            -
                                            -var helper = function (n, res, num) {
                                            -  if (num >= n) return;
                                            -  var len = res.length;
                                            -  for (var i = len - 1; i >= 0; i--) {
                                            -    res.push(res[i] + len);
                                            -  }
                                            -  helper(n, res, num + 1);
                                            -};
                                            -
                                            -

                                            Explain:

                                            -

                                            nope.

                                            -

                                            Complexity:

                                            -
                                              -
                                            • Time complexity : O(2^n).
                                            • -
                                            • Space complexity : O(2^n).
                                            • -
                                            -

                                            Solution 2

                                            -
                                            /**
                                            - * @param {number} n
                                            - * @return {number[]}
                                            - */
                                            -var grayCode = function(n) {
                                            -  var res = [0];
                                            -  var len = 1;
                                            -
                                            -  for (var i = 0; i < n; i++) {
                                            -    len = res.length;
                                            -    for (var j = len - 1; j >= 0; j--) {
                                            -      res.push(res[j] + len);
                                            -    }
                                            -  }
                                            -
                                            -  return res;
                                            -};
                                            -
                                            -
                                            -

                                            Explain:

                                            -

                                            nope.

                                            -

                                            Complexity:

                                            -
                                              -
                                            • Time complexity : O(2^n).
                                            • -
                                            • Space complexity : O(2^n).
                                            • -
                                            github
                                            \ No newline at end of file diff --git a/docs/problem/group-anagrams.html b/docs/problem/group-anagrams.html deleted file mode 100644 index ac289d1..0000000 --- a/docs/problem/group-anagrams.html +++ /dev/null @@ -1,40 +0,0 @@ -Group Anagrams - LeetCode javascript solutions

                                            49. Group Anagrams

                                            Difficulty:
                                            Related Topics:

                                            Problem

                                            -

                                            Given an array of strings, group anagrams together.

                                            -

                                            Example:

                                            -
                                            Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
                                            -Output:
                                            -[
                                            -  ["ate","eat","tea"],
                                            -  ["nat","tan"],
                                            -  ["bat"]
                                            -]
                                            -
                                            -

                                            Note:

                                            -
                                              -
                                            • All inputs will be in lowercase.
                                            • -
                                            • The order of your output does not matter.
                                            • -
                                            -

                                            Solution

                                            -
                                            /**
                                            - * @param {string[]} strs
                                            - * @return {string[][]}
                                            - */
                                            -var groupAnagrams = function(strs) {
                                            -  var res = {};
                                            -  var str = '';
                                            -  var len = strs.length;
                                            -  for (var i = 0; i < len; i++) {
                                            -    str = Array.from(strs[i]).sort().join('');
                                            -    if (!res[str]) res[str] = [];
                                            -    res[str].push(strs[i]);
                                            -  }
                                            -  return Object.values(res);
                                            -};
                                            -
                                            -

                                            Explain:

                                            -

                                            把每个字符串排序一下,用哈希表存起来

                                            -

                                            Complexity:

                                            -
                                              -
                                            • Time complexity : O(m * nlog(n)). m 为数组长度, n 为字符长度。
                                            • -
                                            • Space complexity : O(m).
                                            • -
                                            github
                                            \ No newline at end of file diff --git a/docs/problem/happy-number.html b/docs/problem/happy-number.html deleted file mode 100644 index a421215..0000000 --- a/docs/problem/happy-number.html +++ /dev/null @@ -1,86 +0,0 @@ -Happy Number - LeetCode javascript solutions

                                            202. Happy Number

                                            Difficulty:
                                            Related Topics:
                                            Similar Questions:

                                            Problem

                                            -

                                            Write an algorithm to determine if a number is "happy".

                                            -

                                            A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.

                                            -

                                            **Example: **

                                            -
                                            Input: 19
                                            -Output: true
                                            -Explanation: 
                                            -12 + 92 = 82
                                            -82 + 22 = 68
                                            -62 + 82 = 100
                                            -12 + 02 + 02 = 1
                                            -
                                            -

                                            Solution 1

                                            -
                                            /**
                                            - * @param {number} n
                                            - * @return {boolean}
                                            - */
                                            -var isHappy = function(n) {
                                            -  var map = {};
                                            -  var tmp = 0;
                                            -
                                            -  if (n < 1) return false;
                                            -
                                            -  while (n !== 1 && !map[n]) {
                                            -    map[n] = true;
                                            -    tmp = 0;
                                            -
                                            -    while (n > 0) {
                                            -      tmp += Math.pow(n % 10, 2);
                                            -      n = Math.floor(n / 10);
                                            -    }
                                            -
                                            -    n = tmp;
                                            -  }
                                            -
                                            -  return n === 1;
                                            -};
                                            -
                                            -

                                            Explain:

                                            -

                                            nope.

                                            -

                                            Complexity:

                                            -
                                              -
                                            • Time complexity :
                                            • -
                                            • Space complexity :
                                            • -
                                            -

                                            Solution 2

                                            -
                                            /**
                                            - * @param {number} n
                                            - * @return {boolean}
                                            - */
                                            -var isHappy = function(n) {
                                            -  var fast = n;
                                            -  var slow = n;
                                            -
                                            -  if (n < 1) return false;
                                            -
                                            -  do {
                                            -    slow = getsumsquare(slow);
                                            -    fast = getsumsquare(getsumsquare(fast));
                                            -  } while (slow !== fast);
                                            -
                                            -  return slow === 1;
                                            -};
                                            -
                                            -var getsumsquare = function (n) {
                                            -  var sum = 0;
                                            -  var tmp = 0;
                                            -
                                            -  while (n > 0) {
                                            -    tmp = n % 10;
                                            -    sum += tmp * tmp;
                                            -    n = Math.floor(n / 10);
                                            -  }
                                            -
                                            -  return sum;
                                            -};
                                            -
                                            -

                                            Explain:

                                            -

                                            两种情况:有 1 和 循环。

                                            -

                                            循环的时候,在一个圈里,两人在相同的地方同时出发,一个人每次走一步,另一个人每次走两步,他们肯定会再相遇。

                                            -

                                            1 的时候,两人都会停留在 1

                                            -

                                            Complexity:

                                            -
                                              -
                                            • Time complexity :
                                            • -
                                            • Space complexity :
                                            • -
                                            github
                                            \ No newline at end of file diff --git a/docs/problem/house-robber.html b/docs/problem/house-robber.html deleted file mode 100644 index 3342326..0000000 --- a/docs/problem/house-robber.html +++ /dev/null @@ -1,87 +0,0 @@ -House Robber - LeetCode javascript solutions

                                            198. House Robber

                                            Difficulty:
                                            Related Topics:

                                            Problem

                                            -

                                            You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

                                            -

                                            Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

                                            -

                                            Example 1:

                                            -
                                            Input: [1,2,3,1]
                                            -Output: 4
                                            -Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
                                            -             Total amount you can rob = 1 + 3 = 4.
                                            -
                                            -

                                            Example 2:

                                            -
                                            Input: [2,7,9,3,1]
                                            -Output: 12
                                            -Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
                                            -             Total amount you can rob = 2 + 9 + 1 = 12.
                                            -
                                            -

                                            Solution 1

                                            -
                                            /**
                                            - * @param {number[]} nums
                                            - * @return {number}
                                            - */
                                            -var rob = function (nums) {
                                            -  return helper([], 0, nums);
                                            -};
                                            -
                                            -var helper = function (dp, i, nums) {
                                            -  if (i >= nums.length) return 0;
                                            -  if (dp[i] === undefined) {
                                            -    dp[i] = Math.max(
                                            -      helper(dp, i + 1, nums),
                                            -      nums[i] + helper(dp, i + 2, nums)
                                            -    );
                                            -  }
                                            -  return dp[i];
                                            -};
                                            -
                                            -

                                            Explain:

                                            -

                                            nope.

                                            -

                                            Complexity:

                                            -
                                              -
                                            • Time complexity : O(n).
                                            • -
                                            • Space complexity : O(n).
                                            • -
                                            -

                                            Solution 2

                                            -
                                            /**
                                            - * @param {number[]} nums
                                            - * @return {number}
                                            - */
                                            -var rob = function (nums) {
                                            -  var len = nums.length;
                                            -  var dp = Array(len);
                                            -  for (var i = len - 1; i >= 0; i--) {
                                            -    dp[i] = Math.max(
                                            -      dp[i + 1] || 0,
                                            -      nums[i] + (dp[i + 2] || 0)
                                            -    );
                                            -  }
                                            -  return dp[0] || 0;
                                            -};
                                            -
                                            -

                                            Explain:

                                            -

                                            nope.

                                            -

                                            Complexity:

                                            -
                                              -
                                            • Time complexity : O(n).
                                            • -
                                            • Space complexity : O(n).
                                            • -
                                            -

                                            Solution 3

                                            -
                                            /**
                                            - * @param {number[]} nums
                                            - * @return {number}
                                            - */
                                            -var rob = function (nums) {
                                            -  var len = nums.length;
                                            -  var dp = [0, 0];
                                            -  for (var i = len - 1; i >= 0; i--) {
                                            -    dp = [Math.max(dp[0], nums[i] + dp[1]), dp[0]];
                                            -  }
                                            -  return dp[0];
                                            -};
                                            -
                                            -

                                            Explain:

                                            -

                                            nope.

                                            -

                                            Complexity:

                                            -
                                              -
                                            • Time complexity : O(n).
                                            • -
                                            • Space complexity : O(1).
                                            • -
                                            github
                                            \ No newline at end of file diff --git a/docs/problem/image-overlap.html b/docs/problem/image-overlap.html deleted file mode 100644 index 511e23a..0000000 --- a/docs/problem/image-overlap.html +++ /dev/null @@ -1,94 +0,0 @@ -Image Overlap - LeetCode javascript solutions

                                            864. Image Overlap

                                            Difficulty:
                                            Related Topics:
                                            Similar Questions:

                                              Problem

                                              -

                                              Two images A and B are given, represented as binary, square matrices of the same size. (A binary matrix has only 0s and 1s as values.)

                                              -

                                              We translate one image however we choose (sliding it left, right, up, or down any number of units), and place it on top of the other image. After, the overlap of this translation is the number of positions that have a 1 in both images.

                                              -

                                              (Note also that a translation does not include any kind of rotation.)

                                              -

                                              What is the largest possible overlap?

                                              -

                                              Example 1:

                                              -
                                              Input: A = [[1,1,0],
                                              -            [0,1,0],
                                              -            [0,1,0]]
                                              -       B = [[0,0,0],
                                              -            [0,1,1],
                                              -            [0,0,1]]
                                              -Output: 3
                                              -Explanation: We slide A to right by 1 unit and down by 1 unit.
                                              -
                                              -

                                              Notes:

                                              -
                                                -
                                              • 1 <= A.length = A[0].length = B.length = B[0].length <= 30
                                              • -
                                              • 0 <= A[i][j], B[i][j] <= 1
                                              • -
                                              -

                                              Solution 1

                                              -
                                              /**
                                              - * @param {number[][]} A
                                              - * @param {number[][]} B
                                              - * @return {number}
                                              - */
                                              -var largestOverlap = function(A, B) {
                                              -  var len = A.length;
                                              -  var res = 0;
                                              -  var tmp = 0;
                                              -  for (var i = 1 - len; i < len; i++) {
                                              -    for (var j = 1 - len; j < len; j++) {
                                              -      tmp = 0;
                                              -      for (var k = 0; k < len; k++) {
                                              -        for (var m = 0; m < len; m++) {
                                              -          if (B[k][m] === 1 && A[k + i] && A[k + i][m + j] === 1) tmp++;
                                              -        }
                                              -      }
                                              -      res = Math.max(res, tmp);
                                              -    }
                                              -  }
                                              -  return res;
                                              -};
                                              -
                                              -

                                              Explain:

                                              -

                                              nope.

                                              -

                                              Complexity:

                                              -
                                                -
                                              • Time complexity : O(n^4).
                                              • -
                                              • Space complexity : O(1).
                                              • -
                                              -

                                              Solution 2

                                              -
                                              /**
                                              - * @param {number[][]} A
                                              - * @param {number[][]} B
                                              - * @return {number}
                                              - */
                                              -var largestOverlap = function(A, B) {
                                              -  var len = A.length;
                                              -  var arrA = [];
                                              -  var arrB = [];
                                              -  var count = {};
                                              -  var key = 0;
                                              -  var max = 0;
                                              -
                                              -  for (var i = 0; i < len; i++) {
                                              -    for (var j = 0; j < len; j++) {
                                              -      if (A[i][j] === 1) arrA.push(i * 100 + j);
                                              -      if (B[i][j] === 1) arrB.push(i * 100 + j);
                                              -    }
                                              -  }
                                              -
                                              -  for (var m = 0; m < arrA.length; m++) {
                                              -    for (var n = 0; n < arrB.length; n++) {
                                              -      key = arrA[m] - arrB[n];
                                              -      if (!count[key]) count[key] = 0;
                                              -      count[key]++;
                                              -    }
                                              -  }
                                              -
                                              -  for (key in count) {
                                              -    max = Math.max(max, count[key]);
                                              -  }
                                              -
                                              -  return max;
                                              -};
                                              -
                                              -

                                              Explain:

                                              -

                                              找出 A, B 中所有的 1。比如 A[1][1] = 1B[2][3] = 1,这两个 1 要对应上的话,A 要下移一位,再右移两位,分配一个独立的 key 代表这个移动,即 1 * 100 + 2。按照移动的类型,统计最大值。

                                              -

                                              Complexity:

                                              -
                                                -
                                              • Time complexity : O(n^2).
                                              • -
                                              • Space complexity : O(n).
                                              • -
                                              github
                                              \ No newline at end of file diff --git a/docs/problem/implement-strstr.html b/docs/problem/implement-strstr.html deleted file mode 100644 index 8b4ead8..0000000 --- a/docs/problem/implement-strstr.html +++ /dev/null @@ -1,41 +0,0 @@ -Implement strStr() - LeetCode javascript solutions

                                              28. Implement strStr()

                                              Difficulty:
                                              Related Topics:

                                              Problem

                                              -

                                              Implement strStr().

                                              -

                                              Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

                                              -

                                              Example 1:

                                              -
                                              Input: haystack = "hello", needle = "ll"
                                              -Output: 2
                                              -
                                              -

                                              Example 2:

                                              -
                                              Input: haystack = "aaaaa", needle = "bba"
                                              -Output: -1
                                              -
                                              -

                                              Clarification:

                                              -

                                              What should we return when needle is an empty string? This is a great question to ask during an interview.

                                              -

                                              For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().

                                              -

                                              Solution

                                              -
                                              /**
                                              - * @param {string} haystack
                                              - * @param {string} needle
                                              - * @return {number}
                                              - */
                                              -var strStr = function(haystack, needle) {
                                              -  var len1 = haystack.length;
                                              -  var len2 = needle.length;
                                              -  if (!len2) return 0;
                                              -  for (var i = 0; i < len1; i++) {
                                              -    for (var j = 0; j < len2; j++) {
                                              -      if (i + j === len1) return -1;
                                              -      if (haystack[i + j] !== needle[j]) break;
                                              -      if (j === len2 - 1) return i;
                                              -    }
                                              -  }
                                              -  return -1;
                                              -};
                                              -
                                              -

                                              Explain:

                                              -

                                              nope.

                                              -

                                              Complexity:

                                              -
                                                -
                                              • Time complexity : O(n*m).
                                              • -
                                              • Space complexity : O(1).
                                              • -
                                              github
                                              \ No newline at end of file diff --git a/docs/problem/implement-trie-prefix-tree.html b/docs/problem/implement-trie-prefix-tree.html deleted file mode 100644 index d97e7ce..0000000 --- a/docs/problem/implement-trie-prefix-tree.html +++ /dev/null @@ -1,96 +0,0 @@ -Implement Trie (Prefix Tree) - LeetCode javascript solutions

                                              208. Implement Trie (Prefix Tree)

                                              Difficulty:
                                              Related Topics:

                                              Problem

                                              -

                                              Implement a trie with insert, search, and startsWith methods.

                                              -

                                              Example:

                                              -
                                              Trie trie = new Trie();
                                              -
                                              -trie.insert("apple");
                                              -trie.search("apple");   // returns true
                                              -trie.search("app");     // returns false
                                              -trie.startsWith("app"); // returns true
                                              -trie.insert("app");   
                                              -trie.search("app");     // returns true
                                              -
                                              -

                                              Note:

                                              -
                                                -
                                              • You may assume that all inputs are consist of lowercase letters a-z.
                                              • -
                                              • All inputs are guaranteed to be non-empty strings.
                                              • -
                                              -

                                              Solution

                                              -
                                              var Node = function () {
                                              -  this.children = {};
                                              -  this.isWord = false;
                                              -};
                                              -
                                              -/**
                                              - * Initialize your data structure here.
                                              - */
                                              -var Trie = function() {
                                              -  this.root = new Node();
                                              -};
                                              -
                                              -/**
                                              - * Inserts a word into the trie. 
                                              - * @param {string} word
                                              - * @return {void}
                                              - */
                                              -Trie.prototype.insert = function(word) {
                                              -  var len = word.length;
                                              -  var node = this.root;
                                              -  var char = 0;
                                              -  for (var i = 0; i < len; i++) {
                                              -    char = word[i];
                                              -    if (!node[char]) node[char] = new Node();
                                              -    node = node[char];
                                              -  }
                                              -  node.isWord = true;
                                              -};
                                              -
                                              -/**
                                              - * Returns if the word is in the trie. 
                                              - * @param {string} word
                                              - * @return {boolean}
                                              - */
                                              -Trie.prototype.search = function(word) {
                                              -  var len = word.length;
                                              -  var node = this.root;
                                              -  var char = 0;
                                              -  for (var i = 0; i < len; i++) {
                                              -    char = word[i];
                                              -    if (!node[char]) return false;
                                              -    node = node[char];
                                              -  }
                                              -  return node.isWord;
                                              -};
                                              -
                                              -/**
                                              - * Returns if there is any word in the trie that starts with the given prefix. 
                                              - * @param {string} prefix
                                              - * @return {boolean}
                                              - */
                                              -Trie.prototype.startsWith = function(prefix) {
                                              -  var len = prefix.length;
                                              -  var node = this.root;
                                              -  var char = 0;
                                              -  for (var i = 0; i < len; i++) {
                                              -    char = prefix[i];
                                              -    if (!node[char]) return false;
                                              -    node = node[char];
                                              -  }
                                              -  return true;
                                              -};
                                              -
                                              -/** 
                                              - * Your Trie object will be instantiated and called as such:
                                              - * var obj = Object.create(Trie).createNew()
                                              - * obj.insert(word)
                                              - * var param_2 = obj.search(word)
                                              - * var param_3 = obj.startsWith(prefix)
                                              - */
                                              -
                                              -

                                              Explain:

                                              -

                                              nope.

                                              -

                                              Complexity:

                                              -
                                                -
                                              • Time complexity : O(h).
                                              • -
                                              • Space complexity : O(h).
                                              • -
                                              github
                                              \ No newline at end of file diff --git a/docs/problem/insert-interval.html b/docs/problem/insert-interval.html deleted file mode 100644 index 6fe33c3..0000000 --- a/docs/problem/insert-interval.html +++ /dev/null @@ -1,53 +0,0 @@ -Insert Interval - LeetCode javascript solutions

                                              57. Insert Interval

                                              Difficulty:
                                              Related Topics:
                                              Similar Questions:

                                              Problem

                                              -

                                              Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).

                                              -

                                              You may assume that the intervals were initially sorted according to their start times.

                                              -

                                              Example 1:

                                              -
                                              Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
                                              -Output: [[1,5],[6,9]]
                                              -
                                              -

                                              Example 2:

                                              -
                                              Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
                                              -Output: [[1,2],[3,10],[12,16]]
                                              -Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].
                                              -
                                              -

                                              Solution

                                              -
                                              /**
                                              - * Definition for an interval.
                                              - * function Interval(start, end) {
                                              - *     this.start = start;
                                              - *     this.end = end;
                                              - * }
                                              - */
                                              -/**
                                              - * @param {Interval[]} intervals
                                              - * @param {Interval} newInterval
                                              - * @return {Interval[]}
                                              - */
                                              -var insert = function(intervals, newInterval) {
                                              -  var len = intervals.length;
                                              -  var i = 0;
                                              -  var res = [];
                                              -  while (i < len && intervals[i].end < newInterval.start) {
                                              -    res.push(intervals[i]);
                                              -    i++;
                                              -  }
                                              -  while (i < len && intervals[i].start <= newInterval.end) {
                                              -    newInterval.start = Math.min(newInterval.start, intervals[i].start);
                                              -    newInterval.end = Math.max(newInterval.end, intervals[i].end);
                                              -    i++;
                                              -  }
                                              -  res.push(newInterval);
                                              -  while (i < len) {
                                              -    res.push(intervals[i]);
                                              -    i++;
                                              -  }
                                              -  return res;
                                              -};
                                              -
                                              -

                                              Explain:

                                              -

                                              nope.

                                              -

                                              Complexity:

                                              -
                                                -
                                              • Time complexity : O(n).
                                              • -
                                              • Space complexity : O(n).
                                              • -
                                              github
                                              \ No newline at end of file diff --git a/docs/problem/insertion-sort-list.html b/docs/problem/insertion-sort-list.html deleted file mode 100644 index 0d3d18f..0000000 --- a/docs/problem/insertion-sort-list.html +++ /dev/null @@ -1,56 +0,0 @@ -Insertion Sort List - LeetCode javascript solutions

                                              147. Insertion Sort List

                                              Difficulty:
                                              Related Topics:

                                              Problem

                                              -

                                              Sort a linked list using insertion sort.

                                              -

                                              -

                                              A graphical example of insertion sort. The partial sorted list (black) initially contains only the first element in the list. -With each iteration one element (red) is removed from the input data and inserted in-place into the sorted list

                                              -

                                              Algorithm of Insertion Sort:

                                              -
                                                -
                                              • Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list.
                                              • -
                                              • At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there.
                                              • -
                                              • It repeats until no input elements remain.
                                              • -
                                              -

                                              Example 1:

                                              -
                                              Input: 4->2->1->3
                                              -Output: 1->2->3->4
                                              -
                                              -

                                              Example 2:

                                              -
                                              Input: -1->5->3->4->0
                                              -Output: -1->0->3->4->5
                                              -
                                              -

                                              Solution

                                              -
                                              /**
                                              - * Definition for singly-linked list.
                                              - * function ListNode(val) {
                                              - *     this.val = val;
                                              - *     this.next = null;
                                              - * }
                                              - */
                                              -/**
                                              - * @param {ListNode} head
                                              - * @return {ListNode}
                                              - */
                                              -var insertionSortList = function(head) {
                                              -  var newHead = new ListNode(0);
                                              -  var now = head;
                                              -  var next = null;
                                              -  var tmp = null;
                                              -  while (now) {
                                              -    next = now.next;
                                              -    tmp = newHead;
                                              -    while (tmp.next && tmp.next.val < now.val) {
                                              -      tmp = tmp.next;
                                              -    }
                                              -    now.next = tmp.next;
                                              -    tmp.next = now;
                                              -    now = next;
                                              -  }
                                              -  return newHead.next;
                                              -};
                                              -
                                              -

                                              Explain:

                                              -

                                              nope.

                                              -

                                              Complexity:

                                              -
                                                -
                                              • Time complexity : O(n^2).
                                              • -
                                              • Space complexity : O(1).
                                              • -
                                              github
                                              \ No newline at end of file diff --git a/docs/problem/integer-to-roman.html b/docs/problem/integer-to-roman.html deleted file mode 100644 index 1ae2804..0000000 --- a/docs/problem/integer-to-roman.html +++ /dev/null @@ -1,142 +0,0 @@ -Integer to Roman - LeetCode javascript solutions

                                              12. Integer to Roman

                                              Difficulty:
                                              Related Topics:

                                              Problem

                                              -

                                              Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

                                              -
                                              Symbol       Value
                                              -I             1
                                              -V             5
                                              -X             10
                                              -L             50
                                              -C             100
                                              -D             500
                                              -M             1000
                                              -
                                              -

                                              For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.

                                              -

                                              Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

                                              -
                                                -
                                              • I can be placed before V (5) and X (10) to make 4 and 9.
                                              • -
                                              • X can be placed before L (50) and C (100) to make 40 and 90.
                                              • -
                                              • C can be placed before D (500) and M (1000) to make 400 and 900.
                                              • -
                                              -

                                              Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999.

                                              -

                                              Example 1:

                                              -
                                              Input: 3
                                              -Output: "III"
                                              -
                                              -

                                              Example 2:

                                              -
                                              Input: 4
                                              -Output: "IV"
                                              -
                                              -

                                              Example 3:

                                              -
                                              Input: 9
                                              -Output: "IX"
                                              -
                                              -

                                              Example 4:

                                              -
                                              Input: 58
                                              -Output: "LVIII"
                                              -Explanation: C = 100, L = 50, XXX = 30 and III = 3.
                                              -
                                              -

                                              Example 5:

                                              -
                                              Input: 1994
                                              -Output: "MCMXCIV"
                                              -Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
                                              -
                                              -

                                              Solution 1

                                              -
                                              /**
                                              - * @param {number} num
                                              - * @return {string}
                                              - */
                                              -var intToRoman = function(num) {
                                              -  var str = [
                                              -    ['I', 'V'],
                                              -    ['X', 'L'],
                                              -    ['C', 'D'],
                                              -    ['M']
                                              -  ];
                                              -  var res = '';
                                              -  var i = 0;
                                              -  var tmp = 0;
                                              -  while (num > 0) {
                                              -    tmp = num % 10;
                                              -    if (tmp === 9) {
                                              -      res = str[i][0] + str[i + 1][0] + res;
                                              -    } else if (tmp >= 5) {
                                              -      res = str[i][1] + str[i][0].repeat(tmp - 5) + res;
                                              -    } else if (tmp === 4) {
                                              -      res = str[i][0] + str[i][1] + res;
                                              -    } else {
                                              -      res = str[i][0].repeat(tmp) + res;
                                              -    }
                                              -    num = Math.floor(num / 10);
                                              -    i++;
                                              -  }
                                              -  return res;
                                              -};
                                              -
                                              -

                                              Explain:

                                              -

                                              nope.

                                              -

                                              Complexity:

                                              -
                                                -
                                              • Time complexity : O(log(n)).
                                              • -
                                              • Space complexity : O(1).
                                              • -
                                              -

                                              Solution 2

                                              -
                                              /**
                                              - * @param {number} num
                                              - * @return {string}
                                              - */
                                              -var intToRoman = function(num) {
                                              -  var map = [
                                              -    [1, "I"],
                                              -    [4, "IV"],
                                              -    [5, "V"],
                                              -    [9, "IX"],
                                              -    [10, "X"],
                                              -    [40, "XL"],
                                              -    [50, "L"],
                                              -    [90, "XC"],
                                              -    [100, "C"],
                                              -    [400, "CD"],
                                              -    [500, "D"],
                                              -    [900, "CM"],
                                              -    [1000, "M"]
                                              -  ];
                                              -  var res = '';
                                              -  var i = 12;
                                              -  var tmp = 0;
                                              -  while (num > 0) {
                                              -    res += map[i][1].repeat(Math.floor(num / map[i][0]));
                                              -    num %= map[i][0];
                                              -    i--;
                                              -  }
                                              -  return res;
                                              -};
                                              -
                                              -

                                              Explain:

                                              -

                                              nope.

                                              -

                                              Complexity:

                                              -
                                                -
                                              • Time complexity : O(log(n)).
                                              • -
                                              • Space complexity : O(1).
                                              • -
                                              -

                                              Solution 3

                                              -
                                              /**
                                              - * @param {number} num
                                              - * @return {string}
                                              - */
                                              -var intToRoman = function(num) {
                                              -  var M =["", "M", "MM", "MMM"];
                                              -  var C = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"];
                                              -  var X = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"];
                                              -  var I = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"];
                                              -  return M[Math.floor(num / 1000)]
                                              -        + C[Math.floor((num % 1000) / 100)]
                                              -        + X[Math.floor((num % 100) / 10)]
                                              -        + I[num % 10];
                                              -};
                                              -
                                              -

                                              Explain:

                                              -

                                              nope.

                                              -

                                              Complexity:

                                              -
                                                -
                                              • Time complexity : O(1).
                                              • -
                                              • Space complexity : O(1).
                                              • -
                                              github
                                              \ No newline at end of file diff --git a/docs/problem/interleaving-string.html b/docs/problem/interleaving-string.html deleted file mode 100644 index ffef069..0000000 --- a/docs/problem/interleaving-string.html +++ /dev/null @@ -1,49 +0,0 @@ -Interleaving String - LeetCode javascript solutions

                                              97. Interleaving String

                                              Difficulty:
                                              Similar Questions:

                                                Problem

                                                -

                                                Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.

                                                -

                                                Example 1:

                                                -
                                                Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
                                                -Output: true
                                                -
                                                -

                                                Example 2:

                                                -
                                                Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
                                                -Output: false
                                                -
                                                -

                                                Solution

                                                -
                                                /**
                                                - * @param {string} s1
                                                - * @param {string} s2
                                                - * @param {string} s3
                                                - * @return {boolean}
                                                - */
                                                -var isInterleave = function(s1, s2, s3) {
                                                -  var dp = {};
                                                -  if (s3.length !== s1.length + s2.length) return false;
                                                -  return helper(s1, s2, s3, 0, 0, 0, dp);
                                                -};
                                                -
                                                -var helper = function (s1, s2, s3, i, j, k, dp) {
                                                -  var res = false;
                                                -
                                                -  if (k >= s3.length) return true;
                                                -  if (dp['' + i + j + k] !== undefined) return dp['' + i + j + k];
                                                -
                                                -  if (s3[k] === s1[i] && s3[k] === s2[j]) {
                                                -    res = helper(s1, s2, s3, i + 1, j, k + 1, dp) || helper(s1, s2, s3, i, j + 1, k + 1, dp);
                                                -  } else if (s3[k] === s1[i]) {
                                                -    res = helper(s1, s2, s3, i + 1, j, k + 1, dp);
                                                -  } else if (s3[k] === s2[j]) {
                                                -    res = helper(s1, s2, s3, i, j + 1, k + 1, dp);
                                                -  }
                                                -
                                                -  dp['' + i + j + k] = res;
                                                -
                                                -  return res;
                                                -};
                                                -
                                                -

                                                Explain:

                                                -

                                                nope.

                                                -

                                                Complexity:

                                                -
                                                  -
                                                • Time complexity : O(n^2). ns3.length
                                                • -
                                                • Space complexity : O(n^2).
                                                • -
                                                github
                                                \ No newline at end of file diff --git a/docs/problem/intersection-of-two-linked-lists.html b/docs/problem/intersection-of-two-linked-lists.html deleted file mode 100644 index 7c7ba2a..0000000 --- a/docs/problem/intersection-of-two-linked-lists.html +++ /dev/null @@ -1,102 +0,0 @@ -Intersection of Two Linked Lists - LeetCode javascript solutions

                                                160. Intersection of Two Linked Lists

                                                Difficulty:
                                                Related Topics:

                                                Problem

                                                -

                                                Write a program to find the node at which the intersection of two singly linked lists begins.

                                                -

                                                For example, the following two linked lists:

                                                -
                                                A:          a1a2
                                                -                   ↘
                                                -                     c1c2c3
                                                -                   ↗            
                                                -B:     b1 b2 b3
                                                -
                                                -

                                                begin to intersect at node c1.

                                                -

                                                Notes:

                                                -
                                                  -
                                                • If the two linked lists have no intersection at all, return null.
                                                • -
                                                • The linked lists must retain their original structure after the function returns.
                                                • -
                                                • You may assume there are no cycles anywhere in the entire linked structure.
                                                • -
                                                • Your code should preferably run in O(n) time and use only O(1) memory.
                                                • -
                                                -

                                                Credits:Special thanks to @stellari for adding this problem and creating all test cases.

                                                -

                                                Solution 1

                                                -
                                                /**
                                                - * Definition for singly-linked list.
                                                - * function ListNode(val) {
                                                - *     this.val = val;
                                                - *     this.next = null;
                                                - * }
                                                - */
                                                -
                                                -/**
                                                - * @param {ListNode} headA
                                                - * @param {ListNode} headB
                                                - * @return {ListNode}
                                                - */
                                                -var getIntersectionNode = function(headA, headB) {
                                                -  var lenA = getLen(headA);
                                                -  var lenB = getLen(headB);
                                                -  let diff = Math.abs(lenA - lenB);
                                                -
                                                -  if (lenA > lenB) {
                                                -    while (diff--) headA = headA.next;
                                                -  } else {
                                                -    while (diff--) headB = headB.next;
                                                -  }
                                                -
                                                -  while (headA !== headB) {
                                                -    headA = headA.next;
                                                -    headB = headB.next;
                                                -  }
                                                -
                                                -  return headA;
                                                -};
                                                -
                                                -var getLen = function (head) {
                                                -  var len = 0;
                                                -  while (head) {
                                                -    len++;
                                                -    head = head.next;
                                                -  }
                                                -  return len;
                                                -};
                                                -
                                                -

                                                Explain:

                                                -

                                                nope.

                                                -

                                                Complexity:

                                                -
                                                  -
                                                • Time complexity : O(n).
                                                • -
                                                • Space complexity : O(1).
                                                • -
                                                -

                                                Solution 2

                                                -
                                                /**
                                                - * Definition for singly-linked list.
                                                - * function ListNode(val) {
                                                - *     this.val = val;
                                                - *     this.next = null;
                                                - * }
                                                - */
                                                -
                                                -/**
                                                - * @param {ListNode} headA
                                                - * @param {ListNode} headB
                                                - * @return {ListNode}
                                                - */
                                                -var getIntersectionNode = function(headA, headB) {
                                                -  if (!headA || !headB) return null;  
                                                -
                                                -  var nowA = headA;
                                                -  var nowB = headB;
                                                -
                                                -  while (nowA !== nowB) {
                                                -    nowA = nowA ? nowA.next : headB;
                                                -    nowB = nowB ? nowB.next : headA;
                                                -  }
                                                -
                                                -  return nowA;
                                                -};
                                                -
                                                -

                                                Explain:

                                                -

                                                nope.

                                                -

                                                Complexity:

                                                -
                                                  -
                                                • Time complexity : O(n).
                                                • -
                                                • Space complexity : O(1).
                                                • -
                                                github
                                                \ No newline at end of file diff --git a/docs/problem/invert-binary-tree.html b/docs/problem/invert-binary-tree.html deleted file mode 100644 index 8e32fcd..0000000 --- a/docs/problem/invert-binary-tree.html +++ /dev/null @@ -1,54 +0,0 @@ -Invert Binary Tree - LeetCode javascript solutions

                                                226. Invert Binary Tree

                                                Difficulty:
                                                Related Topics:
                                                Similar Questions:

                                                  Problem

                                                  -

                                                  Invert a binary tree.

                                                  -

                                                  Example:

                                                  -

                                                  Input:

                                                  -
                                                       4
                                                  -   /   \
                                                  -  2     7
                                                  - / \   / \
                                                  -1   3 6   9
                                                  -
                                                  -

                                                  Output:

                                                  -
                                                       4
                                                  -   /   \
                                                  -  7     2
                                                  - / \   / \
                                                  -9   6 3   1
                                                  -
                                                  -

                                                  Trivia: -This problem was inspired by this original tweet by Max Howell:

                                                  -

                                                  Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so f*** off.

                                                  -

                                                  Solution

                                                  -
                                                  /**
                                                  - * Definition for a binary tree node.
                                                  - * function TreeNode(val) {
                                                  - *     this.val = val;
                                                  - *     this.left = this.right = null;
                                                  - * }
                                                  - */
                                                  -/**
                                                  - * @param {TreeNode} root
                                                  - * @return {TreeNode}
                                                  - */
                                                  -var invertTree = function(root) {
                                                  -  if (root) {
                                                  -    swap(root);
                                                  -    invertTree(root.left);
                                                  -    invertTree(root.right);
                                                  -  }
                                                  -  return root;
                                                  -};
                                                  -
                                                  -var swap = function (node) {
                                                  -  var left = node.left;
                                                  -  node.left = node.right;
                                                  -  node.right = left;
                                                  -};
                                                  -
                                                  -

                                                  Explain:

                                                  -

                                                  nope.

                                                  -

                                                  Complexity:

                                                  -
                                                    -
                                                  • Time complexity : O(n).
                                                  • -
                                                  • Space complexity : O(n).
                                                  • -
                                                  github
                                                  \ No newline at end of file diff --git a/docs/problem/jump-game-ii.html b/docs/problem/jump-game-ii.html deleted file mode 100644 index 5cdd5f4..0000000 --- a/docs/problem/jump-game-ii.html +++ /dev/null @@ -1,44 +0,0 @@ -Jump Game II - LeetCode javascript solutions

                                                  45. Jump Game II

                                                  Difficulty:
                                                  Related Topics:
                                                  Similar Questions:

                                                  Problem

                                                  -

                                                  Given an array of non-negative integers, you are initially positioned at the first index of the array.

                                                  -

                                                  Each element in the array represents your maximum jump length at that position.

                                                  -

                                                  Your goal is to reach the last index in the minimum number of jumps.

                                                  -

                                                  Example:

                                                  -
                                                  Input: [2,3,1,1,4]
                                                  -Output: 2
                                                  -Explanation: The minimum number of jumps to reach the last index is 2.
                                                  -    Jump 1 step from index 0 to 1, then 3 steps to the last index.
                                                  -
                                                  -

                                                  Note:

                                                  -

                                                  You can assume that you can always reach the last index.

                                                  -

                                                  Solution

                                                  -
                                                  /**
                                                  - * @param {number[]} nums
                                                  - * @return {number}
                                                  - */
                                                  -var jump = function(nums) {
                                                  -  var len = nums.length;
                                                  -  var step = 0;
                                                  -  var now = 0;
                                                  -  var max = 0;
                                                  -
                                                  -  for (var i = 0; i < len - 1; i++) {
                                                  -    max = Math.max(max, i + nums[i]);
                                                  -    if (i === now) {
                                                  -      step++;
                                                  -      now = max;
                                                  -    }
                                                  -  }
                                                  -
                                                  -  return step;
                                                  -};
                                                  -
                                                  -

                                                  Explain:

                                                  -

                                                  假设 nums[0] === 8,那就是 1 ~ 8 都只需一步就能到达

                                                  -

                                                  1 ~ 8 里找出跳得最远的,假设能跳到 12,那就是 9 ~ 12 都只需要两步就能到达

                                                  -

                                                  9 ~ 12 里找出跳得最远的…

                                                  -

                                                  贪心,每次选最好的.

                                                  -

                                                  Complexity:

                                                  -
                                                    -
                                                  • Time complexity : O(n).
                                                  • -
                                                  • Space complexity : O(1).
                                                  • -
                                                  github
                                                  \ No newline at end of file diff --git a/docs/problem/jump-game.html b/docs/problem/jump-game.html deleted file mode 100644 index cfa7bb4..0000000 --- a/docs/problem/jump-game.html +++ /dev/null @@ -1,37 +0,0 @@ -Jump Game - LeetCode javascript solutions

                                                  55. Jump Game

                                                  Difficulty:
                                                  Related Topics:
                                                  Similar Questions:

                                                  Problem

                                                  -

                                                  Given an array of non-negative integers, you are initially positioned at the first index of the array.

                                                  -

                                                  Each element in the array represents your maximum jump length at that position.

                                                  -

                                                  Determine if you are able to reach the last index.

                                                  -

                                                  Example 1:

                                                  -
                                                  Input: [2,3,1,1,4]
                                                  -Output: true
                                                  -Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
                                                  -
                                                  -

                                                  Example 2:

                                                  -
                                                  Input: [3,2,1,0,4]
                                                  -Output: false
                                                  -Explanation: You will always arrive at index 3 no matter what. Its maximum
                                                  -             jump length is 0, which makes it impossible to reach the last index.
                                                  -
                                                  -

                                                  Solution

                                                  -
                                                  /**
                                                  - * @param {number[]} nums
                                                  - * @return {boolean}
                                                  - */
                                                  -var canJump = function(nums) {
                                                  -  var len = nums.length;
                                                  -  var max = 0;
                                                  -  for (var i = 0; i < len; i++) {
                                                  -    if (i > max) return false;
                                                  -    max = Math.max(max, i + nums[i]);
                                                  -  }
                                                  -  return true;
                                                  -};
                                                  -
                                                  -

                                                  Explain:

                                                  -

                                                  nope.

                                                  -

                                                  Complexity:

                                                  -
                                                    -
                                                  • Time complexity : O(n).
                                                  • -
                                                  • Space complexity : O(1).
                                                  • -
                                                  github
                                                  \ No newline at end of file diff --git a/docs/problem/kth-largest-element-in-an-array.html b/docs/problem/kth-largest-element-in-an-array.html deleted file mode 100644 index 7c7bc40..0000000 --- a/docs/problem/kth-largest-element-in-an-array.html +++ /dev/null @@ -1,49 +0,0 @@ -Kth Largest Element in an Array - LeetCode javascript solutions

                                                  215. Kth Largest Element in an Array

                                                  Difficulty:
                                                  Related Topics:

                                                  Problem

                                                  -

                                                  Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.

                                                  -

                                                  Example 1:

                                                  -
                                                  Input: [3,2,1,5,6,4] and k = 2
                                                  -Output: 5
                                                  -
                                                  -

                                                  Example 2:

                                                  -
                                                  Input: [3,2,3,1,2,4,5,5,6] and k = 4
                                                  -Output: 4
                                                  -
                                                  -

                                                  **Note: ** -You may assume k is always valid, 1 ≤ k ≤ array's length.

                                                  -

                                                  Solution

                                                  -
                                                  /**
                                                  - * @param {number[]} nums
                                                  - * @param {number} k
                                                  - * @return {number}
                                                  - */
                                                  -var findKthLargest = function(nums, k) {
                                                  -  return quickSelect(nums, 0, nums.length - 1, k);
                                                  -};
                                                  -
                                                  -var quickSelect = function (nums, left, right, k) {
                                                  -  var le = left;
                                                  -  var ri = right;
                                                  -  var mid = nums[right];
                                                  -  while (le < ri) {
                                                  -    if (nums[le++] > mid) swap(nums, --le, --ri);
                                                  -  }
                                                  -  swap(nums, le, right);
                                                  -  var len = right - le;
                                                  -  if (len === k - 1) return nums[le];
                                                  -  else if (len < k - 1) return quickSelect(nums, left, le - 1, k - len - 1);
                                                  -  else return quickSelect(nums, le + 1, right, k);
                                                  -};
                                                  -
                                                  -var swap = function (nums, i, j) {
                                                  -  var tmp = nums[i];
                                                  -  nums[i] = nums[j];
                                                  -  nums[j] = tmp;
                                                  -}
                                                  -
                                                  -

                                                  Explain:

                                                  -

                                                  nope.

                                                  -

                                                  Complexity:

                                                  -
                                                    -
                                                  • Time complexity : O(n).
                                                  • -
                                                  • Space complexity : O(1).
                                                  • -
                                                  github
                                                  \ No newline at end of file diff --git a/docs/problem/largest-number.html b/docs/problem/largest-number.html deleted file mode 100644 index c463571..0000000 --- a/docs/problem/largest-number.html +++ /dev/null @@ -1,33 +0,0 @@ -Largest Number - LeetCode javascript solutions

                                                  179. Largest Number

                                                  Difficulty:
                                                  Related Topics:
                                                  Similar Questions:

                                                    Problem

                                                    -

                                                    Given a list of non negative integers, arrange them such that they form the largest number.

                                                    -

                                                    Example 1:

                                                    -
                                                    Input: [10,2]
                                                    -Output: "210"
                                                    -
                                                    -

                                                    Example 2:

                                                    -
                                                    Input: [3,30,34,5,9]
                                                    -Output: "9534330"
                                                    -
                                                    -

                                                    Note: The result may be very large, so you need to return a string instead of an integer.

                                                    -

                                                    Solution

                                                    -
                                                    /**
                                                    - * @param {number[]} nums
                                                    - * @return {string}
                                                    - */
                                                    -var largestNumber = function(nums) {
                                                    -  var res = nums.sort(function (a, b) {
                                                    -    var str1 = '' + a + b;
                                                    -    var str2 = '' + b + a;
                                                    -    if (str1 === str2) return 0;
                                                    -    return str1 > str2 ? -1 : 1;
                                                    -  }).join('');
                                                    -  return res[0] === '0' ? '0' : res;
                                                    -};
                                                    -
                                                    -

                                                    Explain:

                                                    -

                                                    nope.

                                                    -

                                                    Complexity:

                                                    -
                                                      -
                                                    • Time complexity : O(nlog(n)).
                                                    • -
                                                    • Space complexity : O(1).
                                                    • -
                                                    github
                                                    \ No newline at end of file diff --git a/docs/problem/largest-rectangle-in-histogram.html b/docs/problem/largest-rectangle-in-histogram.html deleted file mode 100644 index 02b82c8..0000000 --- a/docs/problem/largest-rectangle-in-histogram.html +++ /dev/null @@ -1,41 +0,0 @@ -Largest Rectangle in Histogram - LeetCode javascript solutions

                                                    84. Largest Rectangle in Histogram

                                                    Difficulty:
                                                    Related Topics:
                                                    Similar Questions:

                                                    Problem

                                                    -

                                                    Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.

                                                    -

                                                    -

                                                    Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].

                                                    -

                                                    -

                                                    The largest rectangle is shown in the shaded area, which has area = 10 unit.

                                                    -

                                                    Example:

                                                    -
                                                    Input: [2,1,5,6,2,3]
                                                    -Output: 10
                                                    -
                                                    -

                                                    Solution

                                                    -
                                                    /**
                                                    - * @param {number[]} heights
                                                    - * @return {number}
                                                    - */
                                                    -var largestRectangleArea = function(heights) {
                                                    -  var len = heights.length;
                                                    -  var stack = [];
                                                    -  var max = 0;
                                                    -  var h = 0;
                                                    -  var w = 0;
                                                    -
                                                    -  for (var i = 0; i <= len; i++) {
                                                    -    while (stack.length && (i === len || heights[i] <= heights[stack[stack.length - 1]])) {
                                                    -      h = heights[stack.pop()];
                                                    -      w = stack.length === 0 ? i : i - stack[stack.length - 1] - 1;
                                                    -      max = Math.max(max, h * w);
                                                    -    }
                                                    -    stack.push(i);
                                                    -  }
                                                    -
                                                    -  return max;
                                                    -};
                                                    -
                                                    -

                                                    Explain:

                                                    -

                                                    nope.

                                                    -

                                                    Complexity:

                                                    -
                                                      -
                                                    • Time complexity : O(n).
                                                    • -
                                                    • Space complexity : O(n).
                                                    • -
                                                    github
                                                    \ No newline at end of file diff --git a/docs/problem/length-of-last-word.html b/docs/problem/length-of-last-word.html deleted file mode 100644 index a6315a7..0000000 --- a/docs/problem/length-of-last-word.html +++ /dev/null @@ -1,28 +0,0 @@ -Length of Last Word - LeetCode javascript solutions

                                                    58. Length of Last Word

                                                    Difficulty:
                                                    Related Topics:
                                                    Similar Questions:

                                                      Problem

                                                      -

                                                      Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.

                                                      -

                                                      If the last word does not exist, return 0.

                                                      -

                                                      Note: A word is defined as a character sequence consists of non-space characters only.

                                                      -

                                                      Example:

                                                      -
                                                      Input: "Hello World"
                                                      -Output: 5
                                                      -
                                                      -

                                                      Solution

                                                      -
                                                      /**
                                                      - * @param {string} s
                                                      - * @return {number}
                                                      - */
                                                      -var lengthOfLastWord = function(s) {
                                                      -  var str = s.trim();
                                                      -  var len = str.length;
                                                      -  var i = len - 1;
                                                      -  while (i >= 0 && str[i] !== ' ') i--;
                                                      -  return len - 1 - i;
                                                      -};
                                                      -
                                                      -

                                                      Explain:

                                                      -

                                                      nope.

                                                      -

                                                      Complexity:

                                                      -
                                                        -
                                                      • Time complexity : O(n).
                                                      • -
                                                      • Space complexity : O(1).
                                                      • -
                                                      github
                                                      \ No newline at end of file diff --git a/docs/problem/letter-combinations-of-a-phone-number.html b/docs/problem/letter-combinations-of-a-phone-number.html deleted file mode 100644 index 7017966..0000000 --- a/docs/problem/letter-combinations-of-a-phone-number.html +++ /dev/null @@ -1,39 +0,0 @@ -Letter Combinations of a Phone Number - LeetCode javascript solutions

                                                      17. Letter Combinations of a Phone Number

                                                      Difficulty:
                                                      Related Topics:

                                                      Problem

                                                      -

                                                      Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.

                                                      -

                                                      A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

                                                      -

                                                      -

                                                      Example:

                                                      -
                                                      Input: "23"
                                                      -Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
                                                      -
                                                      -

                                                      Note:

                                                      -

                                                      Although the above answer is in lexicographical order, your answer could be in any order you want.

                                                      -

                                                      Solution

                                                      -
                                                      /**
                                                      - * @param {string} digits
                                                      - * @return {string[]}
                                                      - */
                                                      -var letterCombinations = function(digits) {
                                                      -  if (digits.length === 0) return [];
                                                      -  var res = [''];
                                                      -  var mapping = ['', '', 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz'];
                                                      -  bfs(res, 0, digits, mapping, true);
                                                      -  return res;
                                                      -};
                                                      -
                                                      -var bfs = function (res, index, digits, mapping, lead) {
                                                      -  if (res.length === 0 || index === digits.length) return;
                                                      -  var tmp = res.pop();
                                                      -  var chars = mapping[digits[index]];
                                                      -  bfs(res, index, digits, mapping, false);
                                                      -  for (var i = 0; i < chars.length; i++) res.push(tmp + chars[i]);
                                                      -  if (lead) bfs(res, index + 1, digits, mapping, true);
                                                      -};
                                                      -
                                                      -

                                                      Explain:

                                                      -

                                                      每一层先把之前的结果一个个出栈,全部出栈后,再把新的推进去,最后由 lead 调用下一层。

                                                      -

                                                      Complexity:

                                                      -
                                                        -
                                                      • Time complexity :
                                                      • -
                                                      • Space complexity :
                                                      • -
                                                      github
                                                      \ No newline at end of file diff --git a/docs/problem/linked-list-cycle-ii.html b/docs/problem/linked-list-cycle-ii.html deleted file mode 100644 index a4e4264..0000000 --- a/docs/problem/linked-list-cycle-ii.html +++ /dev/null @@ -1,57 +0,0 @@ -Linked List Cycle II - LeetCode javascript solutions

                                                      142. Linked List Cycle II

                                                      Difficulty:

                                                      Problem

                                                      -

                                                      Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

                                                      -

                                                      Note: Do not modify the linked list. -Follow up: -Can you solve it without using extra space?

                                                      -

                                                      Solution

                                                      -
                                                      /**
                                                      - * Definition for singly-linked list.
                                                      - * function ListNode(val) {
                                                      - *     this.val = val;
                                                      - *     this.next = null;
                                                      - * }
                                                      - */
                                                      -
                                                      -/**
                                                      - * @param {ListNode} head
                                                      - * @return {ListNode}
                                                      - */
                                                      -var detectCycle = function(head) {
                                                      -  var slow = head;
                                                      -  var fast = head;
                                                      -  var entry = head;
                                                      -  while (slow && fast) {
                                                      -    slow = slow.next;
                                                      -    fast = fast.next ? fast.next.next : undefined;
                                                      -    if (slow === fast) {
                                                      -      while (entry !== slow) {
                                                      -        entry = entry.next;
                                                      -        slow = slow.next;
                                                      -      }
                                                      -      return entry;
                                                      -    }
                                                      -  }
                                                      -  return null;
                                                      -};
                                                      -
                                                      -

                                                      Explain:

                                                      -

                                                      fast 每次走两步,slow 每次走一步,如果链表有环的话,它们最终会相遇。

                                                      -

                                                      设:

                                                      -
                                                        -
                                                      • xhead 到环起点的长度
                                                      • -
                                                      • y 为环的长度
                                                      • -
                                                      • a 为环起点到 fastslow 相遇点的长度
                                                      • -
                                                      • bfastslow 相遇点到环起点的长度
                                                      • -
                                                      -

                                                      则有:

                                                      -
                                                        -
                                                      • fast 走的长度为 x + a
                                                      • -
                                                      • slow 走的长度为 x + y + a
                                                      • -
                                                      • (x + y + a) / (x + a) = 2
                                                      • -
                                                      -

                                                      推出:y = x + a; x = y - a = b;

                                                      -

                                                      Complexity:

                                                      -
                                                        -
                                                      • Time complexity : O(n).
                                                      • -
                                                      • Space complexity : O(1).
                                                      • -
                                                      github
                                                      \ No newline at end of file diff --git a/docs/problem/linked-list-cycle.html b/docs/problem/linked-list-cycle.html deleted file mode 100644 index 9493862..0000000 --- a/docs/problem/linked-list-cycle.html +++ /dev/null @@ -1,35 +0,0 @@ -Linked List Cycle - LeetCode javascript solutions

                                                      141. Linked List Cycle

                                                      Difficulty:

                                                      Problem

                                                      -

                                                      Given a linked list, determine if it has a cycle in it.

                                                      -

                                                      Follow up: -Can you solve it without using extra space?

                                                      -

                                                      Solution

                                                      -
                                                      /**
                                                      - * Definition for singly-linked list.
                                                      - * function ListNode(val) {
                                                      - *     this.val = val;
                                                      - *     this.next = null;
                                                      - * }
                                                      - */
                                                      -
                                                      -/**
                                                      - * @param {ListNode} head
                                                      - * @return {boolean}
                                                      - */
                                                      -var hasCycle = function(head) {
                                                      -  var slow = head;
                                                      -  var fast = head;
                                                      -  while (slow && fast) {
                                                      -    slow = slow.next;
                                                      -    fast = fast.next ? fast.next.next : undefined;
                                                      -    if (slow === fast) return true;
                                                      -  }
                                                      -  return false;
                                                      -};
                                                      -
                                                      -

                                                      Explain:

                                                      -

                                                      fast 每次走两步,slow 每次走一步,如果链表有环的话,它们最终会相遇。

                                                      -

                                                      Complexity:

                                                      -
                                                        -
                                                      • Time complexity : O(n).
                                                      • -
                                                      • Space complexity : O(1).
                                                      • -
                                                      github
                                                      \ No newline at end of file diff --git a/docs/problem/longest-common-prefix.html b/docs/problem/longest-common-prefix.html deleted file mode 100644 index d24065c..0000000 --- a/docs/problem/longest-common-prefix.html +++ /dev/null @@ -1,42 +0,0 @@ -Longest Common Prefix - LeetCode javascript solutions

                                                      14. Longest Common Prefix

                                                      Difficulty:
                                                      Related Topics:
                                                      Similar Questions:

                                                        Problem

                                                        -

                                                        Write a function to find the longest common prefix string amongst an array of strings.

                                                        -

                                                        If there is no common prefix, return an empty string "".

                                                        -

                                                        Example 1:

                                                        -
                                                        Input: ["flower","flow","flight"]
                                                        -Output: "fl"
                                                        -
                                                        -

                                                        Example 2:

                                                        -
                                                        Input: ["dog","racecar","car"]
                                                        -Output: ""
                                                        -Explanation: There is no common prefix among the input strings.
                                                        -
                                                        -

                                                        Note:

                                                        -

                                                        All given inputs are in lowercase letters a-z.

                                                        -

                                                        Solution

                                                        -
                                                        /**
                                                        - * @param {string[]} strs
                                                        - * @return {string}
                                                        - */
                                                        -var longestCommonPrefix = function(strs) {
                                                        -  if (strs.length === 0) return '';
                                                        -  var len1 = strs.length;
                                                        -  var len2 = strs[0].length;
                                                        -  var tmp = '';
                                                        -  var res = '';
                                                        -  outer: for (var i = 0; i < len2; i++) {
                                                        -    tmp = strs[0][i];
                                                        -    inner: for (var j = 1; j < len1; j++) {
                                                        -      if (strs[j][i] !== tmp) break outer;
                                                        -    }
                                                        -    res += tmp;
                                                        -  }
                                                        -  return res;
                                                        -};
                                                        -
                                                        -

                                                        Explain:

                                                        -

                                                        nope.

                                                        -

                                                        Complexity:

                                                        -
                                                          -
                                                        • Time complexity : O(n^2).
                                                        • -
                                                        • Space complexity : O(1).
                                                        • -
                                                        github
                                                        \ No newline at end of file diff --git a/docs/problem/longest-consecutive-sequence.html b/docs/problem/longest-consecutive-sequence.html deleted file mode 100644 index 1771cee..0000000 --- a/docs/problem/longest-consecutive-sequence.html +++ /dev/null @@ -1,40 +0,0 @@ -Longest Consecutive Sequence - LeetCode javascript solutions

                                                        128. Longest Consecutive Sequence

                                                        Difficulty:
                                                        Related Topics:

                                                        Problem

                                                        -

                                                        Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

                                                        -

                                                        Your algorithm should run in O(n) complexity.

                                                        -

                                                        Example:

                                                        -
                                                        Input: [100, 4, 200, 1, 3, 2]
                                                        -Output: 4
                                                        -Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
                                                        -
                                                        -

                                                        Solution

                                                        -
                                                        /**
                                                        - * @param {number[]} nums
                                                        - * @return {number}
                                                        - */
                                                        -var longestConsecutive = function(nums) {
                                                        -  var map = {};
                                                        -  var max = 0;
                                                        -  var start = 0;
                                                        -  var end = 0;
                                                        -  var num = 0;
                                                        -  var len = nums.length;
                                                        -  for (var i = 0; i < len; i++) {
                                                        -    num = nums[i];
                                                        -    if (map[num]) continue;
                                                        -    start = map[num - 1] ? map[num - 1].start : num;
                                                        -    end = map[num + 1] ? map[num + 1].end : num;
                                                        -    map[num] = { start: num, end: num };
                                                        -    map[start].end = end;
                                                        -    map[end].start = start;
                                                        -    max = Math.max(end - start + 1, max);
                                                        -  }
                                                        -  return max;
                                                        -};
                                                        -
                                                        -

                                                        Explain:

                                                        -

                                                        num 为某连续序列的端点,map[num] 保存了连续序列的起点和终点。

                                                        -

                                                        Complexity:

                                                        -
                                                          -
                                                        • Time complexity : O(n).
                                                        • -
                                                        • Space complexity : O(n).
                                                        • -
                                                        github
                                                        \ No newline at end of file diff --git a/docs/problem/longest-palindromic-substring.html b/docs/problem/longest-palindromic-substring.html deleted file mode 100644 index 4f4a9ac..0000000 --- a/docs/problem/longest-palindromic-substring.html +++ /dev/null @@ -1,49 +0,0 @@ -Longest Palindromic Substring - LeetCode javascript solutions

                                                        5. Longest Palindromic Substring

                                                        Difficulty:

                                                        Problem

                                                        -

                                                        Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

                                                        -

                                                        Example 1:

                                                        -
                                                        Input: "babad"
                                                        -Output: "bab"
                                                        -Note: "aba" is also a valid answer.
                                                        -
                                                        -

                                                        Example 2:

                                                        -
                                                        Input: "cbbd"
                                                        -Output: "bb"
                                                        -
                                                        -

                                                        Solution

                                                        -
                                                        /**
                                                        - * @param {string} s
                                                        - * @return {string}
                                                        - */
                                                        -var longestPalindrome = function(s) {
                                                        -  var start = 0;
                                                        -  var end = 0;
                                                        -  var len = s.length;
                                                        -  var num = 0;
                                                        -  for (var i = 0; i < len; i++) {
                                                        -    num = Math.max(expandAroundCenter(s, i, i), expandAroundCenter(s, i, i + 1));
                                                        -    if (num > end - start) {
                                                        -      start = i - Math.floor((num - 1) / 2);
                                                        -      end = i + Math.floor(num / 2);
                                                        -    }
                                                        -  }
                                                        -  return s.slice(start, end + 1);
                                                        -};
                                                        -
                                                        -var expandAroundCenter = function (s, left, right) {
                                                        -  var l = left;
                                                        -  var r = right;
                                                        -  var len = s.length;
                                                        -  while (l >= 0 && r < len && s[l] === s[r]) {
                                                        -    l--;
                                                        -    r++;
                                                        -  }
                                                        -  return r - l - 1;
                                                        -};
                                                        -
                                                        -

                                                        Explain:

                                                        -

                                                        遍历每个字符,检查以这个字符或相邻两个字符为中心是否回文,记录最长的回文字符位置。

                                                        -

                                                        Complexity:

                                                        -
                                                          -
                                                        • Time complexity : O(n^2).
                                                        • -
                                                        • Space complexity : O(1).
                                                        • -
                                                        github
                                                        \ No newline at end of file diff --git a/docs/problem/longest-substring-without-repeating-characters.html b/docs/problem/longest-substring-without-repeating-characters.html deleted file mode 100644 index ded16ce..0000000 --- a/docs/problem/longest-substring-without-repeating-characters.html +++ /dev/null @@ -1,33 +0,0 @@ -Longest Substring Without Repeating Characters - LeetCode javascript solutions

                                                        3. Longest Substring Without Repeating Characters

                                                        Difficulty:

                                                        Problem

                                                        -

                                                        Given a string, find the length of the longest substring without repeating characters.

                                                        -

                                                        Examples:

                                                        -

                                                        Given "abcabcbb", the answer is "abc", which the length is 3.

                                                        -

                                                        Given "bbbbb", the answer is "b", with the length of 1.

                                                        -

                                                        Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

                                                        -

                                                        Solution

                                                        -
                                                        /**
                                                        - * @param {string} s
                                                        - * @return {number}
                                                        - */
                                                        -var lengthOfLongestSubstring = function(s) {
                                                        -  var map = {};
                                                        -  var len = s.length;
                                                        -  var max = 0;
                                                        -  var start = 0;
                                                        -  for (var i = 0; i < len; i++) {
                                                        -    if (map[s[i]] !== undefined) {
                                                        -      start = Math.max(start, map[s[i]] + 1);
                                                        -    }
                                                        -    map[s[i]] = i;
                                                        -    max = Math.max(max, i - start + 1);
                                                        -  }
                                                        -  return max;
                                                        -};
                                                        -
                                                        -

                                                        Explain:

                                                        -

                                                        nope.

                                                        -

                                                        Complexity:

                                                        -
                                                          -
                                                        • Time complexity : O(n).
                                                        • -
                                                        • Space complexity : O(n).
                                                        • -
                                                        github
                                                        \ No newline at end of file diff --git a/docs/problem/longest-valid-parentheses.html b/docs/problem/longest-valid-parentheses.html deleted file mode 100644 index 542fafb..0000000 --- a/docs/problem/longest-valid-parentheses.html +++ /dev/null @@ -1,58 +0,0 @@ -Longest Valid Parentheses - LeetCode javascript solutions

                                                        32. Longest Valid Parentheses

                                                        Difficulty:
                                                        Similar Questions:

                                                        Problem

                                                        -

                                                        Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

                                                        -

                                                        Example 1:

                                                        -
                                                        Input: "(()"
                                                        -Output: 2
                                                        -Explanation: The longest valid parentheses substring is "()"
                                                        -
                                                        -

                                                        Example 2:

                                                        -
                                                        Input: ")()())"
                                                        -Output: 4
                                                        -Explanation: The longest valid parentheses substring is "()()"
                                                        -
                                                        -

                                                        Solution

                                                        -
                                                        /**
                                                        - * @param {string} s
                                                        - * @return {number}
                                                        - */
                                                        -var longestValidParentheses = function(s) {
                                                        -  var max = 0;
                                                        -  var len = s.length;
                                                        -  var dp = Array(len).fill(0);
                                                        -  var tmp = 0;
                                                        -  var getNum = function (index) {
                                                        -    return index >= 0 ? dp[index] : 0;
                                                        -  };
                                                        -
                                                        -  for (var i = 1; i < len; i++) {
                                                        -    if (s[i] === ')') {
                                                        -      if (s[i - 1] === '(') {
                                                        -        dp[i] = getNum(i - 2) + 2;
                                                        -      } else {
                                                        -        tmp = i - dp[i - 1] - 1;
                                                        -        if (tmp >= 0 && s[tmp] === '(') {
                                                        -          dp[i] = dp[i - 1] + getNum(tmp - 1) + 2;
                                                        -        }
                                                        -      }
                                                        -      max = Math.max(max, dp[i]);
                                                        -    }
                                                        -  }
                                                        -
                                                        -  return max;
                                                        -};
                                                        -
                                                        -

                                                        Explain:

                                                        -

                                                        动态规划

                                                        -
                                                          -
                                                        1. 建立等长的 dp 数组,填充 0,每个数值代表 s 相应位置处的连续匹配括号的长度
                                                        2. -
                                                        3. '(' 不影响结果,不处理,数值为 0
                                                        4. -
                                                        5. ')' 的上一个是 '(' 的话,配对,数值为上一数值 + 2
                                                        6. -
                                                        7. ')' 的上一个是 ')' 时,这时候要看上一个数值,上一个数值代表连续匹配的括号数量,记为 n - 如果回退 n + 1 个,正好是个 '(' 的话,配对,数值为上一数值 + (回退 n + 2 个的数值) + 2 - 否则是不匹配,不处理,数值为 0
                                                        8. -
                                                        -

                                                        Complexity:

                                                        -
                                                          -
                                                        • Time complexity : O(n).
                                                        • -
                                                        • Space complexity : O(n).
                                                        • -
                                                        github
                                                        \ No newline at end of file diff --git a/docs/problem/lru-cache.html b/docs/problem/lru-cache.html deleted file mode 100644 index 1c7fa24..0000000 --- a/docs/problem/lru-cache.html +++ /dev/null @@ -1,110 +0,0 @@ -LRU Cache - LeetCode javascript solutions

                                                        146. LRU Cache

                                                        Difficulty:
                                                        Related Topics:

                                                        Problem

                                                        -

                                                        Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.

                                                        -

                                                        get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1. -put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.

                                                        -

                                                        Follow up: -Could you do both operations in O(1) time complexity?

                                                        -

                                                        Example:

                                                        -
                                                        LRUCache cache = new LRUCache( 2 /* capacity */ );
                                                        -
                                                        -cache.put(1, 1);
                                                        -cache.put(2, 2);
                                                        -cache.get(1);       // returns 1
                                                        -cache.put(3, 3);    // evicts key 2
                                                        -cache.get(2);       // returns -1 (not found)
                                                        -cache.put(4, 4);    // evicts key 1
                                                        -cache.get(1);       // returns -1 (not found)
                                                        -cache.get(3);       // returns 3
                                                        -cache.get(4);       // returns 4
                                                        -
                                                        -

                                                        Solution

                                                        -
                                                        var List = function (key, val) {
                                                        -  this.key = key;
                                                        -  this.val = val;
                                                        -  this.next = null;
                                                        -  this.prev = null;
                                                        -};
                                                        -
                                                        -/**
                                                        - * @param {number} capacity
                                                        - */
                                                        -var LRUCache = function(capacity) {
                                                        -  this.capacity = capacity;
                                                        -  this.length = 0;
                                                        -  this.map = {};
                                                        -  this.head = null;
                                                        -  this.tail = null;
                                                        -};
                                                        -
                                                        -/** 
                                                        - * @param {number} key
                                                        - * @return {number}
                                                        - */
                                                        -LRUCache.prototype.get = function(key) {
                                                        -  var node = this.map[key];
                                                        -  if (node) {
                                                        -    this.remove(node);
                                                        -    this.insert(node.key, node.val);
                                                        -    return node.val;
                                                        -  } else {
                                                        -    return -1;
                                                        -  }
                                                        -};
                                                        -
                                                        -/** 
                                                        - * @param {number} key 
                                                        - * @param {number} value
                                                        - * @return {void}
                                                        - */
                                                        -LRUCache.prototype.put = function(key, value) {
                                                        -  if (this.map[key]) {
                                                        -    this.remove(this.map[key]);
                                                        -    this.insert(key, value);
                                                        -  } else {
                                                        -    if (this.length === this.capacity) {
                                                        -      this.remove(this.head);
                                                        -      this.insert(key, value);
                                                        -    } else {
                                                        -      this.insert(key, value);
                                                        -      this.length++;
                                                        -    }
                                                        -  }
                                                        -};
                                                        -
                                                        -/** 
                                                        - * Your LRUCache object will be instantiated and called as such:
                                                        - * var obj = Object.create(LRUCache).createNew(capacity)
                                                        - * var param_1 = obj.get(key)
                                                        - * obj.put(key,value)
                                                        - */
                                                        -
                                                        -LRUCache.prototype.remove = function (node) {
                                                        -  var prev = node.prev;
                                                        -  var next = node.next;
                                                        -  if (next) next.prev = prev;
                                                        -  if (prev) prev.next = next;
                                                        -  if (this.head === node) this.head = next;
                                                        -  if (this.tail === node) this.tail = prev;
                                                        -  delete this.map[node.key];
                                                        -};
                                                        -
                                                        -LRUCache.prototype.insert = function (key, val) {
                                                        -  var node = new List(key, val);
                                                        -  if (!this.tail) {
                                                        -    this.tail = node;
                                                        -    this.head = node;
                                                        -  } else {
                                                        -    this.tail.next = node;
                                                        -    node.prev = this.tail;
                                                        -    this.tail = node;
                                                        -  }
                                                        -  this.map[key] = node;
                                                        -};
                                                        -
                                                        -

                                                        Explain:

                                                        -

                                                        nope.

                                                        -

                                                        Complexity:

                                                        -
                                                          -
                                                        • Time complexity : O(1).
                                                        • -
                                                        • Space complexity : O(n).
                                                        • -
                                                        github
                                                        \ No newline at end of file diff --git a/docs/problem/majority-element.html b/docs/problem/majority-element.html deleted file mode 100644 index a39ddc3..0000000 --- a/docs/problem/majority-element.html +++ /dev/null @@ -1,66 +0,0 @@ -Majority Element - LeetCode javascript solutions

                                                        169. Majority Element

                                                        Difficulty:
                                                        Similar Questions:

                                                        Problem

                                                        -

                                                        Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

                                                        -

                                                        You may assume that the array is non-empty and the majority element always exist in the array.

                                                        -

                                                        Example 1:

                                                        -
                                                        Input: [3,2,3]
                                                        -Output: 3
                                                        -
                                                        -

                                                        Example 2:

                                                        -
                                                        Input: [2,2,1,1,1,2,2]
                                                        -Output: 2
                                                        -
                                                        -

                                                        Solution 1

                                                        -
                                                        /**
                                                        - * @param {number[]} nums
                                                        - * @return {number}
                                                        - */
                                                        -var majorityElement = function(nums) {
                                                        -  var map = {};
                                                        -  var max = 0;
                                                        -  var majorNum = 0;
                                                        -  var len = nums.length;
                                                        -  for (var i = 0; i < len; i++) {
                                                        -    if (!map[nums[i]]) map[nums[i]] = 0;
                                                        -    map[nums[i]]++;
                                                        -    if (map[nums[i]] > max) {
                                                        -      majorNum = nums[i];
                                                        -      max = map[nums[i]];
                                                        -    }
                                                        -  }
                                                        -  return majorNum;
                                                        -};
                                                        -
                                                        -

                                                        Explain:

                                                        -

                                                        nope.

                                                        -

                                                        Complexity:

                                                        -
                                                          -
                                                        • Time complexity : O(n).
                                                        • -
                                                        • Space complexity : O(n).
                                                        • -
                                                        -

                                                        Solution 2

                                                        -
                                                        /**
                                                        - * @param {number[]} nums
                                                        - * @return {number}
                                                        - */
                                                        -var majorityElement = function(nums) {
                                                        -  var count = 0;
                                                        -  var majorNum = 0;
                                                        -  var len = nums.length;
                                                        -  for (var i = 0; i < len; i++) {
                                                        -    if (!count) {
                                                        -      majorNum = nums[i];
                                                        -      count = 1;
                                                        -    } else {
                                                        -      count += (nums[i] === majorNum ? 1 : -1);
                                                        -    }
                                                        -  }
                                                        -  return majorNum;
                                                        -};
                                                        -
                                                        -

                                                        Explain:

                                                        -

                                                        nope.

                                                        -

                                                        Complexity:

                                                        -
                                                          -
                                                        • Time complexity : O(n).
                                                        • -
                                                        • Space complexity : O(1).
                                                        • -
                                                        github
                                                        \ No newline at end of file diff --git a/docs/problem/max-points-on-a-line.html b/docs/problem/max-points-on-a-line.html deleted file mode 100644 index dc93619..0000000 --- a/docs/problem/max-points-on-a-line.html +++ /dev/null @@ -1,74 +0,0 @@ -Max Points on a Line - LeetCode javascript solutions

                                                        149. Max Points on a Line

                                                        Difficulty:
                                                        Related Topics:
                                                        Similar Questions:

                                                        Problem

                                                        -

                                                        Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.

                                                        -

                                                        Example 1:

                                                        -
                                                        Input: [[1,1],[2,2],[3,3]]
                                                        -Output: 3
                                                        -Explanation:
                                                        -^
                                                        -|
                                                        -|        o
                                                        -|     o
                                                        -|  o  
                                                        -+------------->
                                                        -0  1  2  3  4
                                                        -
                                                        -

                                                        Example 2:

                                                        -
                                                        Input: [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
                                                        -Output: 4
                                                        -Explanation:
                                                        -^
                                                        -|
                                                        -|  o
                                                        -|     o        o
                                                        -|        o
                                                        -|  o        o
                                                        -+------------------->
                                                        -0  1  2  3  4  5  6
                                                        -
                                                        -

                                                        Solution

                                                        -
                                                        /**
                                                        - * Definition for a point.
                                                        - * function Point(x, y) {
                                                        - *     this.x = x;
                                                        - *     this.y = y;
                                                        - * }
                                                        - */
                                                        -/**
                                                        - * @param {Point[]} points
                                                        - * @return {number}
                                                        - */
                                                        -var maxPoints = function(points) {
                                                        -  var max = 0;
                                                        -  var map = {};
                                                        -  var localMax = 0;
                                                        -  var samePoint = 0;
                                                        -  var k = 0;
                                                        -  var len = points.length;
                                                        -  for (var i = 0; i < len; i++) {
                                                        -    map = {};
                                                        -    localMax = 0;
                                                        -    samePoint = 1;
                                                        -    for (var j = i + 1; j < len; j++) {
                                                        -      if (points[i].x === points[j].x && points[i].y === points[j].y) {
                                                        -        samePoint++;
                                                        -        continue;
                                                        -      }
                                                        -        if (points[i].y === points[j].y) k = Number.MAX_SAFE_INTEGER;
                                                        -        else k = (points[i].x - points[j].x) / (points[i].y - points[j].y);
                                                        -        if (!map[k]) map[k] = 0;
                                                        -        map[k]++;
                                                        -        localMax = Math.max(localMax, map[k]);
                                                        -    }
                                                        -    localMax += samePoint;
                                                        -    max = Math.max(max, localMax);
                                                        -  }
                                                        -  return max;
                                                        -};
                                                        -
                                                        -

                                                        Explain:

                                                        -

                                                        nope.

                                                        -

                                                        Complexity:

                                                        -
                                                          -
                                                        • Time complexity : O(n^2).
                                                        • -
                                                        • Space complexity : O(n).
                                                        • -
                                                        github
                                                        \ No newline at end of file diff --git a/docs/problem/maximal-rectangle.html b/docs/problem/maximal-rectangle.html deleted file mode 100644 index 30aebfb..0000000 --- a/docs/problem/maximal-rectangle.html +++ /dev/null @@ -1,62 +0,0 @@ -Maximal Rectangle - LeetCode javascript solutions

                                                        85. Maximal Rectangle

                                                        Difficulty:

                                                        Problem

                                                        -

                                                        Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.

                                                        -

                                                        Example:

                                                        -
                                                        Input:
                                                        -[
                                                        -  ["1","0","1","0","0"],
                                                        -  ["1","0","1","1","1"],
                                                        -  ["1","1","1","1","1"],
                                                        -  ["1","0","0","1","0"]
                                                        -]
                                                        -Output: 6
                                                        -
                                                        -

                                                        Solution

                                                        -
                                                        /**
                                                        - * @param {character[][]} matrix
                                                        - * @return {number}
                                                        - */
                                                        -var maximalRectangle = function(matrix) {
                                                        -  var n = matrix.length;
                                                        -  var m = (matrix[0] || []).length;
                                                        -  var max = 0;
                                                        -  var heights = Array(m);
                                                        -  var stack = [];
                                                        -  var h = 0;
                                                        -  var w = 0;
                                                        -
                                                        -  for (var i = 0; i < n; i++) {
                                                        -    stack = [];
                                                        -
                                                        -    for (var j = 0; j < m; j++) {
                                                        -      if (matrix[i][j] === '1') {
                                                        -        heights[j] = i === 0 ? 1 : heights[j] + 1;
                                                        -      } else {
                                                        -        heights[j] = 0;
                                                        -      }
                                                        -
                                                        -      while (stack.length && heights[j] <= heights[stack[stack.length - 1]]) {
                                                        -        h = heights[stack.pop()];
                                                        -        w = stack.length === 0 ? j : j - stack[stack.length - 1] - 1;
                                                        -        max = Math.max(max, h * w);
                                                        -      }
                                                        -
                                                        -      stack.push(j);
                                                        -    }
                                                        -
                                                        -    while (stack.length) {
                                                        -      h = heights[stack.pop()];
                                                        -      w = stack.length === 0 ? m : m - stack[stack.length - 1] - 1;
                                                        -      max = Math.max(max, h * w);
                                                        -    }
                                                        -  }
                                                        -
                                                        -  return max;
                                                        -};
                                                        -
                                                        -

                                                        Explain:

                                                        -

                                                        see Largest Rectangle in Histogram.

                                                        -

                                                        Complexity:

                                                        -
                                                          -
                                                        • Time complexity : O(n^2).
                                                        • -
                                                        • Space complexity : O(n).
                                                        • -
                                                        github
                                                        \ No newline at end of file diff --git a/docs/problem/maximal-square.html b/docs/problem/maximal-square.html deleted file mode 100644 index 72d1bbd..0000000 --- a/docs/problem/maximal-square.html +++ /dev/null @@ -1,54 +0,0 @@ -Maximal Square - LeetCode javascript solutions

                                                        221. Maximal Square

                                                        Difficulty:
                                                        Related Topics:

                                                        Problem

                                                        -

                                                        Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.

                                                        -

                                                        Example:

                                                        -
                                                        Input: 
                                                        -
                                                        -1 0 1 0 0
                                                        -1 0 1 1 1
                                                        -1 1 1 1 1
                                                        -1 0 0 1 0
                                                        -
                                                        -Output: 4
                                                        -
                                                        -

                                                        Solution

                                                        -
                                                        /**
                                                        - * @param {character[][]} matrix
                                                        - * @return {number}
                                                        - */
                                                        -var maximalSquare = function(matrix) {
                                                        -  var m = matrix.length;
                                                        -  var n = (matrix[0] || []).length;
                                                        -  var dp = Array(m).fill(0).map(_ => Array(n));
                                                        -  var max = 0;
                                                        -
                                                        -  for (var k = 0; k < m; k++) {
                                                        -    dp[k][0] = matrix[k][0] === '1' ? 1 : 0;
                                                        -    max = Math.max(max, dp[k][0]);
                                                        -  }
                                                        -
                                                        -  for (var p = 0; p < n; p++) {
                                                        -    dp[0][p] = matrix[0][p] === '1' ? 1 : 0;
                                                        -    max = Math.max(max, dp[0][p]);
                                                        -  }
                                                        -
                                                        -  for (var i = 1; i < m; i++) {
                                                        -    for (var j = 1; j < n; j++) {
                                                        -      if (matrix[i][j] === '1') {
                                                        -        dp[i][j] = Math.min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]) + 1;
                                                        -        max = Math.max(max, dp[i][j]);
                                                        -      } else {
                                                        -        dp[i][j] = 0;
                                                        -      }
                                                        -    }
                                                        -  }
                                                        -
                                                        -  return max * max;
                                                        -};
                                                        -
                                                        -

                                                        Explain:

                                                        -

                                                        nope.

                                                        -

                                                        Complexity:

                                                        -
                                                          -
                                                        • Time complexity : O(m*n).
                                                        • -
                                                        • Space complexity : O(m*n).
                                                        • -
                                                        github
                                                        \ No newline at end of file diff --git a/docs/problem/maximum-depth-of-binary-tree.html b/docs/problem/maximum-depth-of-binary-tree.html deleted file mode 100644 index 8b2cb7b..0000000 --- a/docs/problem/maximum-depth-of-binary-tree.html +++ /dev/null @@ -1,41 +0,0 @@ -Maximum Depth of Binary Tree - LeetCode javascript solutions

                                                        104. Maximum Depth of Binary Tree

                                                        Difficulty:
                                                        Related Topics:

                                                        Problem

                                                        -

                                                        Given a binary tree, find its maximum depth.

                                                        -

                                                        The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

                                                        -

                                                        Note: A leaf is a node with no children.

                                                        -

                                                        Example:

                                                        -

                                                        Given binary tree [3,9,20,null,null,15,7],

                                                        -
                                                            3
                                                        -   / \
                                                        -  9  20
                                                        -    /  \
                                                        -   15   7
                                                        -
                                                        -

                                                        return its depth = 3.

                                                        -

                                                        Solution

                                                        -
                                                        /**
                                                        - * Definition for a binary tree node.
                                                        - * function TreeNode(val) {
                                                        - *     this.val = val;
                                                        - *     this.left = this.right = null;
                                                        - * }
                                                        - */
                                                        -/**
                                                        - * @param {TreeNode} root
                                                        - * @return {number}
                                                        - */
                                                        -var maxDepth = function(root) {
                                                        -  return helper(root, 0);
                                                        -};
                                                        -
                                                        -var helper = function (root, level) {
                                                        -  if (!root) return level;
                                                        -  return Math.max(helper(root.left, level + 1), helper(root.right, level + 1));
                                                        -};
                                                        -
                                                        -

                                                        Explain:

                                                        -

                                                        nope.

                                                        -

                                                        Complexity:

                                                        -
                                                          -
                                                        • Time complexity : O(n).
                                                        • -
                                                        • Space complexity : O(1).
                                                        • -
                                                        github
                                                        \ No newline at end of file diff --git a/docs/problem/maximum-gap.html b/docs/problem/maximum-gap.html deleted file mode 100644 index 5292c02..0000000 --- a/docs/problem/maximum-gap.html +++ /dev/null @@ -1,62 +0,0 @@ -Maximum Gap - LeetCode javascript solutions

                                                        164. Maximum Gap

                                                        Difficulty:
                                                        Related Topics:
                                                        Similar Questions:

                                                          Problem

                                                          -

                                                          Given an unsorted array, find the maximum difference between the successive elements in its sorted form.

                                                          -

                                                          Return 0 if the array contains less than 2 elements.

                                                          -

                                                          Example 1:

                                                          -
                                                          Input: [3,6,9,1]
                                                          -Output: 3
                                                          -Explanation: The sorted form of the array is [1,3,6,9], either
                                                          -             (3,6) or (6,9) has the maximum difference 3.
                                                          -
                                                          -

                                                          Example 2:

                                                          -
                                                          Input: [10]
                                                          -Output: 0
                                                          -Explanation: The array contains less than 2 elements, therefore return 0.
                                                          -
                                                          -

                                                          Note:

                                                          -
                                                            -
                                                          • You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.
                                                          • -
                                                          • Try to solve it in linear time/space.
                                                          • -
                                                          -

                                                          Solution

                                                          -
                                                          /**
                                                          - * @param {number[]} nums
                                                          - * @return {number}
                                                          - */
                                                          -var maximumGap = function(nums) {
                                                          -  var len = nums.length;
                                                          -  if (len < 2) return 0;
                                                          -
                                                          -  var max = Math.max(...nums);
                                                          -  var min = Math.min(...nums);
                                                          -  if (max === min) return 0;
                                                          -
                                                          -  var minBuckets = Array(len - 1).fill(Number.MAX_SAFE_INTEGER);
                                                          -  var maxBuckets = Array(len - 1).fill(Number.MIN_SAFE_INTEGER);
                                                          -  var gap = Math.ceil((max - min) / (len - 1));
                                                          -  var index = 0;
                                                          -  for (var i = 0; i < len; i++) {
                                                          -    if (nums[i] === min || nums[i] === max) continue;
                                                          -    index = Math.floor((nums[i] - min) / gap);
                                                          -    minBuckets[index] = Math.min(minBuckets[index], nums[i]);
                                                          -    maxBuckets[index] = Math.max(maxBuckets[index], nums[i]);
                                                          -  }
                                                          -
                                                          -  var maxGap = Number.MIN_SAFE_INTEGER;
                                                          -  var preVal = min;
                                                          -  for (var j = 0; j < len - 1; j++) {
                                                          -    if (minBuckets[j] === Number.MAX_SAFE_INTEGER && maxBuckets[j] === Number.MIN_SAFE_INTEGER) continue;
                                                          -    maxGap = Math.max(maxGap, minBuckets[j] - preVal);
                                                          -    preVal = maxBuckets[j];
                                                          -  }
                                                          -  maxGap = Math.max(maxGap, max - preVal);
                                                          -
                                                          -  return maxGap;
                                                          -};
                                                          -
                                                          -

                                                          Explain:

                                                          -

                                                          桶排序

                                                          -

                                                          Complexity:

                                                          -
                                                            -
                                                          • Time complexity : O(n).
                                                          • -
                                                          • Space complexity : O(n).
                                                          • -
                                                          github
                                                          \ No newline at end of file diff --git a/docs/problem/maximum-product-subarray.html b/docs/problem/maximum-product-subarray.html deleted file mode 100644 index 6ce588a..0000000 --- a/docs/problem/maximum-product-subarray.html +++ /dev/null @@ -1,41 +0,0 @@ -Maximum Product Subarray - LeetCode javascript solutions

                                                          152. Maximum Product Subarray

                                                          Difficulty:

                                                          Problem

                                                          -

                                                          Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.

                                                          -

                                                          Example 1:

                                                          -
                                                          Input: [2,3,-2,4]
                                                          -Output: 6
                                                          -Explanation: [2,3] has the largest product 6.
                                                          -
                                                          -

                                                          Example 2:

                                                          -
                                                          Input: [-2,0,-1]
                                                          -Output: 0
                                                          -Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
                                                          -
                                                          -

                                                          Solution

                                                          -
                                                          /**
                                                          - * @param {number[]} nums
                                                          - * @return {number}
                                                          - */
                                                          -var maxProduct = function(nums) {
                                                          -  if (!nums.length) return 0;
                                                          -  var localMax = 0;
                                                          -  var localMin = 0;
                                                          -  var lastMax = nums[0];
                                                          -  var lastMin = nums[0];
                                                          -  var max = nums[0];
                                                          -  for (var i = 1; i < nums.length; i++) {
                                                          -    localMax = Math.max(lastMax * nums[i], lastMin * nums[i], nums[i]);
                                                          -    localMin = Math.min(lastMax * nums[i], lastMin * nums[i], nums[i]);
                                                          -    max = Math.max(max, localMax);
                                                          -    lastMax = localMax;
                                                          -    lastMin = localMin;
                                                          -  }
                                                          -  return max;
                                                          -};
                                                          -
                                                          -

                                                          Explain:

                                                          -

                                                          nope.

                                                          -

                                                          Complexity:

                                                          -
                                                            -
                                                          • Time complexity : O(n).
                                                          • -
                                                          • Space complexity : O(1).
                                                          • -
                                                          github
                                                          \ No newline at end of file diff --git a/docs/problem/maximum-subarray.html b/docs/problem/maximum-subarray.html deleted file mode 100644 index df124bc..0000000 --- a/docs/problem/maximum-subarray.html +++ /dev/null @@ -1,40 +0,0 @@ -Maximum Subarray - LeetCode javascript solutions

                                                          53. Maximum Subarray

                                                          Difficulty:

                                                          Problem

                                                          -

                                                          Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

                                                          -

                                                          Example:

                                                          -
                                                          Input: [-2,1,-3,4,-1,2,1,-5,4],
                                                          -Output: 6
                                                          -Explanation: [4,-1,2,1] has the largest sum = 6.
                                                          -
                                                          -

                                                          Follow up:

                                                          -

                                                          If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

                                                          -

                                                          Solution

                                                          -
                                                          /**
                                                          - * @param {number[]} nums
                                                          - * @return {number}
                                                          - */
                                                          -var maxSubArray = function(nums) {
                                                          -  var len = nums.length;
                                                          -  var max = Number.MIN_SAFE_INTEGER;
                                                          -  var before = 0;
                                                          -  var now = 0;
                                                          -
                                                          -  if (!len) return 0;
                                                          -
                                                          -  for (var i = 0; i < len; i++) {
                                                          -    now = Math.max(before + nums[i], nums[i]);
                                                          -    max = Math.max(now, max);
                                                          -    before = now;
                                                          -  }
                                                          -
                                                          -  return max;
                                                          -};
                                                          -
                                                          -

                                                          Explain:

                                                          -

                                                          动态规划:

                                                          -

                                                          当前值 = max(前值 + 当前值, 当前值); -最大值 = max(当前值, max)

                                                          -

                                                          Complexity:

                                                          -
                                                            -
                                                          • Time complexity : O(n).
                                                          • -
                                                          • Space complexity : O(1).
                                                          • -
                                                          github
                                                          \ No newline at end of file diff --git a/docs/problem/median-of-two-sorted-arrays.html b/docs/problem/median-of-two-sorted-arrays.html deleted file mode 100644 index 295dbc9..0000000 --- a/docs/problem/median-of-two-sorted-arrays.html +++ /dev/null @@ -1,76 +0,0 @@ -Median of Two Sorted Arrays - LeetCode javascript solutions

                                                          4. Median of Two Sorted Arrays

                                                          Difficulty:
                                                          Similar Questions:

                                                            Problem

                                                            -

                                                            There are two sorted arrays nums1 and nums2 of size m and n respectively.

                                                            -

                                                            Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

                                                            -

                                                            Example 1:

                                                            -
                                                            nums1 = [1, 3]
                                                            -nums2 = [2]
                                                            -
                                                            -The median is 2.0
                                                            -
                                                            -

                                                            Example 2:

                                                            -
                                                            nums1 = [1, 2]
                                                            -nums2 = [3, 4]
                                                            -
                                                            -The median is (2 + 3)/2 = 2.5
                                                            -
                                                            -

                                                            Solution

                                                            -
                                                            /**
                                                            - * @param {number[]} nums1
                                                            - * @param {number[]} nums2
                                                            - * @return {number}
                                                            - */
                                                            -var findMedianSortedArrays = function(nums1, nums2) {
                                                            -  var len1 = nums1.length;
                                                            -  var len2 = nums2.length;
                                                            -  var total = len1 + len2;
                                                            -
                                                            -  if (total % 2) {
                                                            -    return findKthOfTwoSortedArrays(nums1, len1, nums2, len2, parseInt(total / 2 + 1));
                                                            -  } else {
                                                            -    return (findKthOfTwoSortedArrays(nums1, len1, nums2, len2, total / 2)
                                                            -        + findKthOfTwoSortedArrays(nums1, len1, nums2, len2, total / 2 + 1)) / 2;
                                                            -  }
                                                            -};
                                                            -
                                                            -function findKthOfTwoSortedArrays (p, m, q, n, k) {
                                                            -
                                                            -    if (m > n) {
                                                            -        return findKthOfTwoSortedArrays(q, n, p, m, k);
                                                            -    }
                                                            -
                                                            -    if (m === 0) {
                                                            -        return q[k - 1];
                                                            -    }
                                                            -
                                                            -    if (k === 1) {
                                                            -        return Math.min(p[0], q[0]);
                                                            -    }
                                                            -
                                                            -    var pa = Math.min(parseInt(k / 2), m);
                                                            -    var qa = k - pa;
                                                            -
                                                            -    if (p[pa - 1] < q[qa - 1]) {
                                                            -        return findKthOfTwoSortedArrays(p.slice(pa), m - pa, q, n, k - pa);
                                                            -    } else if (q[qa - 1] < p[pa - 1]) {
                                                            -        return findKthOfTwoSortedArrays(p, m, q.slice(qa), n - qa, k - qa);
                                                            -    } else {
                                                            -        return p[pa - 1];
                                                            -    }
                                                            -}
                                                            -
                                                            -

                                                            Explain:

                                                            -
                                                              -
                                                            • 结论1:某个数组中有一半的元素不超过数组的中位数,有一半的元素不小于中位数(如果数组中元素个数是偶数,那么这里的一半并不是严格意义的1/2)。
                                                            • -
                                                            • 结论2:如果我们去掉数组比中位数小的k个数,再去掉比中位数大的k个数,得到的子数组的中位数和原来的中位数相同
                                                            • -
                                                            -

                                                            问题转化成求两个已经排序的数组的第 k 个数字的问题:

                                                            -
                                                              -
                                                            1. 在这两个数组的前一部分,各取出加起来为 k 的一部分,比较这两部分的最后一个
                                                            2. -
                                                            3. 更小的那部分可以去除,中位数不会出现在这里
                                                            4. -
                                                            5. 去除后更新数组及其长度,更新 k , 递归
                                                            6. -
                                                            -

                                                            Complexity:

                                                            -
                                                              -
                                                            • Time complexity : O(log(m+n)).
                                                            • -
                                                            • Space complexity : O(1).
                                                            • -
                                                            github
                                                            \ No newline at end of file diff --git a/docs/problem/merge-intervals.html b/docs/problem/merge-intervals.html deleted file mode 100644 index 448afde..0000000 --- a/docs/problem/merge-intervals.html +++ /dev/null @@ -1,60 +0,0 @@ -Merge Intervals - LeetCode javascript solutions

                                                            56. Merge Intervals

                                                            Difficulty:
                                                            Related Topics:

                                                            Problem

                                                            -

                                                            Given a collection of intervals, merge all overlapping intervals.

                                                            -

                                                            Example 1:

                                                            -
                                                            Input: [[1,3],[2,6],[8,10],[15,18]]
                                                            -Output: [[1,6],[8,10],[15,18]]
                                                            -Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
                                                            -
                                                            -

                                                            Example 2:

                                                            -
                                                            Input: [[1,4],[4,5]]
                                                            -Output: [[1,5]]
                                                            -Explanation: Intervals [1,4] and [4,5] are considerred overlapping.
                                                            -
                                                            -

                                                            Solution

                                                            -
                                                            /**
                                                            - * Definition for an interval.
                                                            - * function Interval(start, end) {
                                                            - *     this.start = start;
                                                            - *     this.end = end;
                                                            - * }
                                                            - */
                                                            -/**
                                                            - * @param {Interval[]} intervals
                                                            - * @return {Interval[]}
                                                            - */
                                                            -var merge = function(intervals) {
                                                            -  var len = intervals.length;
                                                            -  var res = [];
                                                            -  var a = null;
                                                            -  var b = null;
                                                            -
                                                            -  intervals.sort((c, d) => (c.start - d.start));
                                                            -
                                                            -  for (var i = 0; i < len; i++) {
                                                            -    a = res[res.length - 1];
                                                            -    b = intervals[i];
                                                            -    if (overlap(a, b)) {
                                                            -      a.start = Math.min(a.start, b.start);
                                                            -      a.end = Math.max(a.end, b.end);
                                                            -    } else {
                                                            -      res.push(new Interval(b.start, b.end));
                                                            -    }
                                                            -  }
                                                            -
                                                            -  return res;
                                                            -};
                                                            -
                                                            -var overlap = function (a, b) {
                                                            -  if (!a || !b) return false;
                                                            -  if (b.start <= a.end && a.end <= b.end) return true;
                                                            -  if (a.start <= b.end && b.end <= a.end) return true;
                                                            -  return false;
                                                            -};
                                                            -
                                                            -

                                                            Explain:

                                                            -

                                                            先排序,后操作。也可以边操作边排序。

                                                            -

                                                            Complexity:

                                                            -
                                                              -
                                                            • Time complexity : O(nlog(n)).
                                                            • -
                                                            • Space complexity : O(n).
                                                            • -
                                                            github
                                                            \ No newline at end of file diff --git a/docs/problem/merge-k-sorted-lists.html b/docs/problem/merge-k-sorted-lists.html deleted file mode 100644 index 9a6f2fb..0000000 --- a/docs/problem/merge-k-sorted-lists.html +++ /dev/null @@ -1,197 +0,0 @@ -Merge k Sorted Lists - LeetCode javascript solutions

                                                            23. Merge k Sorted Lists

                                                            Difficulty:

                                                            Problem

                                                            -

                                                            Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

                                                            -

                                                            Example:

                                                            -
                                                            Input:
                                                            -[
                                                            -  1->4->5,
                                                            -  1->3->4,
                                                            -  2->6
                                                            -]
                                                            -Output: 1->1->2->3->4->4->5->6
                                                            -
                                                            -

                                                            Solution 1

                                                            -
                                                            /**
                                                            - * Definition for singly-linked list.
                                                            - * function ListNode(val) {
                                                            - *     this.val = val;
                                                            - *     this.next = null;
                                                            - * }
                                                            - */
                                                            -/**
                                                            - * @param {ListNode[]} lists
                                                            - * @return {ListNode}
                                                            - */
                                                            -var mergeKLists = function(lists) {
                                                            -  var res = [];
                                                            -  var tmp = null;
                                                            -  for (var i = 0; i < lists.length; i++) {
                                                            -    tmp = lists[i];
                                                            -    while (tmp !== null) {
                                                            -      res.push(tmp);
                                                            -      tmp = tmp.next;
                                                            -    }
                                                            -  }
                                                            -  res.sort((a, b) => (a.val - b.val));
                                                            -  for (var j = 0; j < res.length; j++) {
                                                            -    res[j].next = res[j + 1] || null;
                                                            -  }
                                                            -  return res[0] || null;
                                                            -};
                                                            -
                                                            -

                                                            Explain:

                                                            -

                                                            全部拿出来,再排序。

                                                            -

                                                            Complexity:

                                                            -
                                                              -
                                                            • Time complexity : O(nlog(n)). n 是节点总数。
                                                            • -
                                                            • Space complexity : O(n).
                                                            • -
                                                            -

                                                            Solution 2

                                                            -
                                                            /**
                                                            - * Definition for singly-linked list.
                                                            - * function ListNode(val) {
                                                            - *     this.val = val;
                                                            - *     this.next = null;
                                                            - * }
                                                            - */
                                                            -/**
                                                            - * @param {ListNode[]} lists
                                                            - * @return {ListNode}
                                                            - */
                                                            -var mergeKLists = function(lists) {
                                                            -  var head = new ListNode(0);
                                                            -  var now = head;
                                                            -  var i = 0;
                                                            -  var index = 0;
                                                            -  var min = null;
                                                            -  var len = lists.length;
                                                            -  while (true) {
                                                            -    min = null;
                                                            -    for (i = 0; i < len; i++) {
                                                            -      if (lists[i] && (!min || lists[i].val < min.val)) {
                                                            -        min = lists[i];
                                                            -        index = i;
                                                            -      }
                                                            -    }
                                                            -    if (min) {
                                                            -      now.next = min;
                                                            -      now = now.next;
                                                            -      lists[index] = lists[index].next;
                                                            -    } else {
                                                            -      break;
                                                            -    }
                                                            -  }
                                                            -  return head.next;
                                                            -};
                                                            -
                                                            -

                                                            Explain:

                                                            -

                                                            依次找到目前最小的那个。

                                                            -

                                                            Complexity:

                                                            -
                                                              -
                                                            • Time complexity : O(n*k). n 是节点总数,k 是链表数量。
                                                            • -
                                                            • Space complexity : O(1).
                                                            • -
                                                            -

                                                            Solution 3

                                                            -
                                                            /**
                                                            - * Definition for singly-linked list.
                                                            - * function ListNode(val) {
                                                            - *     this.val = val;
                                                            - *     this.next = null;
                                                            - * }
                                                            - */
                                                            -/**
                                                            - * @param {ListNode[]} lists
                                                            - * @return {ListNode}
                                                            - */
                                                            -var mergeKLists = function(lists) {
                                                            -  var res = null;
                                                            -  for (var i = 0; i < lists.length; i++) {
                                                            -    res = merge(res, lists[i]);
                                                            -  }
                                                            -  return res;
                                                            -};
                                                            -
                                                            -var merge = function (a, b) {
                                                            -  if (!a) return b;
                                                            -  if (!b) return a;
                                                            -
                                                            -  var head = new ListNode(0);
                                                            -  var now = head;
                                                            -
                                                            -  while (a || b) {
                                                            -    if (!a || (b && b.val < a.val)) {
                                                            -      now.next = b;
                                                            -      b = b.next;
                                                            -    } else {
                                                            -      now.next = a;
                                                            -      a = a.next;
                                                            -    }
                                                            -    now = now.next;
                                                            -  }
                                                            -
                                                            -  return head.next;
                                                            -};
                                                            -
                                                            -

                                                            Explain:

                                                            -

                                                            链表依次合并。

                                                            -

                                                            Complexity:

                                                            -
                                                              -
                                                            • Time complexity : O(n*k). n 是节点总数,k 是链表数量。
                                                            • -
                                                            • Space complexity : O(1).
                                                            • -
                                                            -

                                                            Solution 4

                                                            -
                                                            /**
                                                            - * Definition for singly-linked list.
                                                            - * function ListNode(val) {
                                                            - *     this.val = val;
                                                            - *     this.next = null;
                                                            - * }
                                                            - */
                                                            -/**
                                                            - * @param {ListNode[]} lists
                                                            - * @return {ListNode}
                                                            - */
                                                            -var mergeKLists = function(lists) {
                                                            -  var len = lists.length;
                                                            -  var half = Math.ceil(len / 2);
                                                            -  var i = 0;
                                                            -  while (len > 1) {
                                                            -    while (i < half) {
                                                            -      lists[i] = merge(lists[i * 2], (i * 2 + 1) < len ? lists[i * 2 + 1] : null);
                                                            -      i++;
                                                            -    }
                                                            -    len = half;
                                                            -    half = Math.ceil(len / 2);
                                                            -    i = 0;
                                                            -  }
                                                            -  return lists[0] || null;
                                                            -};
                                                            -
                                                            -var merge = function (a, b) {
                                                            -  if (!a) return b;
                                                            -  if (!b) return a;
                                                            -  if (a === b) return a;
                                                            -
                                                            -  var head = new ListNode(0);
                                                            -  var now = head;
                                                            -
                                                            -  while (a || b) {
                                                            -    if (!a || (b && b.val < a.val)) {
                                                            -      now.next = b;
                                                            -      b = b.next;
                                                            -    } else {
                                                            -      now.next = a;
                                                            -      a = a.next;
                                                            -    }
                                                            -    now = now.next;
                                                            -  }
                                                            -
                                                            -  return head.next;
                                                            -};
                                                            -
                                                            -

                                                            Explain:

                                                            -

                                                            链表二分合并。

                                                            -

                                                            Complexity:

                                                            -
                                                              -
                                                            • Time complexity : O(nlog(k)). n 是节点总数,k 是链表数量。
                                                            • -
                                                            • Space complexity : O(1).
                                                            • -
                                                            github
                                                            \ No newline at end of file diff --git a/docs/problem/merge-sorted-array.html b/docs/problem/merge-sorted-array.html deleted file mode 100644 index 1ca800f..0000000 --- a/docs/problem/merge-sorted-array.html +++ /dev/null @@ -1,38 +0,0 @@ -Merge Sorted Array - LeetCode javascript solutions

                                                            88. Merge Sorted Array

                                                            Difficulty:
                                                            Related Topics:
                                                            Similar Questions:

                                                            Problem

                                                            -

                                                            Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

                                                            -

                                                            Note:

                                                            -
                                                              -
                                                            • The number of elements initialized in nums1 and nums2 are m and n respectively.
                                                            • -
                                                            • You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
                                                            • -
                                                            -

                                                            Example:

                                                            -
                                                            Input:
                                                            -nums1 = [1,2,3,0,0,0], m = 3
                                                            -nums2 = [2,5,6],       n = 3
                                                            -
                                                            -Output: [1,2,2,3,5,6]
                                                            -
                                                            -

                                                            Solution

                                                            -
                                                            /**
                                                            - * @param {number[]} nums1
                                                            - * @param {number} m
                                                            - * @param {number[]} nums2
                                                            - * @param {number} n
                                                            - * @return {void} Do not return anything, modify nums1 in-place instead.
                                                            - */
                                                            -var merge = function(nums1, m, nums2, n) {
                                                            -  var i = m - 1;
                                                            -  var j = n - 1;
                                                            -  var k = m + n - 1;
                                                            -  while (j >= 0) {
                                                            -    nums1[k--] = i >= 0 && nums1[i] > nums2[j] ? nums1[i--] : nums2[j--];
                                                            -  }
                                                            -};
                                                            -
                                                            -

                                                            Explain:

                                                            -

                                                            nope.

                                                            -

                                                            Complexity:

                                                            -
                                                              -
                                                            • Time complexity : O(n).
                                                            • -
                                                            • Space complexity : O(1).
                                                            • -
                                                            github
                                                            \ No newline at end of file diff --git a/docs/problem/merge-two-binary-trees.html b/docs/problem/merge-two-binary-trees.html deleted file mode 100644 index a8ca9f2..0000000 --- a/docs/problem/merge-two-binary-trees.html +++ /dev/null @@ -1,50 +0,0 @@ -Merge Two Binary Trees - LeetCode javascript solutions

                                                            617. Merge Two Binary Trees

                                                            Difficulty:
                                                            Related Topics:
                                                            Similar Questions:

                                                              Problem

                                                              -

                                                              Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.

                                                              -

                                                              You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree.

                                                              -

                                                              Example 1:

                                                              -
                                                              Input: 
                                                              -    Tree 1                     Tree 2                  
                                                              -          1                         2                             
                                                              -         / \                       / \                            
                                                              -        3   2                     1   3                        
                                                              -       /                           \   \                      
                                                              -      5                             4   7                  
                                                              -Output: 
                                                              -Merged tree:
                                                              -         3
                                                              -        / \
                                                              -       4   5
                                                              -      / \   \ 
                                                              -     5   4   7
                                                              -
                                                              -

                                                              Note: -The merging process must start from the root nodes of both trees.

                                                              -

                                                              Solution

                                                              -
                                                              /**
                                                              - * Definition for a binary tree node.
                                                              - * function TreeNode(val) {
                                                              - *     this.val = val;
                                                              - *     this.left = this.right = null;
                                                              - * }
                                                              - */
                                                              -/**
                                                              - * @param {TreeNode} t1
                                                              - * @param {TreeNode} t2
                                                              - * @return {TreeNode}
                                                              - */
                                                              -var mergeTrees = function(t1, t2) {
                                                              -  if (!t1 && !t2) return null;
                                                              -  var root = new TreeNode((t1 ? t1.val : 0) + (t2 ? t2.val : 0));
                                                              -  root.left = mergeTrees(t1 ? t1.left : null, t2 ? t2.left : null);
                                                              -  root.right = mergeTrees(t1 ? t1.right : null, t2 ? t2.right : null);
                                                              -  return root;
                                                              -
                                                              -};
                                                              -
                                                              -

                                                              Explain:

                                                              -

                                                              nope.

                                                              -

                                                              Complexity:

                                                              -
                                                                -
                                                              • Time complexity : O(n).
                                                              • -
                                                              • Space complexity : O(n).
                                                              • -
                                                              github
                                                              \ No newline at end of file diff --git a/docs/problem/merge-two-sorted-lists.html b/docs/problem/merge-two-sorted-lists.html deleted file mode 100644 index df1df1d..0000000 --- a/docs/problem/merge-two-sorted-lists.html +++ /dev/null @@ -1,44 +0,0 @@ -Merge Two Sorted Lists - LeetCode javascript solutions

                                                              21. Merge Two Sorted Lists

                                                              Difficulty:
                                                              Related Topics:

                                                              Problem

                                                              -

                                                              Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

                                                              -

                                                              Example:

                                                              -
                                                              Input: 1->2->4, 1->3->4
                                                              -Output: 1->1->2->3->4->4
                                                              -
                                                              -

                                                              Solution

                                                              -
                                                              /**
                                                              - * Definition for singly-linked list.
                                                              - * function ListNode(val) {
                                                              - *     this.val = val;
                                                              - *     this.next = null;
                                                              - * }
                                                              - */
                                                              -/**
                                                              - * @param {ListNode} l1
                                                              - * @param {ListNode} l2
                                                              - * @return {ListNode}
                                                              - */
                                                              -var mergeTwoLists = function(l1, l2) {
                                                              -  var head = new ListNode(0);
                                                              -  var now = head;
                                                              -  var p1 = l1;
                                                              -  var p2 = l2;
                                                              -  while (p1 || p2) {
                                                              -    if (p1 === null || (p2 !== null && p2.val < p1.val)) {
                                                              -      now.next = p2;
                                                              -      p2 = p2.next;
                                                              -    } else {
                                                              -      now.next = p1;
                                                              -      p1 = p1.next;
                                                              -    }
                                                              -    now = now.next;
                                                              -  }
                                                              -  return head.next;
                                                              -};
                                                              -
                                                              -

                                                              Explain:

                                                              -

                                                              nope.

                                                              -

                                                              Complexity:

                                                              -
                                                                -
                                                              • Time complexity : O(m+n).
                                                              • -
                                                              • Space complexity : O(m+n).
                                                              • -
                                                              github
                                                              \ No newline at end of file diff --git a/docs/problem/min-stack.html b/docs/problem/min-stack.html deleted file mode 100644 index 3493e95..0000000 --- a/docs/problem/min-stack.html +++ /dev/null @@ -1,202 +0,0 @@ -Min Stack - LeetCode javascript solutions

                                                              155. Min Stack

                                                              Difficulty:
                                                              Related Topics:

                                                              Problem

                                                              -

                                                              Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

                                                              -

                                                              push(x) -- Push element x onto stack.

                                                              -

                                                              pop() -- Removes the element on top of the stack.

                                                              -

                                                              top() -- Get the top element.

                                                              -

                                                              getMin() -- Retrieve the minimum element in the stack.

                                                              -

                                                              Example:

                                                              -
                                                              MinStack minStack = new MinStack();
                                                              -minStack.push(-2);
                                                              -minStack.push(0);
                                                              -minStack.push(-3);
                                                              -minStack.getMin();   --> Returns -3.
                                                              -minStack.pop();
                                                              -minStack.top();      --> Returns 0.
                                                              -minStack.getMin();   --> Returns -2.
                                                              -
                                                              -

                                                              Solution 1

                                                              -
                                                              /**
                                                              - * initialize your data structure here.
                                                              - */
                                                              -var MinStack = function() {
                                                              -  this.min = [];
                                                              -  this.stack = [];
                                                              -};
                                                              -
                                                              -/** 
                                                              - * @param {number} x
                                                              - * @return {void}
                                                              - */
                                                              -MinStack.prototype.push = function(x) {
                                                              -  if (this.min.length === 0 || x <= this.min[this.min.length - 1]) this.min.push(x);
                                                              -  this.stack.push(x);
                                                              -};
                                                              -
                                                              -/**
                                                              - * @return {void}
                                                              - */
                                                              -MinStack.prototype.pop = function() {
                                                              -  var val = this.stack.pop();
                                                              -  if (val === this.min[this.min.length - 1]) this.min.pop();
                                                              -};
                                                              -
                                                              -/**
                                                              - * @return {number}
                                                              - */
                                                              -MinStack.prototype.top = function() {
                                                              -  return this.stack.length ? this.stack[this.stack.length - 1] : 0;
                                                              -};
                                                              -
                                                              -/**
                                                              - * @return {number}
                                                              - */
                                                              -MinStack.prototype.getMin = function() {
                                                              -  return this.min.length ? this.min[this.min.length - 1] : 0;
                                                              -};
                                                              -
                                                              -/** 
                                                              - * Your MinStack object will be instantiated and called as such:
                                                              - * var obj = Object.create(MinStack).createNew()
                                                              - * obj.push(x)
                                                              - * obj.pop()
                                                              - * var param_3 = obj.top()
                                                              - * var param_4 = obj.getMin()
                                                              - */
                                                              -
                                                              -

                                                              Explain:

                                                              -

                                                              两个栈,一个存值,一个存最小值。

                                                              -

                                                              Complexity:

                                                              -
                                                                -
                                                              • Time complexity :
                                                              • -
                                                              • Space complexity :
                                                              • -
                                                              -

                                                              Solution 2

                                                              -
                                                              /**
                                                              - * initialize your data structure here.
                                                              - */
                                                              -var MinStack = function() {
                                                              -  this.min = 0;
                                                              -  this.length = 0;
                                                              -  this.stack = [];
                                                              -};
                                                              -
                                                              -/** 
                                                              - * @param {number} x
                                                              - * @return {void}
                                                              - */
                                                              -MinStack.prototype.push = function(x) {
                                                              -  if (!this.length || x <= this.min) {
                                                              -    this.stack.push(this.min);
                                                              -    this.min = x;
                                                              -  }
                                                              -  this.stack.push(x);
                                                              -  this.length++;
                                                              -};
                                                              -
                                                              -/**
                                                              - * @return {void}
                                                              - */
                                                              -MinStack.prototype.pop = function() {
                                                              -  if (!this.length) return;
                                                              -  var val = this.stack.pop();
                                                              -  if (val === this.min) {
                                                              -    this.min = this.stack.pop();
                                                              -  }
                                                              -  this.length--;
                                                              -};
                                                              -
                                                              -/**
                                                              - * @return {number}
                                                              - */
                                                              -MinStack.prototype.top = function() {
                                                              -  return this.length ? this.stack[this.stack.length - 1] : 0;
                                                              -};
                                                              -
                                                              -/**
                                                              - * @return {number}
                                                              - */
                                                              -MinStack.prototype.getMin = function() {
                                                              -  return this.min;
                                                              -};
                                                              -
                                                              -/** 
                                                              - * Your MinStack object will be instantiated and called as such:
                                                              - * var obj = Object.create(MinStack).createNew()
                                                              - * obj.push(x)
                                                              - * obj.pop()
                                                              - * var param_3 = obj.top()
                                                              - * var param_4 = obj.getMin()
                                                              - */
                                                              -
                                                              -

                                                              Explain:

                                                              -

                                                              一个栈,同时存值和最小值。

                                                              -

                                                              Complexity:

                                                              -
                                                                -
                                                              • Time complexity :
                                                              • -
                                                              • Space complexity :
                                                              • -
                                                              -

                                                              Solution 3

                                                              -
                                                              /**
                                                              - * initialize your data structure here.
                                                              - */
                                                              -var MinStack = function() {
                                                              -  this.Node = function (val) {
                                                              -    this.val = val;
                                                              -    this.min = 0;
                                                              -    this.next = null;
                                                              -  };
                                                              -  this.head = null;
                                                              -};
                                                              -
                                                              -/** 
                                                              - * @param {number} x
                                                              - * @return {void}
                                                              - */
                                                              -MinStack.prototype.push = function(x) {
                                                              -  var node = new this.Node(x);
                                                              -  if (this.head) {
                                                              -    node.next = this.head;
                                                              -    node.min = Math.min(x, this.head.min);
                                                              -  } else {
                                                              -    node.min = x;
                                                              -  }
                                                              -  this.head = node;
                                                              -};
                                                              -
                                                              -/**
                                                              - * @return {void}
                                                              - */
                                                              -MinStack.prototype.pop = function() {
                                                              -  if (this.head) this.head = this.head.next;
                                                              -};
                                                              -
                                                              -/**
                                                              - * @return {number}
                                                              - */
                                                              -MinStack.prototype.top = function() {
                                                              -  return this.head ? this.head.val : 0;
                                                              -};
                                                              -
                                                              -/**
                                                              - * @return {number}
                                                              - */
                                                              -MinStack.prototype.getMin = function() {
                                                              -  return this.head ? this.head.min : 0;
                                                              -};
                                                              -
                                                              -/** 
                                                              - * Your MinStack object will be instantiated and called as such:
                                                              - * var obj = Object.create(MinStack).createNew()
                                                              - * obj.push(x)
                                                              - * obj.pop()
                                                              - * var param_3 = obj.top()
                                                              - * var param_4 = obj.getMin()
                                                              - */
                                                              -
                                                              -

                                                              Explain:

                                                              -

                                                              用链表模拟栈,每个节点存储值 val,最小值 min,下一个节点 next

                                                              -

                                                              Complexity:

                                                              -
                                                                -
                                                              • Time complexity :
                                                              • -
                                                              • Space complexity :
                                                              • -
                                                              github
                                                              \ No newline at end of file diff --git a/docs/problem/minimum-depth-of-binary-tree.html b/docs/problem/minimum-depth-of-binary-tree.html deleted file mode 100644 index 5083680..0000000 --- a/docs/problem/minimum-depth-of-binary-tree.html +++ /dev/null @@ -1,76 +0,0 @@ -Minimum Depth of Binary Tree - LeetCode javascript solutions

                                                              111. Minimum Depth of Binary Tree

                                                              Difficulty:

                                                              Problem

                                                              -

                                                              Given a binary tree, find its minimum depth.

                                                              -

                                                              The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

                                                              -

                                                              Note: A leaf is a node with no children.

                                                              -

                                                              Example:

                                                              -

                                                              Given binary tree [3,9,20,null,null,15,7],

                                                              -
                                                                  3
                                                              -   / \
                                                              -  9  20
                                                              -    /  \
                                                              -   15   7
                                                              -
                                                              -

                                                              return its minimum depth = 2.

                                                              -

                                                              Solution 1

                                                              -
                                                              /**
                                                              - * Definition for a binary tree node.
                                                              - * function TreeNode(val) {
                                                              - *     this.val = val;
                                                              - *     this.left = this.right = null;
                                                              - * }
                                                              - */
                                                              -/**
                                                              - * @param {TreeNode} root
                                                              - * @return {number}
                                                              - */
                                                              -var minDepth = function(root) {
                                                              -  if (!root) return 0;
                                                              -  if (!root.left) return minDepth(root.right) + 1;
                                                              -  if (!root.right) return minDepth(root.left) + 1;
                                                              -  return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
                                                              -};
                                                              -
                                                              -

                                                              Explain:

                                                              -

                                                              dfs

                                                              -

                                                              Complexity:

                                                              -
                                                                -
                                                              • Time complexity : O(n).
                                                              • -
                                                              • Space complexity : O(1).
                                                              • -
                                                              -

                                                              Solution 2

                                                              -
                                                              /**
                                                              - * Definition for a binary tree node.
                                                              - * function TreeNode(val) {
                                                              - *     this.val = val;
                                                              - *     this.left = this.right = null;
                                                              - * }
                                                              - */
                                                              -/**
                                                              - * @param {TreeNode} root
                                                              - * @return {number}
                                                              - */
                                                              -var minDepth = function(root) {
                                                              -  if (!root) return 0;
                                                              -
                                                              -  var queue = [[root, 1]];
                                                              -  var item = null;
                                                              -  var node = null;
                                                              -  var level = 0;
                                                              -
                                                              -  while (queue.length) {
                                                              -    item = queue.shift();
                                                              -    node = item[0];
                                                              -    level = item[1];
                                                              -    if (!node.left && !node.right) return level;
                                                              -    if (node.left) queue.push([node.left, level + 1]);
                                                              -    if (node.right) queue.push([node.right, level + 1]);
                                                              -  }
                                                              -};
                                                              -
                                                              -

                                                              Explain:

                                                              -

                                                              bfs

                                                              -

                                                              Complexity:

                                                              -
                                                                -
                                                              • Time complexity : O(n).
                                                              • -
                                                              • Space complexity : O(n).
                                                              • -
                                                              github
                                                              \ No newline at end of file diff --git a/docs/problem/minimum-path-sum.html b/docs/problem/minimum-path-sum.html deleted file mode 100644 index d841a31..0000000 --- a/docs/problem/minimum-path-sum.html +++ /dev/null @@ -1,47 +0,0 @@ -Minimum Path Sum - LeetCode javascript solutions

                                                              64. Minimum Path Sum

                                                              Difficulty:

                                                              Problem

                                                              -

                                                              Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.

                                                              -

                                                              Note: You can only move either down or right at any point in time.

                                                              -

                                                              Example:

                                                              -
                                                              Input:
                                                              -[
                                                              -  [1,3,1],
                                                              -  [1,5,1],
                                                              -  [4,2,1]
                                                              -]
                                                              -Output: 7
                                                              -Explanation: Because the path 13111 minimizes the sum.
                                                              -
                                                              -

                                                              Solution

                                                              -
                                                              /**
                                                              - * @param {number[][]} grid
                                                              - * @return {number}
                                                              - */
                                                              -var minPathSum = function(grid) {
                                                              -  var m = grid.length;
                                                              -  var n = (grid[0] || []).length;
                                                              -  var dp = Array(m);
                                                              -  var left = 0;
                                                              -  var top = 0;
                                                              -
                                                              -  if (!m || !n) return 0;
                                                              -
                                                              -  for (var i = 0; i < m; i++) {
                                                              -    dp[i] = Array(n);
                                                              -    for (var j = 0; j < n; j++) {
                                                              -      top = i === 0 ? Number.MAX_SAFE_INTEGER : dp[i - 1][j];
                                                              -      left = j === 0 ? Number.MAX_SAFE_INTEGER : dp[i][j - 1];
                                                              -      dp[i][j] = grid[i][j] + (i === 0 && j === 0 ? 0 : Math.min(left, top));
                                                              -    }
                                                              -  }
                                                              -
                                                              -  return dp[m - 1][n - 1];
                                                              -};
                                                              -
                                                              -

                                                              Explain:

                                                              -

                                                              dp[i][j] 代表到达此位置的最小 sum

                                                              -

                                                              dp[i][j] = min(dp[i - 1][j] + dp[i][j - 1]) + grid[i][j];

                                                              -

                                                              Complexity:

                                                              -
                                                                -
                                                              • Time complexity : O(m*n).
                                                              • -
                                                              • Space complexity : O(m*n).
                                                              • -
                                                              github
                                                              \ No newline at end of file diff --git a/docs/problem/minimum-window-substring.html b/docs/problem/minimum-window-substring.html deleted file mode 100644 index 2a2dd6e..0000000 --- a/docs/problem/minimum-window-substring.html +++ /dev/null @@ -1,71 +0,0 @@ -Minimum Window Substring - LeetCode javascript solutions

                                                              76. Minimum Window Substring

                                                              Difficulty:

                                                              Problem

                                                              -

                                                              Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).

                                                              -

                                                              Example:

                                                              -
                                                              Input: S = "ADOBECODEBANC", T = "ABC"
                                                              -Output: "BANC"
                                                              -
                                                              -

                                                              Note:

                                                              -
                                                                -
                                                              • If there is no such window in S that covers all characters in T, return the empty string "".
                                                              • -
                                                              • If there is such window, you are guaranteed that there will always be only one unique minimum window in S.
                                                              • -
                                                              -

                                                              Solution

                                                              -
                                                              /**
                                                              - * @param {string} s
                                                              - * @param {string} t
                                                              - * @return {string}
                                                              - */
                                                              -var minWindow = function(s, t) {
                                                              -  var map = {};
                                                              -  var sLen = s.length;
                                                              -  var tLen = t.length;
                                                              -  var count = tLen;
                                                              -  var min = Number.MAX_SAFE_INTEGER;
                                                              -  var head = 0;
                                                              -  var left = 0;
                                                              -  var right = 0;
                                                              -
                                                              -  if (!sLen || !tLen) return '';
                                                              -
                                                              -  for (var i = 0; i < tLen; i++) {
                                                              -    if (map[t[i]] === undefined) {
                                                              -      map[t[i]] = 1
                                                              -    } else {
                                                              -      map[t[i]]++;
                                                              -    }
                                                              -  }
                                                              -
                                                              -  while (right < sLen) {
                                                              -    if (map[s[right]] !== undefined) {
                                                              -      if (map[s[right]] > 0) count--;
                                                              -      map[s[right]]--;
                                                              -    }
                                                              -
                                                              -    right++;
                                                              -
                                                              -    while (count === 0) {
                                                              -      if (right - left < min) {
                                                              -        min = right - left;
                                                              -        head = left;
                                                              -      }
                                                              -
                                                              -      if (map[s[left]] !== undefined) {
                                                              -        if (map[s[left]] === 0) count++;
                                                              -        map[s[left]]++;
                                                              -      }
                                                              -
                                                              -      left++;
                                                              -    }
                                                              -  }
                                                              -
                                                              -  return min === Number.MAX_SAFE_INTEGER ? '' : s.substr(head, min);
                                                              -};
                                                              -
                                                              -

                                                              Explain:

                                                              -

                                                              see Here is a 10-line template that can solve most 'substring' problems.

                                                              -

                                                              用哈希表保存各字符的数量,双指针表示当前窗口,用计数器来判断是否符合条件。符合条件后,记录窗口位置、最小值;更新双指针、计数器。

                                                              -

                                                              Complexity:

                                                              -
                                                                -
                                                              • Time complexity : O(n).
                                                              • -
                                                              • Space complexity : O(n).
                                                              • -
                                                              github
                                                              \ No newline at end of file diff --git a/docs/problem/move-zeroes.html b/docs/problem/move-zeroes.html deleted file mode 100644 index 8517905..0000000 --- a/docs/problem/move-zeroes.html +++ /dev/null @@ -1,44 +0,0 @@ -Move Zeroes - LeetCode javascript solutions

                                                              283. Move Zeroes

                                                              Difficulty:
                                                              Related Topics:
                                                              Similar Questions:

                                                              Problem

                                                              -

                                                              Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.

                                                              -

                                                              Example:

                                                              -
                                                              Input: [0,1,0,3,12]
                                                              -Output: [1,3,12,0,0]
                                                              -
                                                              -

                                                              Note:

                                                              -
                                                                -
                                                              • You must do this in-place without making a copy of the array.

                                                              • -
                                                              • Minimize the total number of operations.

                                                              • -
                                                              -

                                                              Solution

                                                              -
                                                              /**
                                                              - * @param {number[]} nums
                                                              - * @return {void} Do not return anything, modify nums in-place instead.
                                                              - */
                                                              -var moveZeroes = function(nums) {
                                                              -  var len = nums.length;
                                                              -  var lastZeroIndex = -1;
                                                              -  for (var i = 0; i < len; i++) {
                                                              -    if (nums[i] === 0 && lastZeroIndex === -1) {
                                                              -      lastZeroIndex = i;
                                                              -    } else if (nums[i] !== 0 && lastZeroIndex !== -1) {
                                                              -      swap(nums, i, lastZeroIndex);
                                                              -      lastZeroIndex += 1;
                                                              -    }
                                                              -  }
                                                              -};
                                                              -
                                                              -var swap = function(arr, i, j) {
                                                              -  var tmp = arr[i];
                                                              -  arr[i] = arr[j];
                                                              -  arr[j] = tmp;
                                                              -};
                                                              -
                                                              -

                                                              Explain:

                                                              -

                                                              two pointer: index in the loop and last zero index we met.

                                                              -

                                                              every time we met a non-zero element, swap it with the last zero element, move the last zero element's index.

                                                              -

                                                              every time we met a zero element, log it if we haven't met any zero yet, otherwise just move on and do nothing.

                                                              -

                                                              Complexity:

                                                              -
                                                                -
                                                              • Time complexity : O(n).
                                                              • -
                                                              • Space complexity : O(1).
                                                              • -
                                                              github
                                                              \ No newline at end of file diff --git a/docs/problem/multiply-strings.html b/docs/problem/multiply-strings.html deleted file mode 100644 index 61aff9f..0000000 --- a/docs/problem/multiply-strings.html +++ /dev/null @@ -1,54 +0,0 @@ -Multiply Strings - LeetCode javascript solutions

                                                              43. Multiply Strings

                                                              Difficulty:
                                                              Related Topics:

                                                              Problem

                                                              -

                                                              Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.

                                                              -

                                                              Example 1:

                                                              -
                                                              Input: num1 = "2", num2 = "3"
                                                              -Output: "6"
                                                              -
                                                              -

                                                              Example 2:

                                                              -
                                                              Input: num1 = "123", num2 = "456"
                                                              -Output: "56088"
                                                              -
                                                              -

                                                              Note:

                                                              -
                                                                -
                                                              • The length of both num1 and num2 is < 110.
                                                              • -
                                                              • Both num1 and num2 contain only digits 0-9.
                                                              • -
                                                              • Both num1 and num2 do not contain any leading zero, except the number 0 itself.
                                                              • -
                                                              • You must not use any built-in BigInteger library or convert the inputs to integer directly.
                                                              • -
                                                              -

                                                              Solution

                                                              -
                                                              /**
                                                              - * @param {string} num1
                                                              - * @param {string} num2
                                                              - * @return {string}
                                                              - */
                                                              -var multiply = function(num1, num2) {
                                                              -  var len1 = num1.length;
                                                              -  var len2 = num2.length;
                                                              -  var res = Array(len1 + len2).fill(0);
                                                              -  var carry = 0;
                                                              -  var val = 0;
                                                              -  var index = 0;
                                                              -
                                                              -  for (var i = len1 - 1; i >= 0; i--) {
                                                              -    carry = 0;
                                                              -    for (var j = len2 - 1; j >= 0; j--) {
                                                              -      index = len1 + len2 - 2 - i - j;
                                                              -      val= (num1[i] * num2[j]) + carry + res[index];
                                                              -      carry = Math.floor(val / 10);
                                                              -      res[index] = val % 10;
                                                              -    }
                                                              -    if (carry) res[index + 1] = carry;
                                                              -  }
                                                              -
                                                              -  while (res.length > 1 && res[res.length - 1] === 0) res.pop();
                                                              -
                                                              -  return res.reverse().join('');
                                                              -};
                                                              -
                                                              -

                                                              Explain:

                                                              -

                                                              nope.

                                                              -

                                                              Complexity:

                                                              -
                                                                -
                                                              • Time complexity : O(m*n).
                                                              • -
                                                              • Space complexity : O(log(m*n)).
                                                              • -
                                                              github
                                                              \ No newline at end of file diff --git a/docs/problem/n-queens-ii.html b/docs/problem/n-queens-ii.html deleted file mode 100644 index 3752f5a..0000000 --- a/docs/problem/n-queens-ii.html +++ /dev/null @@ -1,61 +0,0 @@ -N-Queens II - LeetCode javascript solutions

                                                              52. N-Queens II

                                                              Difficulty:
                                                              Related Topics:
                                                              Similar Questions:

                                                              Problem

                                                              -

                                                              The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

                                                              -

                                                              -

                                                              Given an integer n, return the number of distinct solutions to the n-queens puzzle.

                                                              -

                                                              Example:

                                                              -
                                                              Input: 4
                                                              -Output: 2
                                                              -Explanation: There are two distinct solutions to the 4-queens puzzle as shown below.
                                                              -[
                                                              - [".Q..",  // Solution 1
                                                              -  "...Q",
                                                              -  "Q...",
                                                              -  "..Q."],
                                                              -
                                                              - ["..Q.",  // Solution 2
                                                              -  "Q...",
                                                              -  "...Q",
                                                              -  ".Q.."]
                                                              -]
                                                              -
                                                              -

                                                              Solution

                                                              -
                                                              /**
                                                              - * @param {number} n
                                                              - * @return {number}
                                                              - */
                                                              -var totalNQueens = function(n) {
                                                              -  if (n === 1 || n >= 4) return dfs([], n, 0);
                                                              -  return 0;
                                                              -};
                                                              -
                                                              -var dfs = function (points, n, index) {
                                                              -  var res = 0;
                                                              -  if (points.length === n) return 1;
                                                              -  for (var i = index; i < n; i++) {
                                                              -    if (points.length !== i) return res;
                                                              -    for (var j = 0; j < n; j++) {
                                                              -      if (!isValid(points, [i, j])) continue;
                                                              -      points.push([i, j]);
                                                              -      res += dfs(points, n, i + 1);
                                                              -      points.pop();
                                                              -    }
                                                              -  }
                                                              -  return res;
                                                              -};
                                                              -
                                                              -var isValid = function (oldPoints, newPoint) {
                                                              -  var len = oldPoints.length;
                                                              -  for (var i = 0; i < len; i++) {
                                                              -    if (oldPoints[i][0] === newPoint[0] || oldPoints[i][1] === newPoint[1]) return false;
                                                              -    if (Math.abs((oldPoints[i][0] - newPoint[0]) / (oldPoints[i][1] - newPoint[1])) === 1) return false;
                                                              -  }
                                                              -  return true;
                                                              -};
                                                              -
                                                              -

                                                              Explain:

                                                              -

                                                              跟之前的题不同的是,退出的时候要返回 count

                                                              -

                                                              Complexity:

                                                              -
                                                                -
                                                              • Time complexity : O(n^2).
                                                              • -
                                                              • Space complexity : O(n).
                                                              • -
                                                              github
                                                              \ No newline at end of file diff --git a/docs/problem/n-queens.html b/docs/problem/n-queens.html deleted file mode 100644 index e525839..0000000 --- a/docs/problem/n-queens.html +++ /dev/null @@ -1,73 +0,0 @@ -N-Queens - LeetCode javascript solutions

                                                              51. N-Queens

                                                              Difficulty:
                                                              Related Topics:
                                                              Similar Questions:

                                                              Problem

                                                              -

                                                              The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

                                                              -

                                                              -

                                                              Given an integer n, return all distinct solutions to the n-queens puzzle.

                                                              -

                                                              Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.

                                                              -

                                                              Example:

                                                              -
                                                              Input: 4
                                                              -Output: [
                                                              - [".Q..",  // Solution 1
                                                              -  "...Q",
                                                              -  "Q...",
                                                              -  "..Q."],
                                                              -
                                                              - ["..Q.",  // Solution 2
                                                              -  "Q...",
                                                              -  "...Q",
                                                              -  ".Q.."]
                                                              -]
                                                              -Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.
                                                              -
                                                              -

                                                              Solution

                                                              -
                                                              /**
                                                              - * @param {number} n
                                                              - * @return {string[][]}
                                                              - */
                                                              -var solveNQueens = function(n) {
                                                              -  var res = [];
                                                              -  if (n === 1 || n >= 4) dfs(res, [], n, 0);
                                                              -  return res;
                                                              -};
                                                              -
                                                              -var dfs = function (res, points, n, index) {
                                                              -  for (var i = index; i < n; i++) {
                                                              -    if (points.length !== i) return;
                                                              -    for (var j = 0; j < n; j++) {
                                                              -      if (isValid(points, [i, j])) {
                                                              -        points.push([i, j]);
                                                              -        dfs(res, points, n, i + 1);
                                                              -        if (points.length === n) res.push(buildRes(points));
                                                              -        points.pop();
                                                              -      }
                                                              -    }
                                                              -  }
                                                              -};
                                                              -
                                                              -var buildRes = function (points) {
                                                              -  var res = [];
                                                              -  var n = points.length;
                                                              -  for (var i = 0; i < n; i++) {
                                                              -    res[i] = '';
                                                              -    for (var j = 0; j < n; j++) {
                                                              -      res[i] += (points[i][1] === j ? 'Q' : '.');
                                                              -    }
                                                              -  }
                                                              -  return res;
                                                              -};
                                                              -
                                                              -var isValid = function (oldPoints, newPoint) {
                                                              -  var len = oldPoints.length;
                                                              -  for (var i = 0; i < len; i++) {
                                                              -    if (oldPoints[i][0] === newPoint[0] || oldPoints[i][1] === newPoint[1]) return false;
                                                              -    if (Math.abs((oldPoints[i][0] - newPoint[0]) / (oldPoints[i][1] - newPoint[1])) === 1) return false;
                                                              -  }
                                                              -  return true;
                                                              -};
                                                              -
                                                              -

                                                              Explain:

                                                              -

                                                              dfs

                                                              -

                                                              Complexity:

                                                              -
                                                                -
                                                              • Time complexity : O(n^2).
                                                              • -
                                                              • Space complexity : O(n).
                                                              • -
                                                              github
                                                              \ No newline at end of file diff --git a/docs/problem/next-permutation.html b/docs/problem/next-permutation.html deleted file mode 100644 index ac9ecc2..0000000 --- a/docs/problem/next-permutation.html +++ /dev/null @@ -1,54 +0,0 @@ -Next Permutation - LeetCode javascript solutions

                                                              31. Next Permutation

                                                              Difficulty:
                                                              Related Topics:

                                                              Problem

                                                              -

                                                              Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

                                                              -

                                                              If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

                                                              -

                                                              The replacement must be in-place and use only constant extra memory.

                                                              -

                                                              Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.

                                                              -

                                                              1,2,31,3,2

                                                              -

                                                              3,2,11,2,3

                                                              -

                                                              1,1,51,5,1

                                                              -

                                                              Solution

                                                              -
                                                              /**
                                                              - * @param {number[]} nums
                                                              - * @return {void} Do not return anything, modify nums in-place instead.
                                                              - */
                                                              -var nextPermutation = function(nums) {
                                                              -  var len = nums.length;
                                                              -  var i = len - 2;
                                                              -  var j = len - 1;
                                                              -
                                                              -  while (i >= 0 && nums[i] >= nums[i + 1]) i--;
                                                              -
                                                              -  if (i >= 0) {
                                                              -    while (j > i && nums[j] <= nums[i]) j--;
                                                              -    swap(nums, i, j);
                                                              -    reverse(nums, i + 1, len - 1);
                                                              -  } else {
                                                              -    reverse(nums, 0, len - 1);
                                                              -  }
                                                              -};
                                                              -
                                                              -var swap = function (arr, from, to) {
                                                              -  var tmp = arr[from];
                                                              -  arr[from] = arr[to];
                                                              -  arr[to] = tmp;
                                                              -};
                                                              -
                                                              -var reverse = function (arr, start, end) {
                                                              -  while (start < end) {
                                                              -    swap(arr, start, end);
                                                              -    start++;
                                                              -    end--;
                                                              -  }
                                                              -};
                                                              -
                                                              -

                                                              Explain:

                                                              -
                                                                -
                                                              1. 从后往前找,直到 nums[i] < nums[i + 1]
                                                              2. -
                                                              3. 找到 i 后,从后往前找,直到 nums[j] > nums[i],交换 nums[i]nums[j],然后把 i 后的倒置一下
                                                              4. -
                                                              5. 没找到 i 的话,直接倒置一下
                                                              6. -
                                                              -

                                                              Complexity:

                                                              -
                                                                -
                                                              • Time complexity : O(n).
                                                              • -
                                                              • Space complexity : O(1).
                                                              • -
                                                              github
                                                              \ No newline at end of file diff --git a/docs/problem/nim-game.html b/docs/problem/nim-game.html deleted file mode 100644 index a739297..0000000 --- a/docs/problem/nim-game.html +++ /dev/null @@ -1,26 +0,0 @@ -Nim Game - LeetCode javascript solutions

                                                              292. Nim Game

                                                              Difficulty:
                                                              Related Topics:
                                                              Similar Questions:

                                                              Problem

                                                              -

                                                              You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones.

                                                              -

                                                              Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap.

                                                              -

                                                              Example:

                                                              -
                                                              Input: 4
                                                              -Output: false 
                                                              -Explanation: If there are 4 stones in the heap, then you will never win the game;
                                                              -             No matter 1, 2, or 3 stones you remove, the last stone will always be 
                                                              -             removed by your friend.
                                                              -
                                                              -

                                                              Solution

                                                              -
                                                              /**
                                                              - * @param {number} n
                                                              - * @return {boolean}
                                                              - */
                                                              -var canWinNim = function(n) {
                                                              -    return n % 4 ? true : false;
                                                              -};
                                                              -
                                                              -

                                                              Explain:

                                                              -

                                                              nope.

                                                              -

                                                              Complexity:

                                                              -
                                                                -
                                                              • Time complexity : O(1).
                                                              • -
                                                              • Space complexity : O(1).
                                                              • -
                                                              github
                                                              \ No newline at end of file diff --git a/docs/problem/nth-highest-salary.html b/docs/problem/nth-highest-salary.html deleted file mode 100644 index 4740ccb..0000000 --- a/docs/problem/nth-highest-salary.html +++ /dev/null @@ -1,33 +0,0 @@ -Nth Highest Salary - LeetCode javascript solutions

                                                              177. Nth Highest Salary

                                                              Difficulty:
                                                              Related Topics:
                                                                Similar Questions:

                                                                  Problem

                                                                  -

                                                                  Write a SQL query to get the nth highest salary from the Employee table.

                                                                  -
                                                                  +----+--------+
                                                                  -| Id | Salary |
                                                                  -+----+--------+
                                                                  -| 1  | 100    |
                                                                  -| 2  | 200    |
                                                                  -| 3  | 300    |
                                                                  -+----+--------+
                                                                  -
                                                                  -

                                                                  For example, given the above Employee table, the nth highest salary where n = 2 is 200. If there is no nth highest salary, then the query should return null.

                                                                  -
                                                                  +------------------------+
                                                                  -| getNthHighestSalary(2) |
                                                                  -+------------------------+
                                                                  -| 200                    |
                                                                  -+------------------------+
                                                                  -
                                                                  -

                                                                  Solution

                                                                  -
                                                                  CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
                                                                  -BEGIN
                                                                  -  RETURN (
                                                                  -      # Write your MySQL query statement below.
                                                                  -      SELECT DISTINCT Salary FROM Employee ORDER BY Salary DESC LIMIT N, 1
                                                                  -  );
                                                                  -END
                                                                  -
                                                                  -

                                                                  Explain:

                                                                  -

                                                                  nope.

                                                                  -

                                                                  Complexity:

                                                                  -
                                                                    -
                                                                  • Time complexity :
                                                                  • -
                                                                  • Space complexity :
                                                                  • -
                                                                  github
                                                                  \ No newline at end of file diff --git a/docs/problem/number-of-islands.html b/docs/problem/number-of-islands.html deleted file mode 100644 index 6603fa3..0000000 --- a/docs/problem/number-of-islands.html +++ /dev/null @@ -1,58 +0,0 @@ -Number of Islands - LeetCode javascript solutions

                                                                  200. Number of Islands

                                                                  Difficulty:

                                                                  Problem

                                                                  -

                                                                  Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

                                                                  -

                                                                  Example 1:

                                                                  -
                                                                  Input:
                                                                  -11110
                                                                  -11010
                                                                  -11000
                                                                  -00000
                                                                  -
                                                                  -Output: 1
                                                                  -
                                                                  -

                                                                  Example 2:

                                                                  -
                                                                  Input:
                                                                  -11000
                                                                  -11000
                                                                  -00100
                                                                  -00011
                                                                  -
                                                                  -Output: 3
                                                                  -
                                                                  -

                                                                  Solution

                                                                  -
                                                                  /**
                                                                  - * @param {character[][]} grid
                                                                  - * @return {number}
                                                                  - */
                                                                  -var numIslands = function(grid) {
                                                                  -  var m = grid.length;
                                                                  -  var n = (grid[0] || []).length;
                                                                  -  var dp = Array(m).fill(0).map(_ => Array(n));
                                                                  -  var num = 0;
                                                                  -  for (var i = 0; i < n; i++) {
                                                                  -    for (var j = 0; j < m; j++) {
                                                                  -      if (dp[j][i] !== true && grid[j][i] === '1') {
                                                                  -        num++;
                                                                  -        mark(dp, j, i, grid);
                                                                  -      }
                                                                  -    }
                                                                  -  }
                                                                  -  return num;
                                                                  -};
                                                                  -
                                                                  -var mark = function (dp, j, i, grid) {
                                                                  -  if (dp[j] && dp[j][i] !== true && grid[j][i] === '1') {
                                                                  -    dp[j][i] = true;
                                                                  -    mark(dp, j - 1, i, grid);
                                                                  -    mark(dp, j + 1, i, grid);
                                                                  -    mark(dp, j, i - 1, grid);
                                                                  -    mark(dp, j, i + 1, grid);
                                                                  -  }
                                                                  -};
                                                                  -
                                                                  -

                                                                  Explain:

                                                                  -

                                                                  nope.

                                                                  -

                                                                  Complexity:

                                                                  -
                                                                    -
                                                                  • Time complexity : O(m*n).
                                                                  • -
                                                                  • Space complexity : O(m*n).
                                                                  • -
                                                                  github
                                                                  \ No newline at end of file diff --git a/docs/problem/palindrome-linked-list.html b/docs/problem/palindrome-linked-list.html deleted file mode 100644 index 89f32de..0000000 --- a/docs/problem/palindrome-linked-list.html +++ /dev/null @@ -1,56 +0,0 @@ -Palindrome Linked List - LeetCode javascript solutions

                                                                  234. Palindrome Linked List

                                                                  Difficulty:

                                                                  Problem

                                                                  -

                                                                  Given a singly linked list, determine if it is a palindrome.

                                                                  -

                                                                  Example 1:

                                                                  -
                                                                  Input: 1->2
                                                                  -Output: false
                                                                  -
                                                                  -

                                                                  Example 2:

                                                                  -
                                                                  Input: 1->2->2->1
                                                                  -Output: true
                                                                  -
                                                                  -

                                                                  Follow up: -Could you do it in O(n) time and O(1) space?

                                                                  -

                                                                  Solution

                                                                  -
                                                                  /**
                                                                  - * Definition for singly-linked list.
                                                                  - * function ListNode(val) {
                                                                  - *     this.val = val;
                                                                  - *     this.next = null;
                                                                  - * }
                                                                  - */
                                                                  -/**
                                                                  - * @param {ListNode} head
                                                                  - * @return {boolean}
                                                                  - */
                                                                  -var isPalindrome = function(head) {
                                                                  -  var left = null;
                                                                  -  var right = null;
                                                                  -  var slow = head;
                                                                  -  var fast = head;
                                                                  -  var tmp = null;
                                                                  -
                                                                  -  while (fast && fast.next) {
                                                                  -    fast = fast.next.next;
                                                                  -    tmp = slow.next;
                                                                  -    slow.next = left;
                                                                  -    left = slow;
                                                                  -    slow = tmp;
                                                                  -  }
                                                                  -  right = fast ? slow.next : slow;
                                                                  -
                                                                  -  while (left && right) {
                                                                  -    if (left.val !== right.val) return false;
                                                                  -    left = left.next;
                                                                  -    right = right.next;
                                                                  -  }
                                                                  -
                                                                  -  return true;
                                                                  -};
                                                                  -
                                                                  -

                                                                  Explain:

                                                                  -

                                                                  nope.

                                                                  -

                                                                  Complexity:

                                                                  -
                                                                    -
                                                                  • Time complexity : O(n).
                                                                  • -
                                                                  • Space complexity : O(1).
                                                                  • -
                                                                  github
                                                                  \ No newline at end of file diff --git a/docs/problem/palindrome-number.html b/docs/problem/palindrome-number.html deleted file mode 100644 index e6c3e2b..0000000 --- a/docs/problem/palindrome-number.html +++ /dev/null @@ -1,65 +0,0 @@ -Palindrome Number - LeetCode javascript solutions

                                                                  9. Palindrome Number

                                                                  Difficulty:
                                                                  Related Topics:
                                                                  Similar Questions:

                                                                  Problem

                                                                  -

                                                                  Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

                                                                  -

                                                                  Example 1:

                                                                  -
                                                                  Input: 121
                                                                  -Output: true
                                                                  -
                                                                  -

                                                                  Example 2:

                                                                  -
                                                                  Input: -121
                                                                  -Output: false
                                                                  -Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
                                                                  -
                                                                  -

                                                                  Example 3:

                                                                  -
                                                                  Input: 10
                                                                  -Output: false
                                                                  -Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
                                                                  -
                                                                  -

                                                                  Follow up:

                                                                  -

                                                                  Coud you solve it without converting the integer to a string?

                                                                  -

                                                                  Solution 1

                                                                  -
                                                                  /**
                                                                  - * @param {number} x
                                                                  - * @return {boolean}
                                                                  - */
                                                                  -var isPalindrome = function(x) {
                                                                  -  var s = '' + x;
                                                                  -  var l = 0;
                                                                  -  var r = s.length - 1;
                                                                  -  while (l < r) {
                                                                  -    if (s[l] !== s[r]) return false;
                                                                  -    l++;
                                                                  -    r--;
                                                                  -  }
                                                                  -  return true;
                                                                  -};
                                                                  -
                                                                  -

                                                                  Explain:

                                                                  -

                                                                  转成字符串,判断是否回文

                                                                  -

                                                                  Complexity:

                                                                  -
                                                                    -
                                                                  • Time complexity : O(log(n)).
                                                                  • -
                                                                  • Space complexity : O(1).
                                                                  • -
                                                                  -

                                                                  Solution 2

                                                                  -
                                                                  /**
                                                                  - * @param {number} x
                                                                  - * @return {boolean}
                                                                  - */
                                                                  -var isPalindrome = function(x) {
                                                                  -  if (x < 0) return false;
                                                                  -  var num = x;
                                                                  -  var res = 0;
                                                                  -  while (num !== 0) {
                                                                  -    res = (res * 10) + (num % 10);
                                                                  -    num = Math.floor(num / 10);
                                                                  -  }
                                                                  -  return res === x;
                                                                  -};
                                                                  -
                                                                  -

                                                                  Explain:

                                                                  -

                                                                  直接翻转数字,比较是否相等

                                                                  -

                                                                  Complexity:

                                                                  -
                                                                    -
                                                                  • Time complexity : O(log(n)).
                                                                  • -
                                                                  • Space complexity : O(1).
                                                                  • -
                                                                  github
                                                                  \ No newline at end of file diff --git a/docs/problem/palindrome-partitioning-ii.html b/docs/problem/palindrome-partitioning-ii.html deleted file mode 100644 index 46e8598..0000000 --- a/docs/problem/palindrome-partitioning-ii.html +++ /dev/null @@ -1,41 +0,0 @@ -Palindrome Partitioning II - LeetCode javascript solutions

                                                                  132. Palindrome Partitioning II

                                                                  Difficulty:
                                                                  Related Topics:
                                                                  Similar Questions:

                                                                  Problem

                                                                  -

                                                                  Given a string s, partition s such that every substring of the partition is a palindrome.

                                                                  -

                                                                  Return the minimum cuts needed for a palindrome partitioning of s.

                                                                  -

                                                                  Example:

                                                                  -
                                                                  Input: "aab"
                                                                  -Output: 1
                                                                  -Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut.
                                                                  -
                                                                  -

                                                                  Solution

                                                                  -
                                                                  /**
                                                                  - * @param {string} s
                                                                  - * @return {number}
                                                                  - */
                                                                  -var minCut = function(s) {
                                                                  -  var len = s.length;
                                                                  -  var dp = Array(len).fill(0).map(_ => ({}));
                                                                  -  var res = Array(len + 1).fill(0).map((_, i) => (len - i - 1));
                                                                  -
                                                                  -  for (var i = len - 1; i >= 0; i--) {
                                                                  -    for (var j = i; j < len; j++) {
                                                                  -      dp[i][j] = (s[i] === s[j] && (j - i < 2 || dp[i + 1][j - 1]));
                                                                  -      if (dp[i][j]) res[i] = Math.min(res[j + 1] + 1, res[i]);
                                                                  -    }
                                                                  -  }
                                                                  -
                                                                  -  return res[0];
                                                                  -};
                                                                  -
                                                                  -

                                                                  Explain:

                                                                  -

                                                                  题意:给定字符串,给出最小切割次数,使得每一块都是回文(正反读是一样的)。

                                                                  -

                                                                  解:动态规划

                                                                  -

                                                                  dp[i][j] 代表 ij 是否回文 -从后面开始遍历,从前面开始的话,不能及时知道方案的优劣。

                                                                  -

                                                                  依次检查当前字符 s[i] 与后面字符 s[j] 是否构成回文字符串,回文就更新数值。 -· -当前字符的最小切割次数 res[i] = min(res[i],res[j + 1] + 1)

                                                                  -

                                                                  Complexity:

                                                                  -
                                                                    -
                                                                  • Time complexity : O(n^2).
                                                                  • -
                                                                  • Space complexity : O(n^2).
                                                                  • -
                                                                  github
                                                                  \ No newline at end of file diff --git a/docs/problem/palindrome-partitioning.html b/docs/problem/palindrome-partitioning.html deleted file mode 100644 index 749e16d..0000000 --- a/docs/problem/palindrome-partitioning.html +++ /dev/null @@ -1,58 +0,0 @@ -Palindrome Partitioning - LeetCode javascript solutions

                                                                  131. Palindrome Partitioning

                                                                  Difficulty:
                                                                  Related Topics:
                                                                  Similar Questions:

                                                                  Problem

                                                                  -

                                                                  Given a string s, partition s such that every substring of the partition is a palindrome.

                                                                  -

                                                                  Return all possible palindrome partitioning of s.

                                                                  -

                                                                  Example:

                                                                  -
                                                                  Input: "aab"
                                                                  -Output:
                                                                  -[
                                                                  -  ["aa","b"],
                                                                  -  ["a","a","b"]
                                                                  -]
                                                                  -
                                                                  -

                                                                  Solution

                                                                  -
                                                                  /**
                                                                  - * @param {string} s
                                                                  - * @return {string[][]}
                                                                  - */
                                                                  -var partition = function(s) {
                                                                  -  var dp = getDp(s);
                                                                  -  var res = [];
                                                                  -  var now = [];
                                                                  -  dfs(dp, res, now, s, 0);
                                                                  -  return res;
                                                                  -};
                                                                  -
                                                                  -var dfs = function (dp, res, now, s, index) {
                                                                  -  var len = s.length;
                                                                  -  if (index === len) {
                                                                  -    res.push(Array.from(now));
                                                                  -    return;
                                                                  -  }
                                                                  -  for (var i = index; i < len; i++) {
                                                                  -    if (dp[index][i]) {
                                                                  -      now.push(s.substring(index, i + 1));
                                                                  -      dfs(dp, res, now, s, i + 1);
                                                                  -      now.pop();
                                                                  -    }
                                                                  -  }
                                                                  -};
                                                                  -
                                                                  -var getDp = function (s) {
                                                                  -  var len = s.length;
                                                                  -  var dp = Array(len);
                                                                  -  for (var i = 0; i < len; i++) {
                                                                  -    for (var j = 0; j <= i; j++) {
                                                                  -      if (!dp[j]) dp[j] = Array(len);
                                                                  -      dp[j][i] = (s[i] === s[j]) && (i - j <= 2 || dp[j + 1][i - 1]);
                                                                  -    }
                                                                  -  }
                                                                  -  return dp;
                                                                  -};
                                                                  -
                                                                  -

                                                                  Explain:

                                                                  -

                                                                  dp[m][n] 代表 s.substring(m, n + 1) 是否回文。dfs 那里其实还有优化空间,比如 "aaa…","a,aa" 与 "aa,a" 后面的计算是重复的。

                                                                  -

                                                                  Complexity:

                                                                  -
                                                                    -
                                                                  • Time complexity :
                                                                  • -
                                                                  • Space complexity :
                                                                  • -
                                                                  github
                                                                  \ No newline at end of file diff --git a/docs/problem/partition-list.html b/docs/problem/partition-list.html deleted file mode 100644 index ab75588..0000000 --- a/docs/problem/partition-list.html +++ /dev/null @@ -1,51 +0,0 @@ -Partition List - LeetCode javascript solutions

                                                                  86. Partition List

                                                                  Difficulty:
                                                                  Similar Questions:

                                                                    Problem

                                                                    -

                                                                    Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

                                                                    -

                                                                    You should preserve the original relative order of the nodes in each of the two partitions.

                                                                    -

                                                                    Example:

                                                                    -
                                                                    Input: head = 1->4->3->2->5->2, x = 3
                                                                    -Output: 1->2->2->4->3->5
                                                                    -
                                                                    -

                                                                    Solution

                                                                    -
                                                                    /**
                                                                    - * Definition for singly-linked list.
                                                                    - * function ListNode(val) {
                                                                    - *     this.val = val;
                                                                    - *     this.next = null;
                                                                    - * }
                                                                    - */
                                                                    -/**
                                                                    - * @param {ListNode} head
                                                                    - * @param {number} x
                                                                    - * @return {ListNode}
                                                                    - */
                                                                    -var partition = function(head, x) {
                                                                    -  var l1 = new ListNode(0);
                                                                    -  var l2 = new ListNode(0);
                                                                    -  var now1 = l1;
                                                                    -  var now2 = l2;
                                                                    -  var now = head;
                                                                    -
                                                                    -  while (now) {
                                                                    -    if (now.val < x) {
                                                                    -      now1.next = now;
                                                                    -      now1 = now1.next;
                                                                    -    } else {
                                                                    -      now2.next = now;
                                                                    -      now2 = now2.next;
                                                                    -    }
                                                                    -    now = now.next;
                                                                    -  }
                                                                    -
                                                                    -  now1.next = l2.next;
                                                                    -  now2.next = null;
                                                                    -
                                                                    -  return l1.next;
                                                                    -};
                                                                    -
                                                                    -

                                                                    Explain:

                                                                    -

                                                                    nope.

                                                                    -

                                                                    Complexity:

                                                                    -
                                                                      -
                                                                    • Time complexity : O(n).
                                                                    • -
                                                                    • Space complexity : O(1).
                                                                    • -
                                                                    github
                                                                    \ No newline at end of file diff --git a/docs/problem/pascals-triangle-ii.html b/docs/problem/pascals-triangle-ii.html deleted file mode 100644 index fb7c546..0000000 --- a/docs/problem/pascals-triangle-ii.html +++ /dev/null @@ -1,82 +0,0 @@ -Pascal's Triangle II - LeetCode javascript solutions

                                                                    119. Pascal's Triangle II

                                                                    Difficulty:
                                                                    Related Topics:
                                                                    Similar Questions:

                                                                    Problem

                                                                    -

                                                                    Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle.

                                                                    -

                                                                    Note that the row index starts from 0.

                                                                    -

                                                                    -

                                                                    In Pascal's triangle, each number is the sum of the two numbers directly above it.

                                                                    -

                                                                    Example:

                                                                    -
                                                                    Input: 3
                                                                    -Output: [1,3,3,1]
                                                                    -
                                                                    -

                                                                    Follow up:

                                                                    -

                                                                    Could you optimize your algorithm to use only O(k) extra space?

                                                                    -

                                                                    Solution 1

                                                                    -
                                                                    /**
                                                                    - * @param {number} rowIndex
                                                                    - * @return {number[]}
                                                                    - */
                                                                    -var getRow = function(rowIndex) {
                                                                    -  var res = [];
                                                                    -  var i = 0;
                                                                    -  var j = 0;
                                                                    -  for (i = 0; i <= rowIndex; i++) {
                                                                    -    res.unshift(1);
                                                                    -    for (j = 1; j < i; j++) {
                                                                    -      res[j] += res[j + 1];
                                                                    -    }
                                                                    -  }
                                                                    -  return res;
                                                                    -};
                                                                    -
                                                                    -

                                                                    Explain:

                                                                    -

                                                                    nope.

                                                                    -

                                                                    Complexity:

                                                                    -
                                                                      -
                                                                    • Time complexity : O(n^2).
                                                                    • -
                                                                    • Space complexity : O(n).
                                                                    • -
                                                                    -

                                                                    Solution 2

                                                                    -
                                                                    /**
                                                                    - * @param {number} rowIndex
                                                                    - * @return {number[]}
                                                                    - */
                                                                    -var getRow = function(rowIndex) {
                                                                    -  var res = Array(rowIndex + 1);
                                                                    -  var i = 0;
                                                                    -  var j = 0;
                                                                    -  for (i = rowIndex; i >= 0; i--) {
                                                                    -    res[i] = 1;
                                                                    -    for (j = i + 1; j < rowIndex; j++) {
                                                                    -      res[j] += res[j + 1];
                                                                    -    }
                                                                    -  }
                                                                    -  return res;
                                                                    -};
                                                                    -
                                                                    -

                                                                    Explain:

                                                                    -

                                                                    nope.

                                                                    -

                                                                    Complexity:

                                                                    -
                                                                      -
                                                                    • Time complexity : O(n^2).
                                                                    • -
                                                                    • Space complexity : O(n).
                                                                    • -
                                                                    -

                                                                    Solution 3

                                                                    -
                                                                    /**
                                                                    - * @param {number} rowIndex
                                                                    - * @return {number[]}
                                                                    - */
                                                                    -var getRow = function(rowIndex) {
                                                                    -  var res = Array(rowIndex + 1);
                                                                    -  res[0] = 1;
                                                                    -  for (var i = 1; i <= rowIndex; i++) {
                                                                    -    res[i] = res[i - 1] * ((rowIndex - i + 1) / i);
                                                                    -  }
                                                                    -  return res;
                                                                    -};
                                                                    -
                                                                    -

                                                                    Explain:

                                                                    -

                                                                    在第 k 行,第 i 个元素,res[i] = res[i - 1] * ((k - i + 1) / i)

                                                                    -

                                                                    Complexity:

                                                                    -
                                                                      -
                                                                    • Time complexity : O(n).
                                                                    • -
                                                                    • Space complexity : O(n).
                                                                    • -
                                                                    github
                                                                    \ No newline at end of file diff --git a/docs/problem/pascals-triangle.html b/docs/problem/pascals-triangle.html deleted file mode 100644 index 31b673c..0000000 --- a/docs/problem/pascals-triangle.html +++ /dev/null @@ -1,44 +0,0 @@ -Pascal's Triangle - LeetCode javascript solutions

                                                                    118. Pascal's Triangle

                                                                    Difficulty:
                                                                    Related Topics:
                                                                    Similar Questions:

                                                                    Problem

                                                                    -

                                                                    Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.

                                                                    -

                                                                    -

                                                                    In Pascal's triangle, each number is the sum of the two numbers directly above it.

                                                                    -

                                                                    Example:

                                                                    -
                                                                    Input: 5
                                                                    -Output:
                                                                    -[
                                                                    -     [1],
                                                                    -    [1,1],
                                                                    -   [1,2,1],
                                                                    -  [1,3,3,1],
                                                                    - [1,4,6,4,1]
                                                                    -]
                                                                    -
                                                                    -

                                                                    Solution

                                                                    -
                                                                    /**
                                                                    - * @param {number} numRows
                                                                    - * @return {number[][]}
                                                                    - */
                                                                    -var generate = function(numRows) {
                                                                    -  var i = 0;
                                                                    -  var j = 0;
                                                                    -  var res = [];
                                                                    -  for (i = 0; i < numRows; i++) {
                                                                    -    res.push(Array(i + 1));
                                                                    -    for (j = 0; j <= i; j++) {
                                                                    -      if (j === 0 || j === i) {
                                                                    -        res[i][j] = 1;
                                                                    -      } else {
                                                                    -        res[i][j] = res[i - 1][j - 1] + res[i - 1][j];
                                                                    -      }
                                                                    -    }
                                                                    -  }
                                                                    -  return res;
                                                                    -};
                                                                    -
                                                                    -

                                                                    Explain:

                                                                    -

                                                                    nope.

                                                                    -

                                                                    Complexity:

                                                                    -
                                                                      -
                                                                    • Time complexity : O(n^2).
                                                                    • -
                                                                    • Space complexity : O(n^2).
                                                                    • -
                                                                    github
                                                                    \ No newline at end of file diff --git a/docs/problem/path-sum-ii.html b/docs/problem/path-sum-ii.html deleted file mode 100644 index 1de3277..0000000 --- a/docs/problem/path-sum-ii.html +++ /dev/null @@ -1,56 +0,0 @@ -Path Sum II - LeetCode javascript solutions

                                                                    113. Path Sum II

                                                                    Difficulty:
                                                                    Related Topics:

                                                                    Problem

                                                                    -

                                                                    Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

                                                                    -

                                                                    Note: A leaf is a node with no children.

                                                                    -

                                                                    Example:

                                                                    -

                                                                    Given the below binary tree and sum = 22,

                                                                    -
                                                                          5
                                                                    -     / \
                                                                    -    4   8
                                                                    -   /   / \
                                                                    -  11  13  4
                                                                    - /  \    / \
                                                                    -7    2  5   1
                                                                    -
                                                                    -

                                                                    Return:

                                                                    -
                                                                    [
                                                                    -   [5,4,11,2],
                                                                    -   [5,8,4,5]
                                                                    -]
                                                                    -
                                                                    -

                                                                    Solution

                                                                    -
                                                                    /**
                                                                    - * Definition for a binary tree node.
                                                                    - * function TreeNode(val) {
                                                                    - *     this.val = val;
                                                                    - *     this.left = this.right = null;
                                                                    - * }
                                                                    - */
                                                                    -/**
                                                                    - * @param {TreeNode} root
                                                                    - * @param {number} sum
                                                                    - * @return {number[][]}
                                                                    - */
                                                                    -var pathSum = function(root, sum) {
                                                                    -  var res = [];
                                                                    -  helper(root, sum, [], res);
                                                                    -  return res;
                                                                    -};
                                                                    -
                                                                    -var helper = function (root, sum, now, res) {
                                                                    -  if (!root) return;
                                                                    -
                                                                    -  now.push(root.val);
                                                                    -
                                                                    -  if (root.val === sum && !root.left && !root.right) res.push(now);
                                                                    -
                                                                    -  helper(root.left, sum - root.val, Array.from(now), res);
                                                                    -  helper(root.right, sum - root.val, Array.from(now), res);
                                                                    -};
                                                                    -
                                                                    -

                                                                    Explain:

                                                                    -

                                                                    nope.

                                                                    -

                                                                    Complexity:

                                                                    -
                                                                      -
                                                                    • Time complexity :
                                                                    • -
                                                                    • Space complexity :
                                                                    • -
                                                                    github
                                                                    \ No newline at end of file diff --git a/docs/problem/path-sum.html b/docs/problem/path-sum.html deleted file mode 100644 index 07531d2..0000000 --- a/docs/problem/path-sum.html +++ /dev/null @@ -1,40 +0,0 @@ -Path Sum - LeetCode javascript solutions

                                                                    112. Path Sum

                                                                    Difficulty:
                                                                    Related Topics:

                                                                    Problem

                                                                    -

                                                                    Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

                                                                    -

                                                                    Note: A leaf is a node with no children.

                                                                    -

                                                                    Example:

                                                                    -

                                                                    Given the below binary tree and sum = 22,

                                                                    -
                                                                          5
                                                                    -     / \
                                                                    -    4   8
                                                                    -   /   / \
                                                                    -  11  13  4
                                                                    - /  \      \
                                                                    -7    2      1
                                                                    -
                                                                    -

                                                                    return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

                                                                    -

                                                                    Solution

                                                                    -
                                                                    /**
                                                                    - * Definition for a binary tree node.
                                                                    - * function TreeNode(val) {
                                                                    - *     this.val = val;
                                                                    - *     this.left = this.right = null;
                                                                    - * }
                                                                    - */
                                                                    -/**
                                                                    - * @param {TreeNode} root
                                                                    - * @param {number} sum
                                                                    - * @return {boolean}
                                                                    - */
                                                                    -var hasPathSum = function(root, sum) {
                                                                    -  if (!root) return false;
                                                                    -  if (root.val === sum && !root.left && !root.right) return true;
                                                                    -  return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val)
                                                                    -};
                                                                    -
                                                                    -

                                                                    Explain:

                                                                    -

                                                                    nope.

                                                                    -

                                                                    Complexity:

                                                                    -
                                                                      -
                                                                    • Time complexity : O(n).
                                                                    • -
                                                                    • Space complexity : O(1).
                                                                    • -
                                                                    github
                                                                    \ No newline at end of file diff --git a/docs/problem/permutation-sequence.html b/docs/problem/permutation-sequence.html deleted file mode 100644 index d95fed2..0000000 --- a/docs/problem/permutation-sequence.html +++ /dev/null @@ -1,62 +0,0 @@ -Permutation Sequence - LeetCode javascript solutions

                                                                    60. Permutation Sequence

                                                                    Difficulty:
                                                                    Related Topics:

                                                                    Problem

                                                                    -

                                                                    The set [1,2,3,...,**n**] contains a total of n! unique permutations.

                                                                    -

                                                                    By listing and labeling all of the permutations in order, we get the following sequence for n = 3:

                                                                    -
                                                                      -
                                                                    • "123"
                                                                    • -
                                                                    • "132"
                                                                    • -
                                                                    • "213"
                                                                    • -
                                                                    • "231"
                                                                    • -
                                                                    • "312"
                                                                    • -
                                                                    • "321"
                                                                    • -
                                                                    -

                                                                    Given n and k, return the kth permutation sequence.

                                                                    -

                                                                    Note:

                                                                    -
                                                                      -
                                                                    • Given n will be between 1 and 9 inclusive.
                                                                    • -
                                                                    • Given k will be between 1 and n! inclusive.
                                                                    • -
                                                                    -

                                                                    Example 1:

                                                                    -
                                                                    Input: n = 3, k = 3
                                                                    -Output: "213"
                                                                    -
                                                                    -

                                                                    Example 2:

                                                                    -
                                                                    Input: n = 4, k = 9
                                                                    -Output: "2314"
                                                                    -
                                                                    -

                                                                    Solution

                                                                    -
                                                                    /**
                                                                    - * @param {number} n
                                                                    - * @param {number} k
                                                                    - * @return {string}
                                                                    - */
                                                                    -var getPermutation = function(n, k) {
                                                                    -  var str = '';
                                                                    -  var nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];
                                                                    -  var factorial = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]; // n!
                                                                    -  var tmp1 = 0;
                                                                    -  var tmp2 = 0;
                                                                    -
                                                                    -  k--;
                                                                    -
                                                                    -  for (var j = n; j >= 1; j--) {
                                                                    -    tmp1 = factorial[j - 1];
                                                                    -    tmp2 = Math.floor(k / tmp1);
                                                                    -
                                                                    -    k %= tmp1;
                                                                    -    str += nums[tmp2];
                                                                    -
                                                                    -    nums.splice(tmp2, 1);
                                                                    -  }
                                                                    -
                                                                    -  return str;
                                                                    -};
                                                                    -
                                                                    -

                                                                    Explain:

                                                                    -

                                                                    用回溯的方法会超时, -需要用数学规律解的.就是依次找出放在第 index 位的数字。

                                                                    -

                                                                    k-- 这里比较难理解,是用来纠正 k 正好整除于某个阶乘数的特殊情况,即 k % factorial[i] === 0 时。

                                                                    -

                                                                    Complexity:

                                                                    -
                                                                      -
                                                                    • Time complexity : O(n).
                                                                    • -
                                                                    • Space complexity : O(1).
                                                                    • -
                                                                    github
                                                                    \ No newline at end of file diff --git a/docs/problem/permutations-ii.html b/docs/problem/permutations-ii.html deleted file mode 100644 index 44f231b..0000000 --- a/docs/problem/permutations-ii.html +++ /dev/null @@ -1,52 +0,0 @@ -Permutations II - LeetCode javascript solutions

                                                                    47. Permutations II

                                                                    Difficulty:
                                                                    Related Topics:

                                                                    Problem

                                                                    -

                                                                    Given a collection of numbers that might contain duplicates, return all possible unique permutations.

                                                                    -

                                                                    Example:

                                                                    -
                                                                    Input: [1,1,2]
                                                                    -Output:
                                                                    -[
                                                                    -  [1,1,2],
                                                                    -  [1,2,1],
                                                                    -  [2,1,1]
                                                                    -]
                                                                    -
                                                                    -

                                                                    Solution

                                                                    -
                                                                    /**
                                                                    - * @param {number[]} nums
                                                                    - * @return {number[][]}
                                                                    - */
                                                                    -var permuteUnique = function(nums) {
                                                                    -    var res = [];
                                                                    -
                                                                    -    nums.sort((a, b) => (a - b));
                                                                    -    dfs(res, [], nums);
                                                                    -
                                                                    -    return res;
                                                                    -};
                                                                    -
                                                                    -var dfs = function (res, arr, nums) {
                                                                    -  var len = nums.length;
                                                                    -  var tmp1 = null;
                                                                    -  var tmp2 = null;
                                                                    -
                                                                    -  if (!len) return res.push(arr);
                                                                    -
                                                                    -  for (var i = 0; i < len; i++) {
                                                                    -    if (nums[i] === nums[i - 1]) continue;
                                                                    -
                                                                    -    tmp1 = Array.from(arr);
                                                                    -    tmp1.push(nums[i]);
                                                                    -
                                                                    -    tmp2 = Array.from(nums);
                                                                    -    tmp2.splice(i, 1);
                                                                    -
                                                                    -    dfs(res, tmp1, tmp2);
                                                                    -  }
                                                                    -};
                                                                    -
                                                                    -

                                                                    Explain:

                                                                    -

                                                                    跟之前一题的差别是可能有重复的数字,那就先排序一下,遇到重复的数字跳过就好。

                                                                    -

                                                                    Complexity:

                                                                    -
                                                                      -
                                                                    • Time complexity : O(n!).
                                                                    • -
                                                                    • Space complexity :
                                                                    • -
                                                                    github
                                                                    \ No newline at end of file diff --git a/docs/problem/permutations.html b/docs/problem/permutations.html deleted file mode 100644 index 52e7c79..0000000 --- a/docs/problem/permutations.html +++ /dev/null @@ -1,52 +0,0 @@ -Permutations - LeetCode javascript solutions

                                                                    46. Permutations

                                                                    Difficulty:
                                                                    Related Topics:

                                                                    Problem

                                                                    -

                                                                    Given a collection of distinct integers, return all possible permutations.

                                                                    -

                                                                    Example:

                                                                    -
                                                                    Input: [1,2,3]
                                                                    -Output:
                                                                    -[
                                                                    -  [1,2,3],
                                                                    -  [1,3,2],
                                                                    -  [2,1,3],
                                                                    -  [2,3,1],
                                                                    -  [3,1,2],
                                                                    -  [3,2,1]
                                                                    -]
                                                                    -
                                                                    -

                                                                    Solution

                                                                    -
                                                                    /**
                                                                    - * @param {number[]} nums
                                                                    - * @return {number[][]}
                                                                    - */
                                                                    -var permute = function(nums) {
                                                                    -  var res = [];
                                                                    -
                                                                    -  dfs(res, [], nums);
                                                                    -
                                                                    -  return res;
                                                                    -};
                                                                    -
                                                                    -var dfs = function (res, arr, nums) {
                                                                    -  var len = nums.length;
                                                                    -  var tmp1 = null;
                                                                    -  var tmp2 = null;
                                                                    -
                                                                    -  if (!len) return res.push(arr);
                                                                    -
                                                                    -  for (var i = 0; i < len; i++) {
                                                                    -    tmp1 = Array.from(arr);
                                                                    -    tmp1.push(nums[i]);
                                                                    -
                                                                    -    tmp2 = Array.from(nums);
                                                                    -    tmp2.splice(i, 1);
                                                                    -
                                                                    -    dfs(res, tmp1, tmp2);
                                                                    -  }
                                                                    -};
                                                                    -
                                                                    -

                                                                    Explain:

                                                                    -

                                                                    nope.

                                                                    -

                                                                    Complexity:

                                                                    -
                                                                      -
                                                                    • Time complexity : O(n!).
                                                                    • -
                                                                    • Space complexity :
                                                                    • -
                                                                    github
                                                                    \ No newline at end of file diff --git a/docs/problem/plus-one.html b/docs/problem/plus-one.html deleted file mode 100644 index e467677..0000000 --- a/docs/problem/plus-one.html +++ /dev/null @@ -1,40 +0,0 @@ -Plus One - LeetCode javascript solutions

                                                                    66. Plus One

                                                                    Difficulty:
                                                                    Related Topics:

                                                                    Problem

                                                                    -

                                                                    Given a non-empty array of digits representing a non-negative integer, plus one to the integer.

                                                                    -

                                                                    The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.

                                                                    -

                                                                    You may assume the integer does not contain any leading zero, except the number 0 itself.

                                                                    -

                                                                    Example 1:

                                                                    -
                                                                    Input: [1,2,3]
                                                                    -Output: [1,2,4]
                                                                    -Explanation: The array represents the integer 123.
                                                                    -
                                                                    -

                                                                    Example 2:

                                                                    -
                                                                    Input: [4,3,2,1]
                                                                    -Output: [4,3,2,2]
                                                                    -Explanation: The array represents the integer 4321.
                                                                    -
                                                                    -

                                                                    Solution

                                                                    -
                                                                    /**
                                                                    - * @param {number[]} digits
                                                                    - * @return {number[]}
                                                                    - */
                                                                    -var plusOne = function(digits) {
                                                                    -  var i = digits.length - 1;
                                                                    -  var val = 0;
                                                                    -  var carry = 1;
                                                                    -  while (i >= 0 && carry) {
                                                                    -    val = digits[i] + carry;
                                                                    -    carry = Math.floor(val / 10);
                                                                    -    digits[i] = val % 10;
                                                                    -    i--;
                                                                    -  }
                                                                    -  if (carry) digits.unshift(carry);
                                                                    -  return digits;
                                                                    -};
                                                                    -
                                                                    -

                                                                    Explain:

                                                                    -

                                                                    nope.

                                                                    -

                                                                    Complexity:

                                                                    -
                                                                      -
                                                                    • Time complexity : O(n).
                                                                    • -
                                                                    • Space complexity : O(1).
                                                                    • -
                                                                    github
                                                                    \ No newline at end of file diff --git a/docs/problem/populating-next-right-pointers-in-each-node-ii.html b/docs/problem/populating-next-right-pointers-in-each-node-ii.html deleted file mode 100644 index 6a528ab..0000000 --- a/docs/problem/populating-next-right-pointers-in-each-node-ii.html +++ /dev/null @@ -1,111 +0,0 @@ -Populating Next Right Pointers in Each Node II - LeetCode javascript solutions

                                                                    117. Populating Next Right Pointers in Each Node II

                                                                    Difficulty:
                                                                    Related Topics:

                                                                    Problem

                                                                    -

                                                                    Given a binary tree

                                                                    -
                                                                    struct TreeLinkNode {
                                                                    -  TreeLinkNode *left;
                                                                    -  TreeLinkNode *right;
                                                                    -  TreeLinkNode *next;
                                                                    -}
                                                                    -
                                                                    -

                                                                    Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.

                                                                    -

                                                                    Initially, all next pointers are set to NULL.

                                                                    -

                                                                    Note:

                                                                    -
                                                                      -
                                                                    • You may only use constant extra space.
                                                                    • -
                                                                    • Recursive approach is fine, implicit stack space does not count as extra space for this problem.
                                                                    • -
                                                                    -

                                                                    Example:

                                                                    -

                                                                    Given the following binary tree,

                                                                    -
                                                                        1
                                                                    -   /  \
                                                                    -  2    3
                                                                    - / \    \
                                                                    -4   5    7
                                                                    -
                                                                    -

                                                                    After calling your function, the tree should look like:

                                                                    -
                                                                         1 -> NULL
                                                                    -   /  \
                                                                    -  2 -> 3 -> NULL
                                                                    - / \    \
                                                                    -4-> 5 -> 7 -> NULL
                                                                    -
                                                                    -

                                                                    Solution 1

                                                                    -
                                                                    /**
                                                                    - * Definition for binary tree with next pointer.
                                                                    - * function TreeLinkNode(val) {
                                                                    - *     this.val = val;
                                                                    - *     this.left = this.right = this.next = null;
                                                                    - * }
                                                                    - */
                                                                    -
                                                                    -/**
                                                                    - * @param {TreeLinkNode} root
                                                                    - * @return {void} Do not return anything, modify tree in-place instead.
                                                                    - */
                                                                    -var connect = function(root) {
                                                                    -  var stack = [];
                                                                    -  var tmp = null;
                                                                    -  var node = null;
                                                                    -  var next = null;
                                                                    -  var level = 0;
                                                                    -
                                                                    -  if (root) stack.push([root, 0]);
                                                                    -
                                                                    -  while (stack.length) {
                                                                    -    tmp = stack.shift();
                                                                    -    node = tmp[0];
                                                                    -    level = tmp[1];
                                                                    -
                                                                    -    next = stack[0] && stack[0][1] === level ? stack[0][0] : null;
                                                                    -
                                                                    -    node.next = next;
                                                                    -
                                                                    -    if (node.left) stack.push([node.left, level + 1]);
                                                                    -    if (node.right) stack.push([node.right, level + 1]);
                                                                    -  }
                                                                    -};
                                                                    -
                                                                    -

                                                                    Explain:

                                                                    -

                                                                    nope.

                                                                    -

                                                                    Complexity:

                                                                    -
                                                                      -
                                                                    • Time complexity : O(n).
                                                                    • -
                                                                    • Space complexity : O(n).
                                                                    • -
                                                                    -

                                                                    Solution 2

                                                                    -
                                                                    /**
                                                                    - * Definition for binary tree with next pointer.
                                                                    - * function TreeLinkNode(val) {
                                                                    - *     this.val = val;
                                                                    - *     this.left = this.right = this.next = null;
                                                                    - * }
                                                                    - */
                                                                    -
                                                                    -/**
                                                                    - * @param {TreeLinkNode} root
                                                                    - * @return {void} Do not return anything, modify tree in-place instead.
                                                                    - */
                                                                    -var connect = function(root) {
                                                                    -  var now = root;
                                                                    -  var cur = null;
                                                                    -  var tmp = null;
                                                                    -  var last = null;
                                                                    -  while (now) {
                                                                    -    tmp = new TreeLinkNode(0);
                                                                    -    last = tmp;
                                                                    -    cur = now;
                                                                    -    while (cur) {
                                                                    -      if (cur.left) { last.next = cur.left; last = last.next; }
                                                                    -      if (cur.right) { last.next = cur.right; last = last.next; }
                                                                    -      cur = cur.next;
                                                                    -    }
                                                                    -    now = tmp.next;
                                                                    -  }
                                                                    -};
                                                                    -
                                                                    -

                                                                    Explain:

                                                                    -

                                                                    nope.

                                                                    -

                                                                    Complexity:

                                                                    -
                                                                      -
                                                                    • Time complexity : O(n).
                                                                    • -
                                                                    • Space complexity : O(1).
                                                                    • -
                                                                    github
                                                                    \ No newline at end of file diff --git a/docs/problem/populating-next-right-pointers-in-each-node.html b/docs/problem/populating-next-right-pointers-in-each-node.html deleted file mode 100644 index 63ff764..0000000 --- a/docs/problem/populating-next-right-pointers-in-each-node.html +++ /dev/null @@ -1,109 +0,0 @@ -Populating Next Right Pointers in Each Node - LeetCode javascript solutions

                                                                    116. Populating Next Right Pointers in Each Node

                                                                    Difficulty:
                                                                    Related Topics:

                                                                    Problem

                                                                    -

                                                                    Given a binary tree

                                                                    -
                                                                    struct TreeLinkNode {
                                                                    -  TreeLinkNode *left;
                                                                    -  TreeLinkNode *right;
                                                                    -  TreeLinkNode *next;
                                                                    -}
                                                                    -
                                                                    -

                                                                    Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.

                                                                    -

                                                                    Initially, all next pointers are set to NULL.

                                                                    -

                                                                    Note:

                                                                    -
                                                                      -
                                                                    • You may only use constant extra space.

                                                                    • -
                                                                    • Recursive approach is fine, implicit stack space does not count as extra space for this problem.

                                                                    • -
                                                                    • You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).

                                                                    • -
                                                                    -

                                                                    Example:

                                                                    -

                                                                    Given the following perfect binary tree,

                                                                    -
                                                                    1
                                                                    -   /  \
                                                                    -  2    3
                                                                    - / \  / \
                                                                    -4  5  6  7
                                                                    -
                                                                    -

                                                                    After calling your function, the tree should look like:

                                                                    -
                                                                    1 -> NULL
                                                                    -   /  \
                                                                    -  2 -> 3 -> NULL
                                                                    - / \  / \
                                                                    -4->5->6->7 -> NULL
                                                                    -
                                                                    -

                                                                    Solution 1

                                                                    -
                                                                    /**
                                                                    - * Definition for binary tree with next pointer.
                                                                    - * function TreeLinkNode(val) {
                                                                    - *     this.val = val;
                                                                    - *     this.left = this.right = this.next = null;
                                                                    - * }
                                                                    - */
                                                                    -
                                                                    -/**
                                                                    - * @param {TreeLinkNode} root
                                                                    - * @return {void} Do not return anything, modify tree in-place instead.
                                                                    - */
                                                                    -var connect = function(root) {
                                                                    -  var stack = [];
                                                                    -  var tmp = null;
                                                                    -  var node = null;
                                                                    -  var next = null;
                                                                    -  var level = 0;
                                                                    -
                                                                    -  if (root) stack.push([root, 0]);
                                                                    -
                                                                    -  while (stack.length) {
                                                                    -    tmp = stack.shift();
                                                                    -    node = tmp[0];
                                                                    -    level = tmp[1];
                                                                    -
                                                                    -    next = stack[0] && stack[0][1] === level ? stack[0][0] : null;
                                                                    -
                                                                    -    node.next = next;
                                                                    -
                                                                    -    if (node.left) stack.push([node.left, level + 1]);
                                                                    -    if (node.right) stack.push([node.right, level + 1]);
                                                                    -  }
                                                                    -};
                                                                    -
                                                                    -

                                                                    Explain:

                                                                    -

                                                                    nope.

                                                                    -

                                                                    Complexity:

                                                                    -
                                                                      -
                                                                    • Time complexity : O(n).
                                                                    • -
                                                                    • Space complexity : O(n).
                                                                    • -
                                                                    -

                                                                    Solution 2

                                                                    -
                                                                    /**
                                                                    - * Definition for binary tree with next pointer.
                                                                    - * function TreeLinkNode(val) {
                                                                    - *     this.val = val;
                                                                    - *     this.left = this.right = this.next = null;
                                                                    - * }
                                                                    - */
                                                                    -
                                                                    -/**
                                                                    - * @param {TreeLinkNode} root
                                                                    - * @return {void} Do not return anything, modify tree in-place instead.
                                                                    - */
                                                                    -var connect = function(root) {
                                                                    -  if (!root) return;
                                                                    -  var now = root;
                                                                    -  var cur = null;
                                                                    -  while (now.left) {
                                                                    -    cur = now;
                                                                    -    while (cur) {
                                                                    -      cur.left.next = cur.right;
                                                                    -      if (cur.next) cur.right.next = cur.next.left;
                                                                    -      cur = cur.next;
                                                                    -    }
                                                                    -    now = now.left;
                                                                    -  }
                                                                    -};
                                                                    -
                                                                    -

                                                                    Explain:

                                                                    -

                                                                    nope.

                                                                    -

                                                                    Complexity:

                                                                    -
                                                                      -
                                                                    • Time complexity : O(n).
                                                                    • -
                                                                    • Space complexity : O(1).
                                                                    • -
                                                                    github
                                                                    \ No newline at end of file diff --git a/docs/problem/powx-n.html b/docs/problem/powx-n.html deleted file mode 100644 index 25b974d..0000000 --- a/docs/problem/powx-n.html +++ /dev/null @@ -1,49 +0,0 @@ -Pow(x, n) - LeetCode javascript solutions

                                                                    50. Pow(x, n)

                                                                    Difficulty:
                                                                    Related Topics:
                                                                    Similar Questions:

                                                                    Problem

                                                                    -

                                                                    Implement pow(x, n), which calculates x raised to the power n (xn).

                                                                    -

                                                                    Example 1:

                                                                    -
                                                                    Input: 2.00000, 10
                                                                    -Output: 1024.00000
                                                                    -
                                                                    -

                                                                    Example 2:

                                                                    -
                                                                    Input: 2.10000, 3
                                                                    -Output: 9.26100
                                                                    -
                                                                    -

                                                                    Example 3:

                                                                    -
                                                                    Input: 2.00000, -2
                                                                    -Output: 0.25000
                                                                    -Explanation: 2-2 = 1/22 = 1/4 = 0.25
                                                                    -
                                                                    -

                                                                    Note:

                                                                    -
                                                                      -
                                                                    • -100.0 < x < 100.0
                                                                    • -
                                                                    • n is a 32-bit signed integer, within the range [−231, 231 − 1]
                                                                    • -
                                                                    -

                                                                    Solution

                                                                    -
                                                                    /**
                                                                    - * @param {number} x
                                                                    - * @param {number} n
                                                                    - * @return {number}
                                                                    - */
                                                                    -var myPow = function(x, n) {
                                                                    -  if (n === 0) return 1;
                                                                    -  if (n > 0) return pow(x, n);
                                                                    -  if (n < 0) return 1 / pow(x, -n);
                                                                    -};
                                                                    -
                                                                    -var pow = function (x, n) {
                                                                    -  if (n === 1) return x;
                                                                    -  var num = pow(x, Math.floor(n / 2));
                                                                    -  if (n % 2 === 0) {
                                                                    -    return num * num;
                                                                    -  } else {
                                                                    -    return x * num * num;
                                                                    -  }
                                                                    -};
                                                                    -
                                                                    -

                                                                    Explain:

                                                                    -

                                                                    二分、递归。注意 n 小于 0 的情况。

                                                                    -

                                                                    Complexity:

                                                                    -
                                                                      -
                                                                    • Time complexity : O(log(n)).
                                                                    • -
                                                                    • Space complexity : O(log(n)).
                                                                    • -
                                                                    github
                                                                    \ No newline at end of file diff --git a/docs/problem/product-of-array-except-self.html b/docs/problem/product-of-array-except-self.html deleted file mode 100644 index e4fda09..0000000 --- a/docs/problem/product-of-array-except-self.html +++ /dev/null @@ -1,76 +0,0 @@ -Product of Array Except Self - LeetCode javascript solutions

                                                                    238. Product of Array Except Self

                                                                    Difficulty:
                                                                    Related Topics:

                                                                    Problem

                                                                    -

                                                                    Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

                                                                    -

                                                                    Example:

                                                                    -
                                                                    Input:  [1,2,3,4]
                                                                    -Output: [24,12,8,6]
                                                                    -
                                                                    -

                                                                    **Note: **Please solve it without division and in O(n).

                                                                    -

                                                                    Follow up: -Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)

                                                                    -

                                                                    Solution 1

                                                                    -
                                                                    /**
                                                                    - * @param {number[]} nums
                                                                    - * @return {number[]}
                                                                    - */
                                                                    -var productExceptSelf = function(nums) {
                                                                    -  var len = nums.length;
                                                                    -  var left = Array(len + 1);
                                                                    -  var right = Array(len + 1);
                                                                    -  var res = Array(len);
                                                                    -
                                                                    -  left[0] = 1;
                                                                    -  right[0] = 1;
                                                                    -
                                                                    -  for (var i = 0; i < len; i++) {
                                                                    -    left[i + 1] = left[i] * nums[i];
                                                                    -  }
                                                                    -
                                                                    -  for (var j = 0; j < len; j++) {
                                                                    -    right[j + 1] = right[j] * nums[len - 1 - j];
                                                                    -  }
                                                                    -
                                                                    -  for (var k = 0; k < len; k++) {
                                                                    -    res[k] = left[k] * right[len - k - 1];
                                                                    -  }
                                                                    -
                                                                    -  return res;
                                                                    -};
                                                                    -
                                                                    -

                                                                    Explain:

                                                                    -

                                                                    nope.

                                                                    -

                                                                    Complexity:

                                                                    -
                                                                      -
                                                                    • Time complexity : O(n).
                                                                    • -
                                                                    • Space complexity : O(n).
                                                                    • -
                                                                    -

                                                                    Solution 2

                                                                    -
                                                                    /**
                                                                    - * @param {number[]} nums
                                                                    - * @return {number[]}
                                                                    - */
                                                                    -var productExceptSelf = function(nums) {
                                                                    -  var len = nums.length;
                                                                    -  var res = Array(len);
                                                                    -  var right = 1;
                                                                    -
                                                                    -  res[0] = 1;
                                                                    -
                                                                    -  for (var i = 1; i < len; i++) {
                                                                    -    res[i] = res[i - 1] * nums[i - 1];
                                                                    -  }
                                                                    -
                                                                    -  for (var j = len - 1; j >= 0; j--) {
                                                                    -    res[j] *= right;
                                                                    -    right *= nums[j];
                                                                    -  }
                                                                    -
                                                                    -  return res;
                                                                    -};
                                                                    -
                                                                    -

                                                                    Explain:

                                                                    -

                                                                    nope.

                                                                    -

                                                                    Complexity:

                                                                    -
                                                                      -
                                                                    • Time complexity : O(n).
                                                                    • -
                                                                    • Space complexity : O(1).
                                                                    • -
                                                                    github
                                                                    \ No newline at end of file diff --git a/docs/problem/rank-scores.html b/docs/problem/rank-scores.html deleted file mode 100644 index 88b5943..0000000 --- a/docs/problem/rank-scores.html +++ /dev/null @@ -1,59 +0,0 @@ -Rank Scores - LeetCode javascript solutions

                                                                    178. Rank Scores

                                                                    Difficulty:
                                                                    Related Topics:
                                                                      Similar Questions:

                                                                        Problem

                                                                        -

                                                                        Write a SQL query to rank scores. If there is a tie between two scores, both should have the same ranking. Note that after a tie, the next ranking number should be the next consecutive integer value. In other words, there should be no "holes" between ranks.

                                                                        -
                                                                        +----+-------+
                                                                        -| Id | Score |
                                                                        -+----+-------+
                                                                        -| 1  | 3.50  |
                                                                        -| 2  | 3.65  |
                                                                        -| 3  | 4.00  |
                                                                        -| 4  | 3.85  |
                                                                        -| 5  | 4.00  |
                                                                        -| 6  | 3.65  |
                                                                        -+----+-------+
                                                                        -
                                                                        -

                                                                        For example, given the above Scores table, your query should generate the following report (order by highest score):

                                                                        -
                                                                        +-------+------+
                                                                        -| Score | Rank |
                                                                        -+-------+------+
                                                                        -| 4.00  | 1    |
                                                                        -| 4.00  | 1    |
                                                                        -| 3.85  | 2    |
                                                                        -| 3.65  | 3    |
                                                                        -| 3.65  | 3    |
                                                                        -| 3.50  | 4    |
                                                                        -+-------+------+
                                                                        -
                                                                        -

                                                                        Solution 1

                                                                        -
                                                                        # Write your MySQL query statement below
                                                                        -SELECT
                                                                        -  Score,
                                                                        -  (SELECT count(distinct Score) FROM Scores WHERE Score >= s.Score) as Rank
                                                                        -FROM
                                                                        -  Scores s
                                                                        -ORDER BY
                                                                        -  Score DESC
                                                                        -
                                                                        -

                                                                        Explain:

                                                                        -

                                                                        nope.

                                                                        -

                                                                        Complexity:

                                                                        -
                                                                          -
                                                                        • Time complexity :
                                                                        • -
                                                                        • Space complexity :
                                                                        • -
                                                                        -

                                                                        Solution 2

                                                                        -
                                                                        # Write your MySQL query statement below
                                                                        -SELECT
                                                                        -  Score,
                                                                        -  (SELECT count(*) FROM (SELECT distinct Score as s FROM Scores) tmp WHERE s >= Score) as Rank
                                                                        -FROM
                                                                        -  Scores
                                                                        -ORDER BY
                                                                        -  Score DESC
                                                                        -
                                                                        -

                                                                        Explain:

                                                                        -

                                                                        nope.

                                                                        -

                                                                        Complexity:

                                                                        -
                                                                          -
                                                                        • Time complexity :
                                                                        • -
                                                                        • Space complexity :
                                                                        • -
                                                                        github
                                                                        \ No newline at end of file diff --git a/docs/problem/recover-binary-search-tree.html b/docs/problem/recover-binary-search-tree.html deleted file mode 100644 index 1505a70..0000000 --- a/docs/problem/recover-binary-search-tree.html +++ /dev/null @@ -1,140 +0,0 @@ -Recover Binary Search Tree - LeetCode javascript solutions

                                                                        99. Recover Binary Search Tree

                                                                        Difficulty:
                                                                        Related Topics:
                                                                        Similar Questions:

                                                                          Problem

                                                                          -

                                                                          Two elements of a binary search tree (BST) are swapped by mistake.

                                                                          -

                                                                          Recover the tree without changing its structure.

                                                                          -

                                                                          Example 1:

                                                                          -
                                                                          Input: [1,3,null,null,2]
                                                                          -
                                                                          -   1
                                                                          -  /
                                                                          - 3
                                                                          -  \
                                                                          -   2
                                                                          -
                                                                          -Output: [3,1,null,null,2]
                                                                          -
                                                                          -   3
                                                                          -  /
                                                                          - 1
                                                                          -  \
                                                                          -   2
                                                                          -
                                                                          -

                                                                          Example 2:

                                                                          -
                                                                          Input: [3,1,4,null,null,2]
                                                                          -
                                                                          -  3
                                                                          - / \
                                                                          -1   4
                                                                          -   /
                                                                          -  2
                                                                          -
                                                                          -Output: [2,1,4,null,null,3]
                                                                          -
                                                                          -  2
                                                                          - / \
                                                                          -1   4
                                                                          -   /
                                                                          -  3
                                                                          -
                                                                          -

                                                                          Follow up:

                                                                          -
                                                                            -
                                                                          • A solution using O(n) space is pretty straight forward.
                                                                          • -
                                                                          • Could you devise a constant space solution?
                                                                          • -
                                                                          -

                                                                          Solution 1

                                                                          -
                                                                          /**
                                                                          - * Definition for a binary tree node.
                                                                          - * function TreeNode(val) {
                                                                          - *     this.val = val;
                                                                          - *     this.left = this.right = null;
                                                                          - * }
                                                                          - */
                                                                          -/**
                                                                          - * @param {TreeNode} root
                                                                          - * @return {void} Do not return anything, modify root in-place instead.
                                                                          - */
                                                                          -var recoverTree = function(root) {
                                                                          -  var data = {
                                                                          -    prev: null,
                                                                          -    first: null,
                                                                          -    second: null
                                                                          -  };
                                                                          -  var tmp = 0;
                                                                          -
                                                                          -  helper(root, data);
                                                                          -
                                                                          -  tmp = data.first.val;
                                                                          -  data.first.val = data.second.val;
                                                                          -  data.second.val = tmp;
                                                                          -};
                                                                          -
                                                                          -var helper = function (root, data) {
                                                                          -  if (!root) return;
                                                                          -
                                                                          -  helper(root.left, data);
                                                                          -
                                                                          -  if (data.prev && data.prev.val >= root.val) {
                                                                          -    if (!data.first) data.first = data.prev;
                                                                          -    data.second = root;
                                                                          -  }
                                                                          -
                                                                          -  data.prev = root;
                                                                          -
                                                                          -  helper(root.right, data);
                                                                          -};
                                                                          -
                                                                          -

                                                                          Explain:

                                                                          -

                                                                          nope.

                                                                          -

                                                                          Complexity:

                                                                          -
                                                                            -
                                                                          • Time complexity : O(n). n 为节点数。
                                                                          • -
                                                                          • Space complexity : O(1).
                                                                          • -
                                                                          -

                                                                          Solution 2

                                                                          -
                                                                          /**
                                                                          - * Definition for a binary tree node.
                                                                          - * function TreeNode(val) {
                                                                          - *     this.val = val;
                                                                          - *     this.left = this.right = null;
                                                                          - * }
                                                                          - */
                                                                          -/**
                                                                          - * @param {TreeNode} root
                                                                          - * @return {void} Do not return anything, modify root in-place instead.
                                                                          - */
                                                                          -var recoverTree = function(root) {
                                                                          -  var prev = null;
                                                                          -  var first = null;
                                                                          -  var second = null;
                                                                          -  var now = root;
                                                                          -  var stack = [];
                                                                          -  var tmp = 0;
                                                                          -
                                                                          -  while (now || stack.length) {
                                                                          -    while (now) {
                                                                          -      stack.push(now);
                                                                          -      now = now.left;
                                                                          -    }
                                                                          -
                                                                          -    now = stack.pop();
                                                                          -
                                                                          -    if (prev && prev.val >= now.val) {
                                                                          -      if (!first) first = prev;
                                                                          -      second = now;
                                                                          -    }
                                                                          -
                                                                          -    prev = now;
                                                                          -    now = now.right;
                                                                          -  }
                                                                          -
                                                                          -  tmp = first.val;
                                                                          -  first.val = second.val;
                                                                          -  second.val = tmp;
                                                                          -};
                                                                          -
                                                                          -

                                                                          Explain:

                                                                          -

                                                                          nope.

                                                                          -

                                                                          Complexity:

                                                                          -
                                                                            -
                                                                          • Time complexity : O(n). n 为节点数。
                                                                          • -
                                                                          • Space complexity : O(n).
                                                                          • -
                                                                          github
                                                                          \ No newline at end of file diff --git a/docs/problem/regular-expression-matching.html b/docs/problem/regular-expression-matching.html deleted file mode 100644 index 92be1fa..0000000 --- a/docs/problem/regular-expression-matching.html +++ /dev/null @@ -1,85 +0,0 @@ -Regular Expression Matching - LeetCode javascript solutions

                                                                          10. Regular Expression Matching

                                                                          Difficulty:
                                                                          Similar Questions:

                                                                          Problem

                                                                          -

                                                                          Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'.

                                                                          -
                                                                          '.' Matches any single character.
                                                                          -'*' Matches zero or more of the preceding element.
                                                                          -
                                                                          -

                                                                          The matching should cover the entire input string (not partial).

                                                                          -

                                                                          Note:

                                                                          -
                                                                            -
                                                                          • s could be empty and contains only lowercase letters a-z.
                                                                          • -
                                                                          • p could be empty and contains only lowercase letters a-z, and characters like . or *.
                                                                          • -
                                                                          -

                                                                          Example 1:

                                                                          -
                                                                          Input:
                                                                          -s = "aa"
                                                                          -p = "a"
                                                                          -Output: false
                                                                          -Explanation: "a" does not match the entire string "aa".
                                                                          -
                                                                          -

                                                                          Example 2:

                                                                          -
                                                                          Input:
                                                                          -s = "aa"
                                                                          -p = "a*"
                                                                          -Output: true
                                                                          -Explanation: '*' means zero or more of the precedeng element, 'a'. Therefore, by repeating 'a' once, it becomes "aa".
                                                                          -
                                                                          -

                                                                          Example 3:

                                                                          -
                                                                          Input:
                                                                          -s = "ab"
                                                                          -p = ".*"
                                                                          -Output: true
                                                                          -Explanation: ".*" means "zero or more (*) of any character (.)".
                                                                          -
                                                                          -

                                                                          Example 4:

                                                                          -
                                                                          Input:
                                                                          -s = "aab"
                                                                          -p = "c*a*b"
                                                                          -Output: true
                                                                          -Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore it matches "aab".
                                                                          -
                                                                          -

                                                                          Example 5:

                                                                          -
                                                                          Input:
                                                                          -s = "mississippi"
                                                                          -p = "mis*is*p*."
                                                                          -Output: false
                                                                          -
                                                                          -

                                                                          Solution

                                                                          -
                                                                          /**
                                                                          - * @param {string} s
                                                                          - * @param {string} p
                                                                          - * @return {boolean}
                                                                          - */
                                                                          -var isMatch = function(s, p) {
                                                                          -  var dp = Array(s.length + 1).fill(0).map(_ => Array(p.length + 1));
                                                                          -  return helper(dp, 0, 0, s, p);
                                                                          -};
                                                                          -
                                                                          -var helper = function (dp, i, j, s, p) {
                                                                          -  var res = false;
                                                                          -  if (dp[i][j] !== undefined) return dp[i][j];
                                                                          -  if (j === p.length) {
                                                                          -    res = i === s.length;
                                                                          -  } else {
                                                                          -    if (i === s.length) {
                                                                          -      res = p[j + 1] === '*' && helper(dp, i, j + 2, s, p);
                                                                          -    } else if (s[i] === p[j] || p[j] === '.') {
                                                                          -      if (p[j + 1] === '*') {
                                                                          -        res = helper(dp, i + 1, j, s, p) || helper(dp, i, j + 2, s, p) || helper(dp, i + 1, j + 2, s, p);
                                                                          -      } else {
                                                                          -        res = helper(dp, i + 1, j + 1, s, p);
                                                                          -      }
                                                                          -    } else {
                                                                          -      res = p[j + 1] === '*' && helper(dp, i, j + 2, s, p);
                                                                          -    }
                                                                          -  }
                                                                          -  dp[i][j] = res;
                                                                          -  return res;
                                                                          -};
                                                                          -
                                                                          -

                                                                          Explain:

                                                                          -

                                                                          动态规划,dp[i][j] 代表 s[i]p[j] 是否可匹配。

                                                                          -

                                                                          Complexity:

                                                                          -
                                                                            -
                                                                          • Time complexity : O(mn).
                                                                          • -
                                                                          • Space complexity : O(mn).
                                                                          • -
                                                                          github
                                                                          \ No newline at end of file diff --git a/docs/problem/remove-duplicate-letters.html b/docs/problem/remove-duplicate-letters.html deleted file mode 100644 index b412fcb..0000000 --- a/docs/problem/remove-duplicate-letters.html +++ /dev/null @@ -1,47 +0,0 @@ -Remove Duplicate Letters - LeetCode javascript solutions

                                                                          316. Remove Duplicate Letters

                                                                          Difficulty:
                                                                          Related Topics:
                                                                          Similar Questions:

                                                                            Problem

                                                                            -

                                                                            Given a string which contains only lowercase letters, remove duplicate letters so that every letter appear once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.

                                                                            -

                                                                            Example 1:

                                                                            -
                                                                            Input: "bcabc"
                                                                            -Output: "abc"
                                                                            -
                                                                            -

                                                                            Example 2:

                                                                            -
                                                                            Input: "cbacdcbc"
                                                                            -Output: "acdb"
                                                                            -
                                                                            -

                                                                            Solution

                                                                            -
                                                                            /**
                                                                            - * @param {string} s
                                                                            - * @return {string}
                                                                            - */
                                                                            -var removeDuplicateLetters = function(s) {
                                                                            -  var count = {};
                                                                            -  var len = s.length;
                                                                            -  var index = 0;
                                                                            -
                                                                            -  if (!len) return '';
                                                                            -
                                                                            -  for (var i = 0; i < len; i++) {
                                                                            -    if (count[s[i]] === undefined) count[s[i]] = 0;
                                                                            -    count[s[i]]++;
                                                                            -  }
                                                                            -
                                                                            -  for (var j = 0; j < len; j++) {
                                                                            -    if (s[j] < s[index]) index = j;
                                                                            -    if (--count[s[j]] === 0) break;
                                                                            -  }
                                                                            -
                                                                            -  var firstChar = s[index];
                                                                            -  var restString = s.substr(index + 1);
                                                                            -
                                                                            -  restString = restString.replace(new RegExp(firstChar, 'g'), '');
                                                                            -
                                                                            -  return firstChar + removeDuplicateLetters(restString);
                                                                            -};
                                                                            -
                                                                            -

                                                                            Explain:

                                                                            -

                                                                            贪心,每次找到排第一的字符,再递归。

                                                                            -

                                                                            Complexity:

                                                                            -
                                                                              -
                                                                            • Time complexity : O(n).
                                                                            • -
                                                                            • Space complexity : O(n).
                                                                            • -
                                                                            github
                                                                            \ No newline at end of file diff --git a/docs/problem/remove-duplicates-from-sorted-array-ii.html b/docs/problem/remove-duplicates-from-sorted-array-ii.html deleted file mode 100644 index d3d3bdf..0000000 --- a/docs/problem/remove-duplicates-from-sorted-array-ii.html +++ /dev/null @@ -1,61 +0,0 @@ -Remove Duplicates from Sorted Array II - LeetCode javascript solutions

                                                                            80. Remove Duplicates from Sorted Array II

                                                                            Difficulty:
                                                                            Related Topics:

                                                                            Problem

                                                                            -

                                                                            Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length.

                                                                            -

                                                                            Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

                                                                            -

                                                                            Example 1:

                                                                            -
                                                                            Given nums = [1,1,1,2,2,3],
                                                                            -
                                                                            -Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively.
                                                                            -
                                                                            -It doesn't matter what you leave beyond the returned length.
                                                                            -
                                                                            -

                                                                            Example 2:

                                                                            -
                                                                            Given nums = [0,0,1,1,1,1,2,3,3],
                                                                            -
                                                                            -Your function should return length = 7, with the first seven elements of nums being modified to 0, 0, 1, 1, 2, 3 and 3 respectively.
                                                                            -
                                                                            -It doesn't matter what values are set beyond the returned length.
                                                                            -
                                                                            -

                                                                            Clarification:

                                                                            -

                                                                            Confused why the returned value is an integer but your answer is an array?

                                                                            -

                                                                            Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.

                                                                            -

                                                                            Internally you can think of this:

                                                                            -
                                                                            // nums is passed in by reference. (i.e., without making a copy)
                                                                            -int len = removeDuplicates(nums);
                                                                            -
                                                                            -// any modification to nums in your function would be known by the caller.
                                                                            -// using the length returned by your function, it prints the first len elements.
                                                                            -for (int i = 0; i < len; i++) {
                                                                            -    print(nums[i]);
                                                                            -}
                                                                            -
                                                                            -

                                                                            Solution

                                                                            -
                                                                            /**
                                                                            - * @param {number[]} nums
                                                                            - * @return {number}
                                                                            - */
                                                                            -var removeDuplicates = function(nums) {
                                                                            -  var len = nums.length;
                                                                            -  var index = 0;
                                                                            -  var last = NaN;
                                                                            -  var times = 0;
                                                                            -  for (var i = 0; i < len; i++) {
                                                                            -    if (nums[i] === last) {
                                                                            -      if (times < 2) times++;
                                                                            -      else continue;
                                                                            -    } else {
                                                                            -      times = 1;
                                                                            -    }
                                                                            -    last = nums[i];
                                                                            -    nums[index] = nums[i];
                                                                            -    index++;
                                                                            -  }
                                                                            -  return index;
                                                                            -};
                                                                            -
                                                                            -

                                                                            Explain:

                                                                            -

                                                                            nope.

                                                                            -

                                                                            Complexity:

                                                                            -
                                                                              -
                                                                            • Time complexity : O(n).
                                                                            • -
                                                                            • Space complexity : O(1).
                                                                            • -
                                                                            github
                                                                            \ No newline at end of file diff --git a/docs/problem/remove-duplicates-from-sorted-array.html b/docs/problem/remove-duplicates-from-sorted-array.html deleted file mode 100644 index ec1ebc2..0000000 --- a/docs/problem/remove-duplicates-from-sorted-array.html +++ /dev/null @@ -1,56 +0,0 @@ -Remove Duplicates from Sorted Array - LeetCode javascript solutions

                                                                            26. Remove Duplicates from Sorted Array

                                                                            Difficulty:
                                                                            Related Topics:

                                                                            Problem

                                                                            -

                                                                            Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.

                                                                            -

                                                                            Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

                                                                            -

                                                                            Example 1:

                                                                            -
                                                                            Given nums = [1,1,2],
                                                                            -
                                                                            -Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
                                                                            -
                                                                            -It doesn't matter what you leave beyond the returned length.
                                                                            -
                                                                            -

                                                                            Example 2:

                                                                            -
                                                                            Given nums = [0,0,1,1,1,2,2,3,3,4],
                                                                            -
                                                                            -Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.
                                                                            -
                                                                            -It doesn't matter what values are set beyond the returned length.
                                                                            -
                                                                            -

                                                                            Clarification:

                                                                            -

                                                                            Confused why the returned value is an integer but your answer is an array?

                                                                            -

                                                                            Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.

                                                                            -

                                                                            Internally you can think of this:

                                                                            -
                                                                            // nums is passed in by reference. (i.e., without making a copy)
                                                                            -int len = removeDuplicates(nums);
                                                                            -
                                                                            -// any modification to nums in your function would be known by the caller.
                                                                            -// using the length returned by your function, it prints the first len elements.
                                                                            -for (int i = 0; i < len; i++) {
                                                                            -    print(nums[i]);
                                                                            -}
                                                                            -
                                                                            -

                                                                            Solution

                                                                            -
                                                                            /**
                                                                            - * @param {number[]} nums
                                                                            - * @return {number}
                                                                            - */
                                                                            -var removeDuplicates = function(nums) {
                                                                            -  var len = nums.length;
                                                                            -  var last = NaN;
                                                                            -  var count = 0;
                                                                            -  for (var i = 0; i < len; i++) {
                                                                            -    if (nums[i] !== last) {
                                                                            -      nums[count] = nums[i];
                                                                            -      last = nums[i];
                                                                            -      count++;
                                                                            -    }
                                                                            -  }
                                                                            -  return count;
                                                                            -};
                                                                            -
                                                                            -

                                                                            Explain:

                                                                            -

                                                                            nope.

                                                                            -

                                                                            Complexity:

                                                                            -
                                                                              -
                                                                            • Time complexity : O(n).
                                                                            • -
                                                                            • Space complexity : O(1).
                                                                            • -
                                                                            github
                                                                            \ No newline at end of file diff --git a/docs/problem/remove-duplicates-from-sorted-list-ii.html b/docs/problem/remove-duplicates-from-sorted-list-ii.html deleted file mode 100644 index 5d1df40..0000000 --- a/docs/problem/remove-duplicates-from-sorted-list-ii.html +++ /dev/null @@ -1,51 +0,0 @@ -Remove Duplicates from Sorted List II - LeetCode javascript solutions

                                                                            82. Remove Duplicates from Sorted List II

                                                                            Difficulty:
                                                                            Related Topics:

                                                                            Problem

                                                                            -

                                                                            Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

                                                                            -

                                                                            Example 1:

                                                                            -
                                                                            Input: 1->2->3->3->4->4->5
                                                                            -Output: 1->2->5
                                                                            -
                                                                            -

                                                                            Example 2:

                                                                            -
                                                                            Input: 1->1->1->2->3
                                                                            -Output: 2->3
                                                                            -
                                                                            -

                                                                            Solution

                                                                            -
                                                                            /**
                                                                            - * Definition for singly-linked list.
                                                                            - * function ListNode(val) {
                                                                            - *     this.val = val;
                                                                            - *     this.next = null;
                                                                            - * }
                                                                            - */
                                                                            -/**
                                                                            - * @param {ListNode} head
                                                                            - * @return {ListNode}
                                                                            - */
                                                                            -var deleteDuplicates = function(head) {
                                                                            -  var newHead = new ListNode(0);
                                                                            -  var now = newHead;
                                                                            -  var tmp = head;
                                                                            -  var val = 0;
                                                                            -
                                                                            -  while (tmp) {
                                                                            -    val = tmp.val;
                                                                            -    if (tmp.next && tmp.next.val === val) {
                                                                            -      tmp = tmp.next;
                                                                            -      while (tmp && tmp.val === val) tmp = tmp.next;
                                                                            -    } else {
                                                                            -      now.next = tmp;
                                                                            -      now = tmp;
                                                                            -      tmp = tmp.next;
                                                                            -      now.next = null;
                                                                            -    }
                                                                            -  }
                                                                            -
                                                                            -  return newHead.next;
                                                                            -};
                                                                            -
                                                                            -

                                                                            Explain:

                                                                            -

                                                                            nope.

                                                                            -

                                                                            Complexity:

                                                                            -
                                                                              -
                                                                            • Time complexity : O(n).
                                                                            • -
                                                                            • Space complexity : O(1).
                                                                            • -
                                                                            github
                                                                            \ No newline at end of file diff --git a/docs/problem/remove-duplicates-from-sorted-list.html b/docs/problem/remove-duplicates-from-sorted-list.html deleted file mode 100644 index 92775f3..0000000 --- a/docs/problem/remove-duplicates-from-sorted-list.html +++ /dev/null @@ -1,41 +0,0 @@ -Remove Duplicates from Sorted List - LeetCode javascript solutions

                                                                            83. Remove Duplicates from Sorted List

                                                                            Difficulty:
                                                                            Related Topics:

                                                                            Problem

                                                                            -

                                                                            Given a sorted linked list, delete all duplicates such that each element appear only once.

                                                                            -

                                                                            Example 1:

                                                                            -
                                                                            Input: 1->1->2
                                                                            -Output: 1->2
                                                                            -
                                                                            -

                                                                            Example 2:

                                                                            -
                                                                            Input: 1->1->2->3->3
                                                                            -Output: 1->2->3
                                                                            -
                                                                            -

                                                                            Solution

                                                                            -
                                                                            /**
                                                                            - * Definition for singly-linked list.
                                                                            - * function ListNode(val) {
                                                                            - *     this.val = val;
                                                                            - *     this.next = null;
                                                                            - * }
                                                                            - */
                                                                            -/**
                                                                            - * @param {ListNode} head
                                                                            - * @return {ListNode}
                                                                            - */
                                                                            -var deleteDuplicates = function(head) {
                                                                            -  var now = head;
                                                                            -  while (now) {
                                                                            -    if (now.next && now.next.val === now.val) {
                                                                            -      now.next = now.next.next;
                                                                            -    } else {
                                                                            -      now = now.next;
                                                                            -    }
                                                                            -  }
                                                                            -  return head;
                                                                            -};
                                                                            -
                                                                            -

                                                                            Explain:

                                                                            -

                                                                            nope.

                                                                            -

                                                                            Complexity:

                                                                            -
                                                                              -
                                                                            • Time complexity : O(n).
                                                                            • -
                                                                            • Space complexity : O(1).
                                                                            • -
                                                                            github
                                                                            \ No newline at end of file diff --git a/docs/problem/remove-element.html b/docs/problem/remove-element.html deleted file mode 100644 index 3e95754..0000000 --- a/docs/problem/remove-element.html +++ /dev/null @@ -1,55 +0,0 @@ -Remove Element - LeetCode javascript solutions

                                                                            27. Remove Element

                                                                            Difficulty:
                                                                            Related Topics:

                                                                            Problem

                                                                            -

                                                                            Given an array nums and a value val, remove all instances of that value in-place and return the new length.

                                                                            -

                                                                            Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

                                                                            -

                                                                            The order of elements can be changed. It doesn't matter what you leave beyond the new length.

                                                                            -

                                                                            Example 1:

                                                                            -
                                                                            Given nums = [3,2,2,3], val = 3,
                                                                            -
                                                                            -Your function should return length = 2, with the first two elements of nums being 2.
                                                                            -
                                                                            -It doesn't matter what you leave beyond the returned length.
                                                                            -
                                                                            -

                                                                            Example 2:

                                                                            -
                                                                            Given nums = [0,1,2,2,3,0,4,2], val = 2,
                                                                            -
                                                                            -Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.
                                                                            -
                                                                            -Note that the order of those five elements can be arbitrary.
                                                                            -
                                                                            -It doesn't matter what values are set beyond the returned length.
                                                                            -
                                                                            -

                                                                            Clarification:

                                                                            -

                                                                            Confused why the returned value is an integer but your answer is an array?

                                                                            -

                                                                            Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.

                                                                            -

                                                                            Internally you can think of this:

                                                                            -
                                                                            // nums is passed in by reference. (i.e., without making a copy)
                                                                            -int len = removeElement(nums, val);
                                                                            -
                                                                            -// any modification to nums in your function would be known by the caller.
                                                                            -// using the length returned by your function, it prints the first len elements.
                                                                            -for (int i = 0; i < len; i++) {
                                                                            -    print(nums[i]);
                                                                            -}
                                                                            -
                                                                            -

                                                                            Solution

                                                                            -
                                                                            /**
                                                                            - * @param {number[]} nums
                                                                            - * @param {number} val
                                                                            - * @return {number}
                                                                            - */
                                                                            -var removeElement = function(nums, val) {
                                                                            -  var len = nums.length;
                                                                            -  var count = 0;
                                                                            -  for (var i = 0; i < len; i++) {
                                                                            -    if (nums[i] !== val) nums[count++] = nums[i];
                                                                            -  }
                                                                            -  return count;
                                                                            -};
                                                                            -
                                                                            -

                                                                            Explain:

                                                                            -

                                                                            nope.

                                                                            -

                                                                            Complexity:

                                                                            -
                                                                              -
                                                                            • Time complexity : O(n).
                                                                            • -
                                                                            • Space complexity : O(1).
                                                                            • -
                                                                            github
                                                                            \ No newline at end of file diff --git a/docs/problem/remove-nth-node-from-end-of-list.html b/docs/problem/remove-nth-node-from-end-of-list.html deleted file mode 100644 index 2014c34..0000000 --- a/docs/problem/remove-nth-node-from-end-of-list.html +++ /dev/null @@ -1,58 +0,0 @@ -Remove Nth Node From End of List - LeetCode javascript solutions

                                                                            19. Remove Nth Node From End of List

                                                                            Difficulty:
                                                                            Similar Questions:

                                                                              Problem

                                                                              -

                                                                              Given a linked list, remove the n-th node from the end of list and return its head.

                                                                              -

                                                                              Example:

                                                                              -
                                                                              Given linked list: 1->2->3->4->5, and n = 2.
                                                                              -
                                                                              -After removing the second node from the end, the linked list becomes 1->2->3->5.
                                                                              -
                                                                              -

                                                                              Note:

                                                                              -

                                                                              Given n will always be valid.

                                                                              -

                                                                              Follow up:

                                                                              -

                                                                              Could you do this in one pass?

                                                                              -

                                                                              Solution

                                                                              -
                                                                              /**
                                                                              - * Definition for singly-linked list.
                                                                              - * function ListNode(val) {
                                                                              - *     this.val = val;
                                                                              - *     this.next = null;
                                                                              - * }
                                                                              - */
                                                                              -/**
                                                                              - * @param {ListNode} head
                                                                              - * @param {number} n
                                                                              - * @return {ListNode}
                                                                              - */
                                                                              -var removeNthFromEnd = function(head, n) {
                                                                              -  var h = new ListNode(0);
                                                                              -  var ll = h;
                                                                              -  var rr = h;
                                                                              -
                                                                              -  h.next = head;
                                                                              -
                                                                              -  for (var i = 0; i < n + 1; i++) {
                                                                              -    rr = rr.next;
                                                                              -  }
                                                                              -
                                                                              -  while (rr !== null) {
                                                                              -    ll = ll.next;
                                                                              -    rr= rr.next;
                                                                              -  }
                                                                              -
                                                                              -  ll.next = ll.next.next;
                                                                              -
                                                                              -  return h.next;
                                                                              -};
                                                                              -
                                                                              -

                                                                              Explain:

                                                                              -
                                                                                -
                                                                              1. 两个指针 a, b,初始都指向开头
                                                                              2. -
                                                                              3. b 指针往后移动,直到两指针的位置相差 n
                                                                              4. -
                                                                              5. 同时移动两指针,直到 b 指针到了最后。这时候因为两指针的位置相差 na 指针的位置就是从后面数第 n+1
                                                                              6. -
                                                                              7. a 指针那里删掉后面一个,即第 n
                                                                              8. -
                                                                              -

                                                                              要注意可能会出现删掉 head 的情况。

                                                                              -

                                                                              Complexity:

                                                                              -
                                                                                -
                                                                              • Time complexity : O(n).
                                                                              • -
                                                                              • Space complexity : O(1).
                                                                              • -
                                                                              github
                                                                              \ No newline at end of file diff --git a/docs/problem/reorder-list.html b/docs/problem/reorder-list.html deleted file mode 100644 index 4ff6059..0000000 --- a/docs/problem/reorder-list.html +++ /dev/null @@ -1,74 +0,0 @@ -Reorder List - LeetCode javascript solutions

                                                                              143. Reorder List

                                                                              Difficulty:
                                                                              Related Topics:
                                                                              Similar Questions:

                                                                                Problem

                                                                                -

                                                                                Given a singly linked list L: L0→L1→…→Ln-1→Ln, -reorder it to: L0→LnL1→Ln-1→L2→Ln-2→…

                                                                                -

                                                                                You may not modify the values in the list's nodes, only nodes itself may be changed.

                                                                                -

                                                                                Example 1:

                                                                                -
                                                                                Given 1->2->3->4, reorder it to 1->4->2->3.
                                                                                -
                                                                                -

                                                                                Example 2:

                                                                                -
                                                                                Given 1->2->3->4->5, reorder it to 1->5->2->4->3.
                                                                                -
                                                                                -

                                                                                Solution

                                                                                -
                                                                                /**
                                                                                - * Definition for singly-linked list.
                                                                                - * function ListNode(val) {
                                                                                - *     this.val = val;
                                                                                - *     this.next = null;
                                                                                - * }
                                                                                - */
                                                                                -/**
                                                                                - * @param {ListNode} head
                                                                                - * @return {void} Do not return anything, modify head in-place instead.
                                                                                - */
                                                                                -var reorderList = function(head) {
                                                                                -  if (!head || !head.next || !head.next.next) return;
                                                                                -
                                                                                -  // find mid
                                                                                -  var mid = null;
                                                                                -  var fast = head;
                                                                                -  var slow = head;
                                                                                -  while (fast.next && fast.next.next && slow.next) {
                                                                                -    slow = slow.next;
                                                                                -    fast = fast.next.next;
                                                                                -  }
                                                                                -  mid = slow;
                                                                                -
                                                                                -  // reverse the later part
                                                                                -  var now = mid.next.next;
                                                                                -  var second = mid.next;
                                                                                -  var tmp = null;
                                                                                -  second.next = null;
                                                                                -  while (now) {
                                                                                -    tmp = now.next;
                                                                                -    now.next = second;
                                                                                -    second = now;
                                                                                -    now = tmp;
                                                                                -  }
                                                                                -  mid.next = second;
                                                                                -
                                                                                -  // insert one after another
                                                                                -  var before = head;
                                                                                -  var after = mid.next;
                                                                                -  mid.next = null;
                                                                                -  while (after) {
                                                                                -    tmp = before.next;
                                                                                -    before.next = after;
                                                                                -    before = tmp;
                                                                                -    tmp = after.next;
                                                                                -    after.next = before;
                                                                                -    after = tmp
                                                                                -  }
                                                                                -};
                                                                                -
                                                                                -

                                                                                Explain:

                                                                                -

                                                                                比如 1->2->3->4->5->6 ,分三步

                                                                                -
                                                                                  -
                                                                                1. 找到 mid = 3
                                                                                2. -
                                                                                3. 翻转后半部分,变成 1->2->3->6->5->4
                                                                                4. -
                                                                                5. 后半部分依次插入到前半部分
                                                                                6. -
                                                                                -

                                                                                Complexity:

                                                                                -
                                                                                  -
                                                                                • Time complexity : O(n).
                                                                                • -
                                                                                • Space complexity : O(1).
                                                                                • -
                                                                                github
                                                                                \ No newline at end of file diff --git a/docs/problem/reshape-the-matrix.html b/docs/problem/reshape-the-matrix.html deleted file mode 100644 index e2d887e..0000000 --- a/docs/problem/reshape-the-matrix.html +++ /dev/null @@ -1,61 +0,0 @@ -Reshape the Matrix - LeetCode javascript solutions

                                                                                566. Reshape the Matrix

                                                                                Difficulty:
                                                                                Related Topics:
                                                                                Similar Questions:

                                                                                  Problem

                                                                                  -

                                                                                  In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a new one with different size but keep its original data.

                                                                                  -

                                                                                  You're given a matrix represented by a two-dimensional array, and two positive integers r and c representing the row number and column number of the wanted reshaped matrix, respectively.

                                                                                  -

                                                                                  The reshaped matrix need to be filled with all the elements of the original matrix in the same row-traversing order as they were.

                                                                                  -

                                                                                  If the 'reshape' operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.

                                                                                  -

                                                                                  Example 1:

                                                                                  -
                                                                                  Input: 
                                                                                  -nums = 
                                                                                  -[[1,2],
                                                                                  - [3,4]]
                                                                                  -r = 1, c = 4
                                                                                  -Output: 
                                                                                  -[[1,2,3,4]]
                                                                                  -Explanation:The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list.
                                                                                  -
                                                                                  -

                                                                                  Example 2:

                                                                                  -
                                                                                  Input: 
                                                                                  -nums = 
                                                                                  -[[1,2],
                                                                                  - [3,4]]
                                                                                  -r = 2, c = 4
                                                                                  -Output: 
                                                                                  -[[1,2],
                                                                                  - [3,4]]
                                                                                  -Explanation:There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix.
                                                                                  -
                                                                                  -

                                                                                  Note:

                                                                                  -
                                                                                    -
                                                                                  • The height and width of the given matrix is in range [1, 100].
                                                                                  • -
                                                                                  • The given r and c are all positive.
                                                                                  • -
                                                                                  -

                                                                                  Solution

                                                                                  -
                                                                                  /**
                                                                                  - * @param {number[][]} nums
                                                                                  - * @param {number} r
                                                                                  - * @param {number} c
                                                                                  - * @return {number[][]}
                                                                                  - */
                                                                                  -var matrixReshape = function(nums, r, c) {
                                                                                  -  var m = nums.length;
                                                                                  -  var n = nums[0].length;
                                                                                  -
                                                                                  -  if (m * n !== r * c) return nums;
                                                                                  -
                                                                                  -  var res = Array(r).fill(0).map(_ => Array(c));
                                                                                  -  var num = r * c;
                                                                                  -
                                                                                  -  for (var i = 0; i < num; i++) {
                                                                                  -    res[Math.floor(i / c)][i % c] = nums[Math.floor(i / n)][i % n];
                                                                                  -  }
                                                                                  -
                                                                                  -  return res;
                                                                                  -};
                                                                                  -
                                                                                  -

                                                                                  Explain:

                                                                                  -

                                                                                  nope.

                                                                                  -

                                                                                  Complexity:

                                                                                  -
                                                                                    -
                                                                                  • Time complexity : O(r*c).
                                                                                  • -
                                                                                  • Space complexity : O(r*c).
                                                                                  • -
                                                                                  github
                                                                                  \ No newline at end of file diff --git a/docs/problem/restore-ip-addresses.html b/docs/problem/restore-ip-addresses.html deleted file mode 100644 index 0bce4b7..0000000 --- a/docs/problem/restore-ip-addresses.html +++ /dev/null @@ -1,95 +0,0 @@ -Restore IP Addresses - LeetCode javascript solutions

                                                                                  93. Restore IP Addresses

                                                                                  Difficulty:
                                                                                  Related Topics:
                                                                                  Similar Questions:

                                                                                  Problem

                                                                                  -

                                                                                  Given a string containing only digits, restore it by returning all possible valid IP address combinations.

                                                                                  -

                                                                                  Example:

                                                                                  -
                                                                                  Input: "25525511135"
                                                                                  -Output: ["255.255.11.135", "255.255.111.35"]
                                                                                  -
                                                                                  -

                                                                                  Solution 1

                                                                                  -
                                                                                  /**
                                                                                  - * @param {string} s
                                                                                  - * @return {string[]}
                                                                                  - */
                                                                                  -var restoreIpAddresses = function(s) {
                                                                                  -  var res = [];
                                                                                  -  helper(s, 0, [], res);
                                                                                  -  return res;
                                                                                  -};
                                                                                  -
                                                                                  -var helper = function (s, start, now, res) {
                                                                                  -  var str = '';
                                                                                  -  var num = 0;
                                                                                  -
                                                                                  -  if (now.length === 4) {
                                                                                  -    if (start === s.length) res.push(now.join('.'));
                                                                                  -    return;
                                                                                  -  }
                                                                                  -
                                                                                  -  for (var i = 1; i <= 3; i++) {
                                                                                  -    str = s.substr(start, i);
                                                                                  -    if (str.length === 1 || str[0] !== '0') {
                                                                                  -      num = Number(str);
                                                                                  -      if (0 <= num && num <= 255) {
                                                                                  -        now.push(num);
                                                                                  -        helper(s, start + i, now, res);
                                                                                  -        now.pop();
                                                                                  -      }
                                                                                  -    }
                                                                                  -  }
                                                                                  -};
                                                                                  -
                                                                                  -

                                                                                  Explain:

                                                                                  -

                                                                                  nope.

                                                                                  -

                                                                                  Complexity:

                                                                                  -
                                                                                    -
                                                                                  • Time complexity : O(1).
                                                                                  • -
                                                                                  • Space complexity : O(1).
                                                                                  • -
                                                                                  -

                                                                                  Solution 2

                                                                                  -
                                                                                  /**
                                                                                  - * @param {string} s
                                                                                  - * @return {string[]}
                                                                                  - */
                                                                                  -var restoreIpAddresses = function(s) {
                                                                                  -  var res = [];
                                                                                  -  var len = s.length;
                                                                                  -  var str1 = '';
                                                                                  -  var str2 = '';
                                                                                  -  var str3 = '';
                                                                                  -  var str4 = '';
                                                                                  -
                                                                                  -  for (var i = 1; i <= 3; i++) {
                                                                                  -    for (var j = 1; j <= 3; j++) {
                                                                                  -      for (var k = 1; k <= 3; k++) {
                                                                                  -        for (var m = 1; m <= 3; m++) {
                                                                                  -          str1 = s.substr(0, i);
                                                                                  -          str2 = s.substr(i, j);
                                                                                  -          str3 = s.substr(i + j, k);
                                                                                  -          str4 = s.substr(i + j + k, m);
                                                                                  -          if (i + j + k + m === len
                                                                                  -              && isValid(str1)
                                                                                  -              && isValid(str2)
                                                                                  -              && isValid(str3)
                                                                                  -              && isValid(str4)) {
                                                                                  -            res.push(str1 + '.' + str2 + '.' + str3 + '.' + str4);
                                                                                  -          }
                                                                                  -        }
                                                                                  -      }
                                                                                  -    }
                                                                                  -  }
                                                                                  -
                                                                                  -  return res;
                                                                                  -};
                                                                                  -
                                                                                  -var isValid = function (str) {
                                                                                  -  if (str.length > 1 && str[0] === '0') return false;
                                                                                  -  if (Number(str) > 255) return false;
                                                                                  -  return true;
                                                                                  -};
                                                                                  -
                                                                                  -

                                                                                  Explain:

                                                                                  -

                                                                                  nope.

                                                                                  -

                                                                                  Complexity:

                                                                                  -
                                                                                    -
                                                                                  • Time complexity : O(1).
                                                                                  • -
                                                                                  • Space complexity : O(1).
                                                                                  • -
                                                                                  github
                                                                                  \ No newline at end of file diff --git a/docs/problem/reverse-integer.html b/docs/problem/reverse-integer.html deleted file mode 100644 index fc8456d..0000000 --- a/docs/problem/reverse-integer.html +++ /dev/null @@ -1,41 +0,0 @@ -Reverse Integer - LeetCode javascript solutions

                                                                                  7. Reverse Integer

                                                                                  Difficulty:
                                                                                  Related Topics:
                                                                                  Similar Questions:

                                                                                  Problem

                                                                                  -

                                                                                  Given a 32-bit signed integer, reverse digits of an integer.

                                                                                  -

                                                                                  Example 1:

                                                                                  -
                                                                                  Input: 123
                                                                                  -Output: 321
                                                                                  -
                                                                                  -

                                                                                  Example 2:

                                                                                  -
                                                                                  Input: -123
                                                                                  -Output: -321
                                                                                  -
                                                                                  -

                                                                                  Example 3:

                                                                                  -
                                                                                  Input: 120
                                                                                  -Output: 21
                                                                                  -
                                                                                  -

                                                                                  Note: -Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

                                                                                  -

                                                                                  Solution

                                                                                  -
                                                                                  /**
                                                                                  - * @param {number} x
                                                                                  - * @return {number}
                                                                                  - */
                                                                                  -var reverse = function(x) {
                                                                                  -  var INT_MAX = 2147483647;
                                                                                  -  var INT_MIN = - INT_MAX - 1;
                                                                                  -  var res = 0;
                                                                                  -  var num = x;
                                                                                  -  while (num !== 0) {
                                                                                  -    res = (res * 10) + (num % 10);
                                                                                  -    num = num > 0 ? Math.floor(num / 10) : Math.ceil(num / 10);
                                                                                  -    if (res > INT_MAX || res < INT_MIN) return 0;
                                                                                  -  }
                                                                                  -  return res;
                                                                                  -};
                                                                                  -
                                                                                  -

                                                                                  Explain:

                                                                                  -

                                                                                  nope.

                                                                                  -

                                                                                  Complexity:

                                                                                  -
                                                                                    -
                                                                                  • Time complexity : O(log(n)).
                                                                                  • -
                                                                                  • Space complexity : O(n).
                                                                                  • -
                                                                                  github
                                                                                  \ No newline at end of file diff --git a/docs/problem/reverse-linked-list-ii.html b/docs/problem/reverse-linked-list-ii.html deleted file mode 100644 index 273dc35..0000000 --- a/docs/problem/reverse-linked-list-ii.html +++ /dev/null @@ -1,68 +0,0 @@ -Reverse Linked List II - LeetCode javascript solutions

                                                                                  92. Reverse Linked List II

                                                                                  Difficulty:
                                                                                  Related Topics:
                                                                                  Similar Questions:

                                                                                  Problem

                                                                                  -

                                                                                  Reverse a linked list from position m to n. Do it in one-pass.

                                                                                  -

                                                                                  **Note: **1 ≤ mn ≤ length of list.

                                                                                  -

                                                                                  Example:

                                                                                  -
                                                                                  Input: 1->2->3->4->5->NULL, m = 2, n = 4
                                                                                  -Output: 1->4->3->2->5->NULL
                                                                                  -
                                                                                  -

                                                                                  Solution

                                                                                  -
                                                                                  /**
                                                                                  - * Definition for singly-linked list.
                                                                                  - * function ListNode(val) {
                                                                                  - *     this.val = val;
                                                                                  - *     this.next = null;
                                                                                  - * }
                                                                                  - */
                                                                                  -/**
                                                                                  - * @param {ListNode} head
                                                                                  - * @param {number} m
                                                                                  - * @param {number} n
                                                                                  - * @return {ListNode}
                                                                                  - */
                                                                                  -var reverseBetween = function(head, m, n) {
                                                                                  -  var newHead = new ListNode(0);
                                                                                  -  var now = newHead;
                                                                                  -  var tmp = null;
                                                                                  -  var reverseLast = null;
                                                                                  -  var reverseHead = null;
                                                                                  -  var reverseNow = null;
                                                                                  -  var i = 0;
                                                                                  -
                                                                                  -  newHead.next = head;
                                                                                  -
                                                                                  -  while (now) {
                                                                                  -    tmp = now.next;
                                                                                  -
                                                                                  -    if (i === m - 1) {
                                                                                  -      reverseHead = now;
                                                                                  -    }
                                                                                  -
                                                                                  -    if (i === m) {
                                                                                  -      reverseLast = now;
                                                                                  -      reverseNow = now;
                                                                                  -    }
                                                                                  -
                                                                                  -    if (i > m && i <= n) {
                                                                                  -      now.next = reverseNow;
                                                                                  -      reverseNow = now;
                                                                                  -    }
                                                                                  -
                                                                                  -    if (i === n) {
                                                                                  -      reverseLast.next = tmp;
                                                                                  -      reverseHead.next = reverseNow;
                                                                                  -    }
                                                                                  -
                                                                                  -    now = tmp;
                                                                                  -    i++;
                                                                                  -  }
                                                                                  -
                                                                                  -  return newHead.next;
                                                                                  -};
                                                                                  -
                                                                                  -

                                                                                  Explain:

                                                                                  -

                                                                                  nope.

                                                                                  -

                                                                                  Complexity:

                                                                                  -
                                                                                    -
                                                                                  • Time complexity : O(n).
                                                                                  • -
                                                                                  • Space complexity : O(1).
                                                                                  • -
                                                                                  github
                                                                                  \ No newline at end of file diff --git a/docs/problem/reverse-linked-list.html b/docs/problem/reverse-linked-list.html deleted file mode 100644 index ba9f983..0000000 --- a/docs/problem/reverse-linked-list.html +++ /dev/null @@ -1,69 +0,0 @@ -Reverse Linked List - LeetCode javascript solutions

                                                                                  206. Reverse Linked List

                                                                                  Difficulty:
                                                                                  Related Topics:

                                                                                  Problem

                                                                                  -

                                                                                  Reverse a singly linked list.

                                                                                  -

                                                                                  Example:

                                                                                  -
                                                                                  Input: 1->2->3->4->5->NULL
                                                                                  -Output: 5->4->3->2->1->NULL
                                                                                  -
                                                                                  -

                                                                                  Follow up:

                                                                                  -

                                                                                  A linked list can be reversed either iteratively or recursively. Could you implement both?

                                                                                  -

                                                                                  Solution 1

                                                                                  -
                                                                                  /**
                                                                                  - * Definition for singly-linked list.
                                                                                  - * function ListNode(val) {
                                                                                  - *     this.val = val;
                                                                                  - *     this.next = null;
                                                                                  - * }
                                                                                  - */
                                                                                  -/**
                                                                                  - * @param {ListNode} head
                                                                                  - * @return {ListNode}
                                                                                  - */
                                                                                  -var reverseList = function(head) {
                                                                                  -  var newHead = null;
                                                                                  -  var tmp = null;
                                                                                  -  while (head) {
                                                                                  -    tmp = head.next;
                                                                                  -    head.next = newHead;
                                                                                  -    newHead = head;
                                                                                  -    head = tmp;
                                                                                  -  }
                                                                                  -  return newHead;
                                                                                  -};
                                                                                  -
                                                                                  -

                                                                                  Explain:

                                                                                  -

                                                                                  nope.

                                                                                  -

                                                                                  Complexity:

                                                                                  -
                                                                                    -
                                                                                  • Time complexity : O(n).
                                                                                  • -
                                                                                  • Space complexity : O(1).
                                                                                  • -
                                                                                  -

                                                                                  Solution 2

                                                                                  -
                                                                                  /**
                                                                                  - * Definition for singly-linked list.
                                                                                  - * function ListNode(val) {
                                                                                  - *     this.val = val;
                                                                                  - *     this.next = null;
                                                                                  - * }
                                                                                  - */
                                                                                  -/**
                                                                                  - * @param {ListNode} head
                                                                                  - * @return {ListNode}
                                                                                  - */
                                                                                  -var reverseList = function(head) {
                                                                                  -  return reverse(null, head);
                                                                                  -};
                                                                                  -
                                                                                  -var reverse = function (newHead, head) {
                                                                                  -  if (!head) return newHead;
                                                                                  -  var tmp = head.next;
                                                                                  -  head.next = newHead;
                                                                                  -  return reverse(head, tmp);
                                                                                  -};
                                                                                  -
                                                                                  -

                                                                                  Explain:

                                                                                  -

                                                                                  nope.

                                                                                  -

                                                                                  Complexity:

                                                                                  -
                                                                                    -
                                                                                  • Time complexity : O(n).
                                                                                  • -
                                                                                  • Space complexity : O(n).
                                                                                  • -
                                                                                  github
                                                                                  \ No newline at end of file diff --git a/docs/problem/reverse-nodes-in-k-group.html b/docs/problem/reverse-nodes-in-k-group.html deleted file mode 100644 index d8f7c1a..0000000 --- a/docs/problem/reverse-nodes-in-k-group.html +++ /dev/null @@ -1,59 +0,0 @@ -Reverse Nodes in k-Group - LeetCode javascript solutions

                                                                                  25. Reverse Nodes in k-Group

                                                                                  Difficulty:
                                                                                  Related Topics:
                                                                                  Similar Questions:

                                                                                  Problem

                                                                                  -

                                                                                  Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

                                                                                  -

                                                                                  k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

                                                                                  -

                                                                                  Example:

                                                                                  -

                                                                                  Given this linked list: 1->2->3->4->5

                                                                                  -

                                                                                  For k = 2, you should return: 2->1->4->3->5

                                                                                  -

                                                                                  For k = 3, you should return: 3->2->1->4->5

                                                                                  -

                                                                                  Note:

                                                                                  -
                                                                                    -
                                                                                  • Only constant extra memory is allowed.
                                                                                  • -
                                                                                  • You may not alter the values in the list's nodes, only nodes itself may be changed.
                                                                                  • -
                                                                                  -

                                                                                  Solution

                                                                                  -
                                                                                  /**
                                                                                  - * Definition for singly-linked list.
                                                                                  - * function ListNode(val) {
                                                                                  - *     this.val = val;
                                                                                  - *     this.next = null;
                                                                                  - * }
                                                                                  - */
                                                                                  -/**
                                                                                  - * @param {ListNode} head
                                                                                  - * @param {number} k
                                                                                  - * @return {ListNode}
                                                                                  - */
                                                                                  -var reverseKGroup = function(head, k) {
                                                                                  -  if (!head || k < 2) return head;
                                                                                  -
                                                                                  -  var count = 0;
                                                                                  -  var now = head;
                                                                                  -  var last = head;
                                                                                  -  var tmp = null;
                                                                                  -
                                                                                  -  while (now && count < k) {
                                                                                  -    now = now.next;
                                                                                  -    count++;
                                                                                  -  }
                                                                                  -
                                                                                  -  if (count === k) {
                                                                                  -    now = reverseKGroup(now, k);
                                                                                  -    while (count-- > 0) {
                                                                                  -      tmp = last.next;
                                                                                  -      last.next = now;
                                                                                  -      now = last;
                                                                                  -      last = tmp;
                                                                                  -    }
                                                                                  -    last = now;
                                                                                  -  }
                                                                                  -
                                                                                  -  return last;
                                                                                  -};
                                                                                  -
                                                                                  -

                                                                                  Explain:

                                                                                  -

                                                                                  nope.

                                                                                  -

                                                                                  Complexity:

                                                                                  -
                                                                                    -
                                                                                  • Time complexity : O(n).
                                                                                  • -
                                                                                  • Space complexity : O(1).
                                                                                  • -
                                                                                  github
                                                                                  \ No newline at end of file diff --git a/docs/problem/reverse-words-in-a-string-iii.html b/docs/problem/reverse-words-in-a-string-iii.html deleted file mode 100644 index 01ab1b6..0000000 --- a/docs/problem/reverse-words-in-a-string-iii.html +++ /dev/null @@ -1,33 +0,0 @@ -Reverse Words in a String III - LeetCode javascript solutions

                                                                                  557. Reverse Words in a String III

                                                                                  Difficulty:
                                                                                  Related Topics:
                                                                                  Similar Questions:

                                                                                  Problem

                                                                                  -

                                                                                  Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

                                                                                  -

                                                                                  Example 1:

                                                                                  -
                                                                                  Input: "Let's take LeetCode contest"
                                                                                  -Output: "s'teL ekat edoCteeL tsetnoc"
                                                                                  -
                                                                                  -

                                                                                  Note: -In the string, each word is separated by single space and there will not be any extra space in the string.

                                                                                  -

                                                                                  Solution

                                                                                  -
                                                                                  /**
                                                                                  - * @param {string} s
                                                                                  - * @return {string}
                                                                                  - */
                                                                                  -var reverseWords = function(s) {
                                                                                  -  return s.split(' ').map(reverse).join(' ');
                                                                                  -};
                                                                                  -
                                                                                  -var reverse = function (word) {
                                                                                  -  var len = word.length;
                                                                                  -  var res = '';
                                                                                  -  for (var i = 0; i < len; i++) {
                                                                                  -    res += word[len - i - 1];
                                                                                  -  }
                                                                                  -  return res;
                                                                                  -};
                                                                                  -
                                                                                  -

                                                                                  Explain:

                                                                                  -

                                                                                  nope.

                                                                                  -

                                                                                  Complexity:

                                                                                  -
                                                                                    -
                                                                                  • Time complexity :
                                                                                  • -
                                                                                  • Space complexity :
                                                                                  • -
                                                                                  github
                                                                                  \ No newline at end of file diff --git a/docs/problem/reverse-words-in-a-string.html b/docs/problem/reverse-words-in-a-string.html deleted file mode 100644 index 5e15c01..0000000 --- a/docs/problem/reverse-words-in-a-string.html +++ /dev/null @@ -1,29 +0,0 @@ -Reverse Words in a String - LeetCode javascript solutions

                                                                                  151. Reverse Words in a String

                                                                                  Difficulty:
                                                                                  Related Topics:

                                                                                  Problem

                                                                                  -

                                                                                  Given an input string, reverse the string word by word.

                                                                                  -

                                                                                  **Example: **

                                                                                  -
                                                                                  Input: "the sky is blue",
                                                                                  -Output: "blue is sky the".
                                                                                  -
                                                                                  -

                                                                                  Note:

                                                                                  -
                                                                                    -
                                                                                  • A word is defined as a sequence of non-space characters.
                                                                                  • -
                                                                                  • Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
                                                                                  • -
                                                                                  • You need to reduce multiple spaces between two words to a single space in the reversed string.
                                                                                  • -
                                                                                  -

                                                                                  **Follow up: **For C programmers, try to solve it in-place in O(1) space.

                                                                                  -

                                                                                  Solution

                                                                                  -
                                                                                  /**
                                                                                  - * @param {string} str
                                                                                  - * @returns {string}
                                                                                  - */
                                                                                  -var reverseWords = function(str) {
                                                                                  -  return str.split(' ').filter(s => s !== '').reverse().join(' ');
                                                                                  -};
                                                                                  -
                                                                                  -

                                                                                  Explain:

                                                                                  -

                                                                                  nope.

                                                                                  -

                                                                                  Complexity:

                                                                                  -
                                                                                    -
                                                                                  • Time complexity : O(n).
                                                                                  • -
                                                                                  • Space complexity : O(n).
                                                                                  • -
                                                                                  github
                                                                                  \ No newline at end of file diff --git a/docs/problem/roman-to-integer.html b/docs/problem/roman-to-integer.html deleted file mode 100644 index 067937e..0000000 --- a/docs/problem/roman-to-integer.html +++ /dev/null @@ -1,84 +0,0 @@ -Roman to Integer - LeetCode javascript solutions

                                                                                  13. Roman to Integer

                                                                                  Difficulty:
                                                                                  Related Topics:
                                                                                  Similar Questions:

                                                                                  Problem

                                                                                  -

                                                                                  Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

                                                                                  -
                                                                                  Symbol       Value
                                                                                  -I             1
                                                                                  -V             5
                                                                                  -X             10
                                                                                  -L             50
                                                                                  -C             100
                                                                                  -D             500
                                                                                  -M             1000
                                                                                  -
                                                                                  -

                                                                                  For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.

                                                                                  -

                                                                                  Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

                                                                                  -
                                                                                    -
                                                                                  • I can be placed before V (5) and X (10) to make 4 and 9.
                                                                                  • -
                                                                                  • X can be placed before L (50) and C (100) to make 40 and 90.
                                                                                  • -
                                                                                  • C can be placed before D (500) and M (1000) to make 400 and 900.
                                                                                  • -
                                                                                  -

                                                                                  Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.

                                                                                  -

                                                                                  Example 1:

                                                                                  -
                                                                                  Input: "III"
                                                                                  -Output: 3
                                                                                  -
                                                                                  -

                                                                                  Example 2:

                                                                                  -
                                                                                  Input: "IV"
                                                                                  -Output: 4
                                                                                  -
                                                                                  -

                                                                                  Example 3:

                                                                                  -
                                                                                  Input: "IX"
                                                                                  -Output: 9
                                                                                  -
                                                                                  -

                                                                                  Example 4:

                                                                                  -
                                                                                  Input: "LVIII"
                                                                                  -Output: 58
                                                                                  -Explanation: C = 100, L = 50, XXX = 30 and III = 3.
                                                                                  -
                                                                                  -

                                                                                  Example 5:

                                                                                  -
                                                                                  Input: "MCMXCIV"
                                                                                  -Output: 1994
                                                                                  -Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
                                                                                  -
                                                                                  -

                                                                                  Solution

                                                                                  -
                                                                                  /**
                                                                                  - * @param {string} s
                                                                                  - * @return {number}
                                                                                  - */
                                                                                  -var romanToInt = function(s) {
                                                                                  -  var map = {
                                                                                  -    I: 1,
                                                                                  -    IV: 4,
                                                                                  -    V: 5,
                                                                                  -    IX: 9,
                                                                                  -    X: 10,
                                                                                  -    XL: 40,
                                                                                  -    L: 50,
                                                                                  -    XC: 90,
                                                                                  -    C: 100,
                                                                                  -    CD: 400,
                                                                                  -    D: 500,
                                                                                  -    CM: 900,
                                                                                  -    M: 1000
                                                                                  -  };
                                                                                  -  var len = s.length;
                                                                                  -  var i = 0;
                                                                                  -  var res = 0;
                                                                                  -  while (i < len) {
                                                                                  -    if (map[s.substr(i, 2)]) {
                                                                                  -      res += map[s.substr(i, 2)];
                                                                                  -      i += 2;
                                                                                  -    } else {
                                                                                  -      res += map[s[i]];
                                                                                  -      i += 1;
                                                                                  -    }
                                                                                  -  }
                                                                                  -  return res;
                                                                                  -};
                                                                                  -
                                                                                  -

                                                                                  Explain:

                                                                                  -

                                                                                  nope.

                                                                                  -

                                                                                  Complexity:

                                                                                  -
                                                                                    -
                                                                                  • Time complexity : O(n).
                                                                                  • -
                                                                                  • Space complexity : O(1).
                                                                                  • -
                                                                                  github
                                                                                  \ No newline at end of file diff --git a/docs/problem/rotate-image.html b/docs/problem/rotate-image.html deleted file mode 100644 index 3df60a1..0000000 --- a/docs/problem/rotate-image.html +++ /dev/null @@ -1,78 +0,0 @@ -Rotate Image - LeetCode javascript solutions

                                                                                  48. Rotate Image

                                                                                  Difficulty:
                                                                                  Related Topics:
                                                                                  Similar Questions:

                                                                                    Problem

                                                                                    -

                                                                                    You are given an n x n 2D matrix representing an image.

                                                                                    -

                                                                                    Rotate the image by 90 degrees (clockwise).

                                                                                    -

                                                                                    Note:

                                                                                    -

                                                                                    You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

                                                                                    -

                                                                                    Example 1:

                                                                                    -
                                                                                    Given input matrix = 
                                                                                    -[
                                                                                    -  [1,2,3],
                                                                                    -  [4,5,6],
                                                                                    -  [7,8,9]
                                                                                    -],
                                                                                    -
                                                                                    -rotate the input matrix in-place such that it becomes:
                                                                                    -[
                                                                                    -  [7,4,1],
                                                                                    -  [8,5,2],
                                                                                    -  [9,6,3]
                                                                                    -]
                                                                                    -
                                                                                    -

                                                                                    Example 2:

                                                                                    -
                                                                                    Given input matrix =
                                                                                    -[
                                                                                    -  [ 5, 1, 9,11],
                                                                                    -  [ 2, 4, 8,10],
                                                                                    -  [13, 3, 6, 7],
                                                                                    -  [15,14,12,16]
                                                                                    -], 
                                                                                    -
                                                                                    -rotate the input matrix in-place such that it becomes:
                                                                                    -[
                                                                                    -  [15,13, 2, 5],
                                                                                    -  [14, 3, 4, 1],
                                                                                    -  [12, 6, 8, 9],
                                                                                    -  [16, 7,10,11]
                                                                                    -]
                                                                                    -
                                                                                    -

                                                                                    Solution

                                                                                    -
                                                                                    /**
                                                                                    - * @param {number[][]} matrix
                                                                                    - * @return {void} Do not return anything, modify matrix in-place instead.
                                                                                    - */
                                                                                    -var rotate = function(matrix) {
                                                                                    -  var n = matrix.length;
                                                                                    -  var n2 = Math.floor(n / 2);
                                                                                    -  // 1 2 3     7 8 9
                                                                                    -  // 4 5 6  => 4 5 6
                                                                                    -  // 7 8 9     1 2 3
                                                                                    -  for (var i = 0; i < n2; i++) {
                                                                                    -    for (var j = 0; j < n; j++) {
                                                                                    -      swap(matrix, i, j, n - 1 - i, j);
                                                                                    -    }
                                                                                    -  }
                                                                                    -  // 7 8 9     7 4 1
                                                                                    -  // 4 5 6  => 8 5 2
                                                                                    -  // 1 2 3     9 6 3
                                                                                    -  for (var i = 0; i < n; i++) {
                                                                                    -    for (var j = i + 1; j < n; j++) {
                                                                                    -      swap(matrix, i, j, j, i);
                                                                                    -    }
                                                                                    -  }
                                                                                    -};
                                                                                    -
                                                                                    -var swap = function (matrix, x1, y1, x2, y2) {
                                                                                    -  var tmp = matrix[x1][y1];
                                                                                    -  matrix[x1][y1] = matrix[x2][y2];
                                                                                    -  matrix[x2][y2] = tmp;
                                                                                    -};
                                                                                    -
                                                                                    -

                                                                                    Explain:

                                                                                    -

                                                                                    见注释

                                                                                    -

                                                                                    顺时针 90°:先上下倒置,再对角倒置

                                                                                    -

                                                                                    逆时针 90°:先左右倒置,再对角倒置

                                                                                    -

                                                                                    Complexity:

                                                                                    -
                                                                                      -
                                                                                    • Time complexity : O(n^2).
                                                                                    • -
                                                                                    • Space complexity : O(1).
                                                                                    • -
                                                                                    github
                                                                                    \ No newline at end of file diff --git a/docs/problem/rotate-list.html b/docs/problem/rotate-list.html deleted file mode 100644 index 7f2f253..0000000 --- a/docs/problem/rotate-list.html +++ /dev/null @@ -1,71 +0,0 @@ -Rotate List - LeetCode javascript solutions

                                                                                    61. Rotate List

                                                                                    Difficulty:

                                                                                    Problem

                                                                                    -

                                                                                    Given a linked list, rotate the list to the right by k places, where k is non-negative.

                                                                                    -

                                                                                    Example 1:

                                                                                    -
                                                                                    Input: 1->2->3->4->5->NULL, k = 2
                                                                                    -Output: 4->5->1->2->3->NULL
                                                                                    -Explanation:
                                                                                    -rotate 1 steps to the right: 5->1->2->3->4->NULL
                                                                                    -rotate 2 steps to the right: 4->5->1->2->3->NULL
                                                                                    -
                                                                                    -

                                                                                    Example 2:

                                                                                    -
                                                                                    Input: 0->1->2->NULL, k = 4
                                                                                    -Output: 2->0->1->NULL
                                                                                    -Explanation:
                                                                                    -rotate 1 steps to the right: 2->0->1->NULL
                                                                                    -rotate 2 steps to the right: 1->2->0->NULL
                                                                                    -rotate 3 steps to the right: 0->1->2->NULL
                                                                                    -rotate 4 steps to the right: 2->0->1->NULL
                                                                                    -
                                                                                    -

                                                                                    Solution

                                                                                    -
                                                                                    /**
                                                                                    - * Definition for singly-linked list.
                                                                                    - * function ListNode(val) {
                                                                                    - *     this.val = val;
                                                                                    - *     this.next = null;
                                                                                    - * }
                                                                                    - */
                                                                                    -/**
                                                                                    - * @param {ListNode} head
                                                                                    - * @param {number} k
                                                                                    - * @return {ListNode}
                                                                                    - */
                                                                                    -var rotateRight = function(head, k) {
                                                                                    -    var count = 1;
                                                                                    -    var last = head;
                                                                                    -    var now = head;
                                                                                    -
                                                                                    -    if (!head || !head.next) return head;
                                                                                    -
                                                                                    -    while (last.next) {
                                                                                    -        last = last.next;
                                                                                    -        count++;
                                                                                    -    }
                                                                                    -
                                                                                    -    k %= count;
                                                                                    -
                                                                                    -    if (k === 0) return head;
                                                                                    -
                                                                                    -    while (k < count - 1) {
                                                                                    -        now = now.next;
                                                                                    -        k++;
                                                                                    -    }
                                                                                    -
                                                                                    -    last.next = head;
                                                                                    -    head = now.next;
                                                                                    -    now.next = null;
                                                                                    -
                                                                                    -    return head;
                                                                                    -};
                                                                                    -
                                                                                    -

                                                                                    Explain:

                                                                                    -
                                                                                      -
                                                                                    1. 拿到长度 count 和最后一个 last
                                                                                    2. -
                                                                                    3. k %= count
                                                                                    4. -
                                                                                    5. 找到新的最后一个 newLast,last.next = head,head = newLast.next,newLast.next = null
                                                                                    6. -
                                                                                    7. return head
                                                                                    8. -
                                                                                    -

                                                                                    Complexity:

                                                                                    -
                                                                                      -
                                                                                    • Time complexity : O(n).
                                                                                    • -
                                                                                    • Space complexity : O(1).
                                                                                    • -
                                                                                    github
                                                                                    \ No newline at end of file diff --git a/docs/problem/same-tree.html b/docs/problem/same-tree.html deleted file mode 100644 index df2a205..0000000 --- a/docs/problem/same-tree.html +++ /dev/null @@ -1,99 +0,0 @@ -Same Tree - LeetCode javascript solutions

                                                                                    100. Same Tree

                                                                                    Difficulty:
                                                                                    Related Topics:
                                                                                    Similar Questions:

                                                                                      Problem

                                                                                      -

                                                                                      Given two binary trees, write a function to check if they are the same or not.

                                                                                      -

                                                                                      Two binary trees are considered the same if they are structurally identical and the nodes have the same value.

                                                                                      -

                                                                                      Example 1:

                                                                                      -
                                                                                      Input:     1         1
                                                                                      -          / \       / \
                                                                                      -         2   3     2   3
                                                                                      -
                                                                                      -        [1,2,3],   [1,2,3]
                                                                                      -
                                                                                      -Output: true
                                                                                      -
                                                                                      -

                                                                                      Example 2:

                                                                                      -
                                                                                      Input:     1         1
                                                                                      -          /           \
                                                                                      -         2             2
                                                                                      -
                                                                                      -        [1,2],     [1,null,2]
                                                                                      -
                                                                                      -Output: false
                                                                                      -
                                                                                      -

                                                                                      Example 3:

                                                                                      -
                                                                                      Input:     1         1
                                                                                      -          / \       / \
                                                                                      -         2   1     1   2
                                                                                      -
                                                                                      -        [1,2,1],   [1,1,2]
                                                                                      -
                                                                                      -Output: false
                                                                                      -
                                                                                      -

                                                                                      Solution 1

                                                                                      -
                                                                                      /**
                                                                                      - * Definition for a binary tree node.
                                                                                      - * function TreeNode(val) {
                                                                                      - *     this.val = val;
                                                                                      - *     this.left = this.right = null;
                                                                                      - * }
                                                                                      - */
                                                                                      -/**
                                                                                      - * @param {TreeNode} p
                                                                                      - * @param {TreeNode} q
                                                                                      - * @return {boolean}
                                                                                      - */
                                                                                      -var isSameTree = function(p, q) {
                                                                                      -  if ((!p && q) || (p && !q) || (p && q && p.val !== q.val)) return false;
                                                                                      -  if (p && q) return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
                                                                                      -  return true;
                                                                                      -};
                                                                                      -
                                                                                      -

                                                                                      Explain:

                                                                                      -

                                                                                      nope.

                                                                                      -

                                                                                      Complexity:

                                                                                      -
                                                                                        -
                                                                                      • Time complexity : O(n). n 为节点数。
                                                                                      • -
                                                                                      • Space complexity : O(1).
                                                                                      • -
                                                                                      -

                                                                                      Solution 2

                                                                                      -
                                                                                      /**
                                                                                      - * Definition for a binary tree node.
                                                                                      - * function TreeNode(val) {
                                                                                      - *     this.val = val;
                                                                                      - *     this.left = this.right = null;
                                                                                      - * }
                                                                                      - */
                                                                                      -/**
                                                                                      - * @param {TreeNode} p
                                                                                      - * @param {TreeNode} q
                                                                                      - * @return {boolean}
                                                                                      - */
                                                                                      -var isSameTree = function(p, q) {
                                                                                      -  var s1 = [p];
                                                                                      -  var s2 = [q];
                                                                                      -  var ll = null;
                                                                                      -  var rr = null;
                                                                                      -
                                                                                      -  while (s1.length && s2.length) {
                                                                                      -    ll = s1.pop();
                                                                                      -    rr = s2.pop();
                                                                                      -
                                                                                      -    if (!ll && !rr) continue;
                                                                                      -    if (!ll || !rr) return false;
                                                                                      -    if (ll.val !== rr.val) return false;
                                                                                      -
                                                                                      -    s1.push(ll.left);
                                                                                      -    s1.push(ll.right);
                                                                                      -    s2.push(rr.left);
                                                                                      -    s2.push(rr.right);
                                                                                      -  }
                                                                                      -
                                                                                      -  return true;
                                                                                      -};
                                                                                      -
                                                                                      -

                                                                                      Explain:

                                                                                      -

                                                                                      nope.

                                                                                      -

                                                                                      Complexity:

                                                                                      -
                                                                                        -
                                                                                      • Time complexity : O(n). n 为节点数。
                                                                                      • -
                                                                                      • Space complexity : O(n).
                                                                                      • -
                                                                                      github
                                                                                      \ No newline at end of file diff --git a/docs/problem/scramble-string.html b/docs/problem/scramble-string.html deleted file mode 100644 index eeaab8e..0000000 --- a/docs/problem/scramble-string.html +++ /dev/null @@ -1,92 +0,0 @@ -Scramble String - LeetCode javascript solutions

                                                                                      87. Scramble String

                                                                                      Difficulty:
                                                                                      Similar Questions:

                                                                                        Problem

                                                                                        -

                                                                                        Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively.

                                                                                        -

                                                                                        Below is one possible representation of s1 = "great":

                                                                                        -
                                                                                        great
                                                                                        -   /    \
                                                                                        -  gr    eat
                                                                                        - / \    /  \
                                                                                        -g   r  e   at
                                                                                        -           / \
                                                                                        -          a   t
                                                                                        -
                                                                                        -

                                                                                        To scramble the string, we may choose any non-leaf node and swap its two children.

                                                                                        -

                                                                                        For example, if we choose the node "gr" and swap its two children, it produces a scrambled string "rgeat".

                                                                                        -
                                                                                        rgeat
                                                                                        -   /    \
                                                                                        -  rg    eat
                                                                                        - / \    /  \
                                                                                        -r   g  e   at
                                                                                        -           / \
                                                                                        -          a   t
                                                                                        -
                                                                                        -

                                                                                        We say that "rgeat" is a scrambled string of "great".

                                                                                        -

                                                                                        Similarly, if we continue to swap the children of nodes "eat" and "at", it produces a scrambled string "rgtae".

                                                                                        -
                                                                                        rgtae
                                                                                        -   /    \
                                                                                        -  rg    tae
                                                                                        - / \    /  \
                                                                                        -r   g  ta  e
                                                                                        -       / \
                                                                                        -      t   a
                                                                                        -
                                                                                        -

                                                                                        We say that "rgtae" is a scrambled string of "great".

                                                                                        -

                                                                                        Given two strings s1 and s2 of the same length, determine if s2 is a scrambled string of s1.

                                                                                        -

                                                                                        Example 1:

                                                                                        -
                                                                                        Input: s1 = "great", s2 = "rgeat"
                                                                                        -Output: true
                                                                                        -
                                                                                        -

                                                                                        Example 2:

                                                                                        -
                                                                                        Input: s1 = "abcde", s2 = "caebd"
                                                                                        -Output: false
                                                                                        -
                                                                                        -

                                                                                        Solution

                                                                                        -
                                                                                        /**
                                                                                        - * @param {string} s1
                                                                                        - * @param {string} s2
                                                                                        - * @return {boolean}
                                                                                        - */
                                                                                        -var isScramble = function(s1, s2) {
                                                                                        -  return helper({}, s1, s2);
                                                                                        -};
                                                                                        -
                                                                                        -var helper = function (dp, s1, s2) {
                                                                                        -  var map = {};
                                                                                        -
                                                                                        -  if (dp[s1 + s2] !== undefined) return dp[s1 + s2];
                                                                                        -  if (s1 === s2) return true;
                                                                                        -
                                                                                        -  for (var j = 0; j < s1.length; j++) {
                                                                                        -    if (map[s1[j]] === undefined) map[s1[j]] = 0;
                                                                                        -    if (map[s2[j]] === undefined) map[s2[j]] = 0;
                                                                                        -    map[s1[j]]++;
                                                                                        -    map[s2[j]]--;
                                                                                        -  }
                                                                                        -
                                                                                        -  for (var key in map) {
                                                                                        -    if (map[key] !== 0) {
                                                                                        -      dp[s1 + s2] = false;
                                                                                        -      return false;
                                                                                        -    }
                                                                                        -  }
                                                                                        -
                                                                                        -  for (var i = 1; i < s1.length; i++) {
                                                                                        -    if ((helper(dp, s1.substr(0, i), s2.substr(0, i))
                                                                                        -         && helper(dp, s1.substr(i), s2.substr(i))) ||
                                                                                        -        (helper(dp, s1.substr(0, i), s2.substr(s2.length - i))
                                                                                        -         && helper(dp, s1.substr(i), s2.substr(0, s2.length - i)))) {
                                                                                        -      dp[s1 + s2] = true;
                                                                                        -      return true;
                                                                                        -    }
                                                                                        -  }
                                                                                        -
                                                                                        -  dp[s1 + s2] = false;
                                                                                        -  return false;
                                                                                        -};
                                                                                        -
                                                                                        -

                                                                                        Explain:

                                                                                        -

                                                                                        nope.

                                                                                        -

                                                                                        Complexity:

                                                                                        -
                                                                                          -
                                                                                        • Time complexity : O(n^4).
                                                                                        • -
                                                                                        • Space complexity : O(n^4).
                                                                                        • -
                                                                                        github
                                                                                        \ No newline at end of file diff --git a/docs/problem/search-a-2d-matrix-ii.html b/docs/problem/search-a-2d-matrix-ii.html deleted file mode 100644 index aea7d52..0000000 --- a/docs/problem/search-a-2d-matrix-ii.html +++ /dev/null @@ -1,55 +0,0 @@ -Search a 2D Matrix II - LeetCode javascript solutions

                                                                                        240. Search a 2D Matrix II

                                                                                        Difficulty:
                                                                                        Similar Questions:

                                                                                        Problem

                                                                                        -

                                                                                        Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

                                                                                        -
                                                                                          -
                                                                                        • Integers in each row are sorted in ascending from left to right.
                                                                                        • -
                                                                                        • Integers in each column are sorted in ascending from top to bottom.
                                                                                        • -
                                                                                        -

                                                                                        Consider the following matrix:

                                                                                        -
                                                                                        [
                                                                                        -  [1,   4,  7, 11, 15],
                                                                                        -  [2,   5,  8, 12, 19],
                                                                                        -  [3,   6,  9, 16, 22],
                                                                                        -  [10, 13, 14, 17, 24],
                                                                                        -  [18, 21, 23, 26, 30]
                                                                                        -]
                                                                                        -
                                                                                        -

                                                                                        Example 1:

                                                                                        -
                                                                                        Input: matrix, target = 5
                                                                                        -Output: true
                                                                                        -
                                                                                        -

                                                                                        Example 2:

                                                                                        -
                                                                                        Input: matrix, target = 20
                                                                                        -Output: false
                                                                                        -
                                                                                        -

                                                                                        Solution

                                                                                        -
                                                                                        /**
                                                                                        - * @param {number[][]} matrix
                                                                                        - * @param {number} target
                                                                                        - * @return {boolean}
                                                                                        - */
                                                                                        -var searchMatrix = function(matrix, target) {
                                                                                        -  var n = matrix.length;
                                                                                        -  var m = (matrix[0] || []).length;
                                                                                        -  var x = m - 1;
                                                                                        -  var y = 0;
                                                                                        -  var tmp = 0;
                                                                                        -  while (x >= 0 && y < n) {
                                                                                        -    tmp = matrix[y][x];
                                                                                        -    if (target === tmp) {
                                                                                        -      return true;
                                                                                        -    } else if (target > tmp) {
                                                                                        -      y++;
                                                                                        -    } else {
                                                                                        -      x--;
                                                                                        -    }
                                                                                        -  }
                                                                                        -  return false;
                                                                                        -};
                                                                                        -
                                                                                        -

                                                                                        Explain:

                                                                                        -

                                                                                        nope.

                                                                                        -

                                                                                        Complexity:

                                                                                        -
                                                                                          -
                                                                                        • Time complexity : O(n + m). nm 列。
                                                                                        • -
                                                                                        • Space complexity : O(1).
                                                                                        • -
                                                                                        github
                                                                                        \ No newline at end of file diff --git a/docs/problem/search-a-2d-matrix.html b/docs/problem/search-a-2d-matrix.html deleted file mode 100644 index f040dc4..0000000 --- a/docs/problem/search-a-2d-matrix.html +++ /dev/null @@ -1,104 +0,0 @@ -Search a 2D Matrix - LeetCode javascript solutions

                                                                                        74. Search a 2D Matrix

                                                                                        Difficulty:
                                                                                        Related Topics:
                                                                                        Similar Questions:

                                                                                        Problem

                                                                                        -

                                                                                        Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

                                                                                        -
                                                                                          -
                                                                                        • Integers in each row are sorted from left to right.
                                                                                        • -
                                                                                        • The first integer of each row is greater than the last integer of the previous row.
                                                                                        • -
                                                                                        -

                                                                                        Example 1:

                                                                                        -
                                                                                        Input:
                                                                                        -matrix = [
                                                                                        -  [1,   3,  5,  7],
                                                                                        -  [10, 11, 16, 20],
                                                                                        -  [23, 30, 34, 50]
                                                                                        -]
                                                                                        -target = 3
                                                                                        -Output: true
                                                                                        -
                                                                                        -

                                                                                        Example 2:

                                                                                        -
                                                                                        Input:
                                                                                        -matrix = [
                                                                                        -  [1,   3,  5,  7],
                                                                                        -  [10, 11, 16, 20],
                                                                                        -  [23, 30, 34, 50]
                                                                                        -]
                                                                                        -target = 13
                                                                                        -Output: false
                                                                                        -
                                                                                        -

                                                                                        Solution 1

                                                                                        -
                                                                                        /**
                                                                                        - * @param {number[][]} matrix
                                                                                        - * @param {number} target
                                                                                        - * @return {boolean}
                                                                                        - */
                                                                                        -var searchMatrix = function(matrix, target) {
                                                                                        -  var row = searchRow(matrix, target, 0, matrix.length - 1);
                                                                                        -  return row === -1 ? false : searchArray(matrix[row], target, 0, matrix[row].length - 1);
                                                                                        -};
                                                                                        -
                                                                                        -var searchRow = function (matrix, target, top, bottom) {
                                                                                        -  if (top > bottom) return -1;
                                                                                        -  var mid = top + Math.floor((bottom - top) / 2);
                                                                                        -  var len = matrix[mid].length;
                                                                                        -  if (len === 0) return -1;
                                                                                        -  if (matrix[mid][0] <= target && target <= matrix[mid][len - 1]) {
                                                                                        -    return mid;
                                                                                        -  } else if (target < matrix[mid][0]) {
                                                                                        -    return searchRow(matrix, target, top, mid - 1);
                                                                                        -  } else {
                                                                                        -    return searchRow(matrix, target, mid + 1, bottom);
                                                                                        -  }
                                                                                        -};
                                                                                        -
                                                                                        -var searchArray = function (arr, target, left, right) {
                                                                                        -  if (left > right) return false;
                                                                                        -  var mid = left + Math.floor((right - left) / 2);
                                                                                        -  if (arr[mid] === target) {
                                                                                        -    return true;
                                                                                        -  } else if (arr[mid] > target) {
                                                                                        -    return searchArray(arr, target, left, mid - 1);
                                                                                        -  } else {
                                                                                        -    return searchArray(arr, target, mid + 1, right);
                                                                                        -  }
                                                                                        -};
                                                                                        -
                                                                                        -

                                                                                        Explain:

                                                                                        -

                                                                                        先找行,再找列。

                                                                                        -

                                                                                        Complexity:

                                                                                        -
                                                                                          -
                                                                                        • Time complexity : O(log(m) + log(n)). nm 列。
                                                                                        • -
                                                                                        • Space complexity : O(1).
                                                                                        • -
                                                                                        -

                                                                                        Solution 2

                                                                                        -
                                                                                        /**
                                                                                        - * @param {number[][]} matrix
                                                                                        - * @param {number} target
                                                                                        - * @return {boolean}
                                                                                        - */
                                                                                        -var searchMatrix = function(matrix, target) {
                                                                                        -  var n = matrix.length;
                                                                                        -  var m = (matrix[0] || []).length;
                                                                                        -  var ll = 0;
                                                                                        -  var rr = (n * m) - 1;
                                                                                        -  var mid = 0;
                                                                                        -  var tmp = 0;
                                                                                        -  while (ll <= rr) {
                                                                                        -    mid = ll + Math.floor((rr - ll) / 2);
                                                                                        -    tmp = matrix[Math.floor(mid / m)][mid % m];
                                                                                        -    if (tmp === target) {
                                                                                        -      return true;
                                                                                        -    } else if (tmp > target) {
                                                                                        -      rr = mid - 1;
                                                                                        -    } else {
                                                                                        -      ll = mid + 1;
                                                                                        -    }
                                                                                        -  }
                                                                                        -  return false;
                                                                                        -};
                                                                                        -
                                                                                        -

                                                                                        Explain:

                                                                                        -

                                                                                        直接找位置。

                                                                                        -

                                                                                        Complexity:

                                                                                        -
                                                                                          -
                                                                                        • Time complexity : O(log(m*n)). nm 列。
                                                                                        • -
                                                                                        • Space complexity : O(1).
                                                                                        • -
                                                                                        github
                                                                                        \ No newline at end of file diff --git a/docs/problem/search-for-a-range.html b/docs/problem/search-for-a-range.html deleted file mode 100644 index 39f810e..0000000 --- a/docs/problem/search-for-a-range.html +++ /dev/null @@ -1,59 +0,0 @@ -Search for a Range - LeetCode javascript solutions

                                                                                        34. Search for a Range

                                                                                        Difficulty:
                                                                                        Related Topics:
                                                                                        Similar Questions:

                                                                                        Problem

                                                                                        -

                                                                                        Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.

                                                                                        -

                                                                                        Your algorithm's runtime complexity must be in the order of O(log n).

                                                                                        -

                                                                                        If the target is not found in the array, return [-1, -1].

                                                                                        -

                                                                                        Example 1:

                                                                                        -
                                                                                        Input: nums = [5,7,7,8,8,10], target = 8
                                                                                        -Output: [3,4]
                                                                                        -
                                                                                        -

                                                                                        Example 2:

                                                                                        -
                                                                                        Input: nums = [5,7,7,8,8,10], target = 6
                                                                                        -Output: [-1,-1]
                                                                                        -
                                                                                        -

                                                                                        Solution

                                                                                        -
                                                                                        /**
                                                                                        - * @param {number[]} nums
                                                                                        - * @param {number} target
                                                                                        - * @return {number[]}
                                                                                        - */
                                                                                        -var searchRange = function(nums, target) {
                                                                                        -  var res = [-1, -1];
                                                                                        -  var left = find(nums, target, true);
                                                                                        -  var right = find(nums, target, false);
                                                                                        -  if (!nums.length) return res;
                                                                                        -  if (left > right) return res;
                                                                                        -  return [left, right];
                                                                                        -};
                                                                                        -
                                                                                        -var find = function (nums, target, findLeft) {
                                                                                        -  var left = 0;
                                                                                        -  var right = nums.length - 1;
                                                                                        -  var mid = 0;
                                                                                        -
                                                                                        -  while (left <= right) {
                                                                                        -    mid = Math.floor((left + right) / 2);
                                                                                        -    if (nums[mid] > target || (findLeft && nums[mid] === target)) {
                                                                                        -      right = mid - 1;
                                                                                        -    } else {
                                                                                        -      left = mid + 1;
                                                                                        -    }
                                                                                        -  }
                                                                                        -
                                                                                        -  return findLeft ? left : right;
                                                                                        -};
                                                                                        -
                                                                                        -

                                                                                        Explain:

                                                                                        -

                                                                                        二分查找:

                                                                                        -

                                                                                        分两次,第一次找左边位置,第二次找右边位置

                                                                                        -
                                                                                          -
                                                                                        1. 中间值小于目标,继续去右半部分找
                                                                                        2. -
                                                                                        3. 中间值大于目标,继续去左半部分找
                                                                                        4. -
                                                                                        5. 中间值等于目标,找左位置时,继续去左半部分找; - 找右位置时,继续去右半部分找。
                                                                                        6. -
                                                                                        7. 最终不能找到的话,左位置是会大于右位置的,否则代表找到
                                                                                        8. -
                                                                                        -

                                                                                        Complexity:

                                                                                        -
                                                                                          -
                                                                                        • Time complexity : O(log(n)).
                                                                                        • -
                                                                                        • Space complexity : O(1).
                                                                                        • -
                                                                                        github
                                                                                        \ No newline at end of file diff --git a/docs/problem/search-in-rotated-sorted-array-ii.html b/docs/problem/search-in-rotated-sorted-array-ii.html deleted file mode 100644 index f82a7c3..0000000 --- a/docs/problem/search-in-rotated-sorted-array-ii.html +++ /dev/null @@ -1,61 +0,0 @@ -Search in Rotated Sorted Array II - LeetCode javascript solutions

                                                                                        81. Search in Rotated Sorted Array II

                                                                                        Difficulty:
                                                                                        Related Topics:

                                                                                        Problem

                                                                                        -

                                                                                        Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

                                                                                        -

                                                                                        (i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]).

                                                                                        -

                                                                                        You are given a target value to search. If found in the array return true, otherwise return false.

                                                                                        -

                                                                                        Example 1:

                                                                                        -
                                                                                        Input: nums = [2,5,6,0,0,1,2], target = 0
                                                                                        -Output: true
                                                                                        -
                                                                                        -

                                                                                        Example 2:

                                                                                        -
                                                                                        Input: nums = [2,5,6,0,0,1,2], target = 3
                                                                                        -Output: false
                                                                                        -
                                                                                        -

                                                                                        Follow up:

                                                                                        -
                                                                                          -
                                                                                        • This is a follow up problem to Search in Rotated Sorted Array, where nums may contain duplicates.
                                                                                        • -
                                                                                        • Would this affect the run-time complexity? How and why?
                                                                                        • -
                                                                                        -

                                                                                        Solution

                                                                                        -
                                                                                        /**
                                                                                        - * @param {number[]} nums
                                                                                        - * @param {number} target
                                                                                        - * @return {boolean}
                                                                                        - */
                                                                                        -var search = function(nums, target) {
                                                                                        -  var left = 0;
                                                                                        -  var right = nums.length - 1;
                                                                                        -  var mid = 0;
                                                                                        -  while (left <= right) {
                                                                                        -    mid = Math.floor((left + right) / 2);
                                                                                        -    if (nums[mid] === target) return true;
                                                                                        -    if (nums[mid] > nums[left]) {
                                                                                        -      if (nums[left] <= target && target < nums[mid]) {
                                                                                        -        right = mid - 1;
                                                                                        -      } else {
                                                                                        -        left = mid + 1;
                                                                                        -      }
                                                                                        -    } else if (nums[mid] < nums[left]) {
                                                                                        -      if (nums[mid] < target && target <= nums[right]) {
                                                                                        -        left = mid + 1;
                                                                                        -      } else {
                                                                                        -        right = mid - 1;
                                                                                        -      }
                                                                                        -    } else {
                                                                                        -      left++;
                                                                                        -    }
                                                                                        -  }
                                                                                        -  return false;
                                                                                        -};
                                                                                        -
                                                                                        -

                                                                                        Explain:

                                                                                        -

                                                                                        see Search in Rotated Sorted Array.

                                                                                        -
                                                                                          -
                                                                                        1. 判断哪边是有序的
                                                                                        2. -
                                                                                        3. 判断 target 在有序的那边还是无序的那边
                                                                                        4. -
                                                                                        -

                                                                                        注意重复数字的情况下,只能一个个移动,因为没法判断在哪边。这样算法最坏的情况就是 O(n) 了。

                                                                                        -

                                                                                        Complexity:

                                                                                        -
                                                                                          -
                                                                                        • Time complexity : O(n).
                                                                                        • -
                                                                                        • Space complexity : O(n).
                                                                                        • -
                                                                                        github
                                                                                        \ No newline at end of file diff --git a/docs/problem/search-in-rotated-sorted-array.html b/docs/problem/search-in-rotated-sorted-array.html deleted file mode 100644 index 8c6cbbe..0000000 --- a/docs/problem/search-in-rotated-sorted-array.html +++ /dev/null @@ -1,60 +0,0 @@ -Search in Rotated Sorted Array - LeetCode javascript solutions

                                                                                        33. Search in Rotated Sorted Array

                                                                                        Difficulty:
                                                                                        Related Topics:

                                                                                        Problem

                                                                                        -

                                                                                        Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

                                                                                        -

                                                                                        (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).

                                                                                        -

                                                                                        You are given a target value to search. If found in the array return its index, otherwise return -1.

                                                                                        -

                                                                                        You may assume no duplicate exists in the array.

                                                                                        -

                                                                                        Your algorithm's runtime complexity must be in the order of O(log n).

                                                                                        -

                                                                                        Example 1:

                                                                                        -
                                                                                        Input: nums = [4,5,6,7,0,1,2], target = 0
                                                                                        -Output: 4
                                                                                        -
                                                                                        -

                                                                                        Example 2:

                                                                                        -
                                                                                        Input: nums = [4,5,6,7,0,1,2], target = 3
                                                                                        -Output: -1
                                                                                        -
                                                                                        -

                                                                                        Solution

                                                                                        -
                                                                                        /**
                                                                                        - * @param {number[]} nums
                                                                                        - * @param {number} target
                                                                                        - * @return {number}
                                                                                        - */
                                                                                        -var search = function(nums, target) {
                                                                                        -  var len = nums.length
                                                                                        -  var left = 0;
                                                                                        -  var right = len - 1;
                                                                                        -  var mid = 0;
                                                                                        -
                                                                                        -  while (left <= right) {
                                                                                        -    mid = left + Math.floor((right - left) / 2);
                                                                                        -    if (nums[mid] === target) return mid;
                                                                                        -    if (nums[mid] > nums[right]) {
                                                                                        -      if (nums[left] <= target && target < nums[mid]) {
                                                                                        -        right = mid - 1;
                                                                                        -      } else {
                                                                                        -        left = mid + 1;
                                                                                        -      }
                                                                                        -    } else {
                                                                                        -      if (nums[mid] < target && target <= nums[right]) {
                                                                                        -        left = mid + 1;
                                                                                        -      } else {
                                                                                        -        right = mid - 1;
                                                                                        -      }
                                                                                        -    }
                                                                                        -  }
                                                                                        -
                                                                                        -  return -1;
                                                                                        -};
                                                                                        -
                                                                                        -

                                                                                        Explain:

                                                                                        -

                                                                                        题意:

                                                                                        -

                                                                                        输入数组是已排序的数组在某个点上翻转了一下,比如 01234 在 2 上翻转,变成 23401,在输入数组里找是否存在某个数

                                                                                        -

                                                                                        解:二分查找

                                                                                        -

                                                                                        (规律:输入数组中取任意一段,从中间分开,必定有一边是已排序的)

                                                                                        -

                                                                                        先通过中间值与末尾值比大小,判断已排序的是左边还是右边,当然也可以通过中间值跟起点值比大小来判断

                                                                                        -

                                                                                        (目标值等于中间值的话,就结束了,其实也包括二分查找的极限情况,区间里只剩一个值)

                                                                                        -

                                                                                        然后判断目标值是否在已排序的那边,在的话在这边继续查找,否则去另一半继续查找

                                                                                        -

                                                                                        Complexity:

                                                                                        -
                                                                                          -
                                                                                        • Time complexity : O(log(n)).
                                                                                        • -
                                                                                        • Space complexity : O(1).
                                                                                        • -
                                                                                        github
                                                                                        \ No newline at end of file diff --git a/docs/problem/search-insert-position.html b/docs/problem/search-insert-position.html deleted file mode 100644 index 3f6229c..0000000 --- a/docs/problem/search-insert-position.html +++ /dev/null @@ -1,54 +0,0 @@ -Search Insert Position - LeetCode javascript solutions

                                                                                        35. Search Insert Position

                                                                                        Difficulty:
                                                                                        Related Topics:
                                                                                        Similar Questions:

                                                                                        Problem

                                                                                        -

                                                                                        Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

                                                                                        -

                                                                                        You may assume no duplicates in the array.

                                                                                        -

                                                                                        Example 1:

                                                                                        -
                                                                                        Input: [1,3,5,6], 5
                                                                                        -Output: 2
                                                                                        -
                                                                                        -

                                                                                        Example 2:

                                                                                        -
                                                                                        Input: [1,3,5,6], 2
                                                                                        -Output: 1
                                                                                        -
                                                                                        -

                                                                                        Example 3:

                                                                                        -
                                                                                        Input: [1,3,5,6], 7
                                                                                        -Output: 4
                                                                                        -
                                                                                        -

                                                                                        Example 4:

                                                                                        -
                                                                                        Input: [1,3,5,6], 0
                                                                                        -Output: 0
                                                                                        -
                                                                                        -

                                                                                        Solution

                                                                                        -
                                                                                        /**
                                                                                        - * @param {number[]} nums
                                                                                        - * @param {number} target
                                                                                        - * @return {number}
                                                                                        - */
                                                                                        -var searchInsert = function(nums, target) {
                                                                                        -  var len = nums.length;
                                                                                        -  var left = 0;
                                                                                        -  var right = len - 1;
                                                                                        -  var mid = 0;
                                                                                        -
                                                                                        -  if (!len) return 0;
                                                                                        -
                                                                                        -  while (left <= right) {
                                                                                        -    mid = Math.floor((left + right) / 2);
                                                                                        -    if (nums[mid] > target) {
                                                                                        -      right = mid - 1;
                                                                                        -    } else if (nums[mid] < target) {
                                                                                        -      left = mid + 1;
                                                                                        -    } else {
                                                                                        -      return mid;
                                                                                        -    }
                                                                                        -  }
                                                                                        -
                                                                                        -  return (nums[mid] > target) ? mid : (mid + 1);
                                                                                        -};
                                                                                        -
                                                                                        -

                                                                                        Explain:

                                                                                        -

                                                                                        nope.

                                                                                        -

                                                                                        Complexity:

                                                                                        -
                                                                                          -
                                                                                        • Time complexity : O(log(n)).
                                                                                        • -
                                                                                        • Space complexity : O(1).
                                                                                        • -
                                                                                        github
                                                                                        \ No newline at end of file diff --git a/docs/problem/second-highest-salary.html b/docs/problem/second-highest-salary.html deleted file mode 100644 index 5804985..0000000 --- a/docs/problem/second-highest-salary.html +++ /dev/null @@ -1,28 +0,0 @@ -Second Highest Salary - LeetCode javascript solutions

                                                                                        176. Second Highest Salary

                                                                                        Difficulty:
                                                                                        Related Topics:
                                                                                          Similar Questions:

                                                                                            Problem

                                                                                            -

                                                                                            Write a SQL query to get the second highest salary from the Employee table.

                                                                                            -
                                                                                            +----+--------+
                                                                                            -| Id | Salary |
                                                                                            -+----+--------+
                                                                                            -| 1  | 100    |
                                                                                            -| 2  | 200    |
                                                                                            -| 3  | 300    |
                                                                                            -+----+--------+
                                                                                            -
                                                                                            -

                                                                                            For example, given the above Employee table, the query should return 200 as the second highest salary. If there is no second highest salary, then the query should return null.

                                                                                            -
                                                                                            +---------------------+
                                                                                            -| SecondHighestSalary |
                                                                                            -+---------------------+
                                                                                            -| 200                 |
                                                                                            -+---------------------+
                                                                                            -
                                                                                            -

                                                                                            Solution

                                                                                            -
                                                                                            # Write your MySQL query statement below
                                                                                            -select max(Salary) as SecondHighestSalary from Employee where Salary < (select max(Salary) from Employee)
                                                                                            -
                                                                                            -

                                                                                            Explain:

                                                                                            -

                                                                                            nope.

                                                                                            -

                                                                                            Complexity:

                                                                                            -
                                                                                              -
                                                                                            • Time complexity :
                                                                                            • -
                                                                                            • Space complexity :
                                                                                            • -
                                                                                            github
                                                                                            \ No newline at end of file diff --git a/docs/problem/set-matrix-zeroes.html b/docs/problem/set-matrix-zeroes.html deleted file mode 100644 index 7dc2f0a..0000000 --- a/docs/problem/set-matrix-zeroes.html +++ /dev/null @@ -1,89 +0,0 @@ -Set Matrix Zeroes - LeetCode javascript solutions

                                                                                            73. Set Matrix Zeroes

                                                                                            Difficulty:
                                                                                            Related Topics:
                                                                                            Similar Questions:

                                                                                            Problem

                                                                                            -

                                                                                            Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.

                                                                                            -

                                                                                            Example 1:

                                                                                            -
                                                                                            Input: 
                                                                                            -[
                                                                                            -  [1,1,1],
                                                                                            -  [1,0,1],
                                                                                            -  [1,1,1]
                                                                                            -]
                                                                                            -Output: 
                                                                                            -[
                                                                                            -  [1,0,1],
                                                                                            -  [0,0,0],
                                                                                            -  [1,0,1]
                                                                                            -]
                                                                                            -
                                                                                            -

                                                                                            Example 2:

                                                                                            -
                                                                                            Input: 
                                                                                            -[
                                                                                            -  [0,1,2,0],
                                                                                            -  [3,4,5,2],
                                                                                            -  [1,3,1,5]
                                                                                            -]
                                                                                            -Output: 
                                                                                            -[
                                                                                            -  [0,0,0,0],
                                                                                            -  [0,4,5,0],
                                                                                            -  [0,3,1,0]
                                                                                            -]
                                                                                            -
                                                                                            -

                                                                                            Follow up:

                                                                                            -
                                                                                              -
                                                                                            • A straight forward solution using O(mn) space is probably a bad idea.
                                                                                            • -
                                                                                            • A simple improvement uses O(m + n) space, but still not the best solution.
                                                                                            • -
                                                                                            • Could you devise a constant space solution?
                                                                                            • -
                                                                                            -

                                                                                            Solution

                                                                                            -
                                                                                            /**
                                                                                            - * @param {number[][]} matrix
                                                                                            - * @return {void} Do not return anything, modify matrix in-place instead.
                                                                                            - */
                                                                                            -var setZeroes = function(matrix) {
                                                                                            -  var m = matrix.length;
                                                                                            -  var n = (matrix[0] || []).length;
                                                                                            -  for (var i = 0; i < m; i++) {
                                                                                            -    for (var j = 0; j < n; j++) {
                                                                                            -      if (matrix[i][j] === 0) {
                                                                                            -        left(i, j, m, n, matrix);
                                                                                            -        right(i, j, m, n, matrix);
                                                                                            -        up(i, j, m, n, matrix);
                                                                                            -        down(i, j, m, n, matrix);
                                                                                            -      } else if (matrix[i][j] === '#') {
                                                                                            -        matrix[i][j] = 0;
                                                                                            -      }
                                                                                            -    }
                                                                                            -  }
                                                                                            -};
                                                                                            -
                                                                                            -var left = function (i, j, m, n, matrix) {
                                                                                            -  for (var k = j - 1; k >= 0; k--) {
                                                                                            -    matrix[i][k] = 0;
                                                                                            -  }
                                                                                            -};
                                                                                            -
                                                                                            -var right = function (i, j, m, n, matrix) {
                                                                                            -  for (var k = j + 1; k < n; k++) {
                                                                                            -    matrix[i][k] = matrix[i][k] === 0 ? 0 : '#';
                                                                                            -  }
                                                                                            -};
                                                                                            -
                                                                                            -var up = function (i, j, m, n, matrix) {
                                                                                            -  for (var k = i - 1; k >= 0; k--) {
                                                                                            -    matrix[k][j] = 0;
                                                                                            -  }
                                                                                            -};
                                                                                            -
                                                                                            -var down = function (i, j, m, n, matrix) {
                                                                                            -  for (var k = i + 1; k < m; k++) {
                                                                                            -    matrix[k][j] = matrix[k][j] === 0 ? 0 : '#';
                                                                                            -  }
                                                                                            -};
                                                                                            -
                                                                                            -

                                                                                            Explain:

                                                                                            -

                                                                                            把没遍历的 1 设置为 0 会影响之后的判断,先设置为 #,再改回来。

                                                                                            -

                                                                                            Complexity:

                                                                                            -
                                                                                              -
                                                                                            • Time complexity : O(m*n).
                                                                                            • -
                                                                                            • Space complexity : O(1).
                                                                                            • -
                                                                                            github
                                                                                            \ No newline at end of file diff --git a/docs/problem/shortest-completing-word.html b/docs/problem/shortest-completing-word.html deleted file mode 100644 index b20ff1e..0000000 --- a/docs/problem/shortest-completing-word.html +++ /dev/null @@ -1,77 +0,0 @@ -Shortest Completing Word - LeetCode javascript solutions

                                                                                            749. Shortest Completing Word

                                                                                            Difficulty:
                                                                                            Related Topics:
                                                                                            Similar Questions:

                                                                                              Problem

                                                                                              -

                                                                                              Find the minimum length word from a given dictionary words, which has all the letters from the string licensePlate. Such a word is said to complete the given string licensePlate

                                                                                              -

                                                                                              Here, for letters we ignore case. For example, "P" on the licensePlate still matches "p" on the word.

                                                                                              -

                                                                                              It is guaranteed an answer exists. If there are multiple answers, return the one that occurs first in the array.

                                                                                              -

                                                                                              The license plate might have the same letter occurring multiple times. For example, given a licensePlate of "PP", the word "pair" does not complete the licensePlate, but the word "supper" does.

                                                                                              -

                                                                                              Example 1:

                                                                                              -
                                                                                              Input: licensePlate = "1s3 PSt", words = ["step", "steps", "stripe", "stepple"]
                                                                                              -Output: "steps"
                                                                                              -Explanation: The smallest length word that contains the letters "S", "P", "S", and "T".
                                                                                              -Note that the answer is not "step", because the letter "s" must occur in the word twice.
                                                                                              -Also note that we ignored case for the purposes of comparing whether a letter exists in the word.
                                                                                              -
                                                                                              -

                                                                                              Example 2:

                                                                                              -
                                                                                              Input: licensePlate = "1s3 456", words = ["looks", "pest", "stew", "show"]
                                                                                              -Output: "pest"
                                                                                              -Explanation: There are 3 smallest length words that contains the letters "s".
                                                                                              -We return the one that occurred first.
                                                                                              -
                                                                                              -

                                                                                              Note:

                                                                                              -
                                                                                                -
                                                                                              • licensePlate will be a string with length in range [1, 7].
                                                                                              • -
                                                                                              • licensePlate will contain digits, spaces, or letters (uppercase or lowercase).
                                                                                              • -
                                                                                              • words will have a length in the range [10, 1000].
                                                                                              • -
                                                                                              • Every words[i] will consist of lowercase letters, and have length in range [1, 15].
                                                                                              • -
                                                                                              -

                                                                                              Solution

                                                                                              -
                                                                                              /**
                                                                                              - * @param {string} licensePlate
                                                                                              - * @param {string[]} words
                                                                                              - * @return {string}
                                                                                              - */
                                                                                              -var shortestCompletingWord = function(licensePlate, words) {
                                                                                              -  var count = 0;
                                                                                              -  var map = Array(26);
                                                                                              -  var start = 'a'.charCodeAt(0);
                                                                                              -  var index = 0;
                                                                                              -  var testMap = null;
                                                                                              -  var testCount = 0;
                                                                                              -  var minLen = Number.MAX_SAFE_INTEGER;
                                                                                              -  var result = '';
                                                                                              -
                                                                                              -  for (var i = 0; i < licensePlate.length; i++) {
                                                                                              -    index = licensePlate[i].toLowerCase().charCodeAt(0) - start;
                                                                                              -    if (index < 0 || index >= 26) continue;
                                                                                              -    if (!map[index]) {
                                                                                              -      count++;
                                                                                              -      map[index] = 0;
                                                                                              -    }
                                                                                              -    map[index]++;
                                                                                              -  }
                                                                                              -
                                                                                              -  for (var j = 0; j < words.length; j++) {
                                                                                              -    testMap = Array(26);
                                                                                              -    testCount = 0;
                                                                                              -    for (var k = 0; k < words[j].length; k++) {
                                                                                              -      index = words[j][k].toLowerCase().charCodeAt(0) - start;
                                                                                              -      if (index < 0 || index >= 26) continue;
                                                                                              -      if (!testMap[index]) testMap[index] = 1;
                                                                                              -      else testMap[index]++;
                                                                                              -      if (testMap[index] === map[index]) testCount++;
                                                                                              -    }
                                                                                              -    if (testCount === count && words[j].length < minLen) {
                                                                                              -      minLen = words[j].length;
                                                                                              -      result = words[j];
                                                                                              -    }
                                                                                              -  }
                                                                                              -
                                                                                              -  return result;
                                                                                              -};
                                                                                              -
                                                                                              -

                                                                                              Explain:

                                                                                              -

                                                                                              nope.

                                                                                              -

                                                                                              Complexity:

                                                                                              -
                                                                                                -
                                                                                              • Time complexity :
                                                                                              • -
                                                                                              • Space complexity :
                                                                                              • -
                                                                                              github
                                                                                              \ No newline at end of file diff --git a/docs/problem/simplify-path.html b/docs/problem/simplify-path.html deleted file mode 100644 index e1d24ee..0000000 --- a/docs/problem/simplify-path.html +++ /dev/null @@ -1,39 +0,0 @@ -Simplify Path - LeetCode javascript solutions

                                                                                              71. Simplify Path

                                                                                              Difficulty:
                                                                                              Related Topics:
                                                                                              Similar Questions:

                                                                                                Problem

                                                                                                -

                                                                                                Given an absolute path for a file (Unix-style), simplify it.

                                                                                                -

                                                                                                For example, -path = "/home/", => "/home" -path = "/a/./b/../../c/", => "/c"

                                                                                                -

                                                                                                Corner Cases:

                                                                                                -

                                                                                                Did you consider the case where path = "/../"? -In this case, you should return "/".

                                                                                                -

                                                                                                Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/". -In this case, you should ignore redundant slashes and return "/home/foo".

                                                                                                -

                                                                                                Solution

                                                                                                -
                                                                                                /**
                                                                                                - * @param {string} path
                                                                                                - * @return {string}
                                                                                                - */
                                                                                                -var simplifyPath = function(path) {
                                                                                                -  var arr = path.split('/');
                                                                                                -  var stack = [];
                                                                                                -  var len = arr.length;
                                                                                                -  var item = '';
                                                                                                -  for (var i = 0; i < len; i++) {
                                                                                                -    item = arr[i];
                                                                                                -    if (item === '' || item === '.') continue;
                                                                                                -    if (item === '..') {
                                                                                                -      stack.pop();
                                                                                                -    } else {
                                                                                                -      stack.push(item);
                                                                                                -    }
                                                                                                -  }
                                                                                                -  return '/' + stack.join('/');
                                                                                                -};
                                                                                                -
                                                                                                -

                                                                                                Explain:

                                                                                                -

                                                                                                栈。

                                                                                                -

                                                                                                Complexity:

                                                                                                -
                                                                                                  -
                                                                                                • Time complexity : O(n).
                                                                                                • -
                                                                                                • Space complexity : O(n).
                                                                                                • -
                                                                                                github
                                                                                                \ No newline at end of file diff --git a/docs/problem/single-number-ii.html b/docs/problem/single-number-ii.html deleted file mode 100644 index 0fdcfde..0000000 --- a/docs/problem/single-number-ii.html +++ /dev/null @@ -1,37 +0,0 @@ -Single Number II - LeetCode javascript solutions

                                                                                                137. Single Number II

                                                                                                Difficulty:
                                                                                                Related Topics:

                                                                                                Problem

                                                                                                -

                                                                                                Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one.

                                                                                                -

                                                                                                Note:

                                                                                                -

                                                                                                Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

                                                                                                -

                                                                                                Example 1:

                                                                                                -
                                                                                                Input: [2,2,3,2]
                                                                                                -Output: 3
                                                                                                -
                                                                                                -

                                                                                                Example 2:

                                                                                                -
                                                                                                Input: [0,1,0,1,0,1,99]
                                                                                                -Output: 99
                                                                                                -
                                                                                                -

                                                                                                Solution 1

                                                                                                -
                                                                                                /**
                                                                                                - * @param {number[]} nums
                                                                                                - * @return {number}
                                                                                                - */
                                                                                                -var singleNumber = function(nums) {
                                                                                                -  let one = 0;
                                                                                                -  let two = 0;
                                                                                                -  let len = nums.length;
                                                                                                -  for (var i = 0; i < len; i++) {
                                                                                                -    one = (one ^ nums[i]) & ~two;
                                                                                                -    two = (two ^ nums[i]) & ~one;
                                                                                                -  }
                                                                                                -  return one;
                                                                                                -};
                                                                                                -
                                                                                                -

                                                                                                Explain:

                                                                                                -

                                                                                                one 的二进制中每个 1 代表该位置 1 出现 1 次; -two 的二进制中每个 1 代表该位置 1 出现 2 次; -如果某位置 1 出现 3 次,则清零。

                                                                                                -

                                                                                                Complexity:

                                                                                                -
                                                                                                  -
                                                                                                • Time complexity : O(n).
                                                                                                • -
                                                                                                • Space complexity : O(1).
                                                                                                • -
                                                                                                github
                                                                                                \ No newline at end of file diff --git a/docs/problem/single-number.html b/docs/problem/single-number.html deleted file mode 100644 index 1891b26..0000000 --- a/docs/problem/single-number.html +++ /dev/null @@ -1,33 +0,0 @@ -Single Number - LeetCode javascript solutions

                                                                                                136. Single Number

                                                                                                Difficulty:

                                                                                                Problem

                                                                                                -

                                                                                                Given a non-empty array of integers, every element appears twice except for one. Find that single one.

                                                                                                -

                                                                                                Note:

                                                                                                -

                                                                                                Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

                                                                                                -

                                                                                                Example 1:

                                                                                                -
                                                                                                Input: [2,2,1]
                                                                                                -Output: 1
                                                                                                -
                                                                                                -

                                                                                                Example 2:

                                                                                                -
                                                                                                Input: [4,1,2,1,2]
                                                                                                -Output: 4
                                                                                                -
                                                                                                -

                                                                                                Solution

                                                                                                -
                                                                                                /**
                                                                                                - * @param {number[]} nums
                                                                                                - * @return {number}
                                                                                                - */
                                                                                                -var singleNumber = function(nums) {
                                                                                                -  var res = 0;
                                                                                                -  var len = nums.length;
                                                                                                -  for (var i = 0; i < len; i++) {
                                                                                                -    res ^= nums[i];
                                                                                                -  }
                                                                                                -  return res;
                                                                                                -};
                                                                                                -
                                                                                                -

                                                                                                Explain:

                                                                                                -

                                                                                                XOR

                                                                                                -

                                                                                                Complexity:

                                                                                                -
                                                                                                  -
                                                                                                • Time complexity : O(n).
                                                                                                • -
                                                                                                • Space complexity : O(1).
                                                                                                • -
                                                                                                github
                                                                                                \ No newline at end of file diff --git a/docs/problem/sort-colors.html b/docs/problem/sort-colors.html deleted file mode 100644 index c28bedc..0000000 --- a/docs/problem/sort-colors.html +++ /dev/null @@ -1,96 +0,0 @@ -Sort Colors - LeetCode javascript solutions

                                                                                                75. Sort Colors

                                                                                                Difficulty:
                                                                                                Related Topics:

                                                                                                Problem

                                                                                                -

                                                                                                Given an array with n objects colored red, white or blue, sort them **in-place **so that objects of the same color are adjacent, with the colors in the order red, white and blue.

                                                                                                -

                                                                                                Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.

                                                                                                -

                                                                                                Note: You are not suppose to use the library's sort function for this problem.

                                                                                                -

                                                                                                Example:

                                                                                                -
                                                                                                Input: [2,0,2,1,1,0]
                                                                                                -Output: [0,0,1,1,2,2]
                                                                                                -
                                                                                                -

                                                                                                Follow up:

                                                                                                -
                                                                                                  -
                                                                                                • A rather straight forward solution is a two-pass algorithm using counting sort. First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.
                                                                                                • -
                                                                                                • Could you come up with a one-pass algorithm using only constant space?
                                                                                                • -
                                                                                                -

                                                                                                Solution 1

                                                                                                -
                                                                                                /**
                                                                                                - * @param {number[]} nums
                                                                                                - * @return {void} Do not return anything, modify nums in-place instead.
                                                                                                - */
                                                                                                -var sortColors = function(nums) {
                                                                                                -  var counts = [0, 0, 0];
                                                                                                -  var len = nums.length;
                                                                                                -  for (var i = 0; i < len; i++) {
                                                                                                -    counts[nums[i]]++;
                                                                                                -  }
                                                                                                -  for (var j = 0; j < len; j++) {
                                                                                                -    nums[j] = j < counts[0] ? 0 : (j < counts[0] + counts[1] ? 1 : 2);
                                                                                                -  }
                                                                                                -};
                                                                                                -
                                                                                                -

                                                                                                Explain:

                                                                                                -

                                                                                                nope.

                                                                                                -

                                                                                                Complexity:

                                                                                                -
                                                                                                  -
                                                                                                • Time complexity : O(2n).
                                                                                                • -
                                                                                                • Space complexity : O(1).
                                                                                                • -
                                                                                                -

                                                                                                Solution 2

                                                                                                -
                                                                                                /**
                                                                                                - * @param {number[]} nums
                                                                                                - * @return {void} Do not return anything, modify nums in-place instead.
                                                                                                - */
                                                                                                -var sortColors = function(nums) {
                                                                                                -  var m = 0;
                                                                                                -  var n = 0;
                                                                                                -  var k = nums.length;
                                                                                                -  for (var i = 0; i < k; i++) {
                                                                                                -    if (nums[i] === 0) {
                                                                                                -      nums[i] = 2;
                                                                                                -      nums[n++] = 1;
                                                                                                -      nums[m++] = 0;
                                                                                                -    } else if (nums[i] === 1) {
                                                                                                -      nums[i] = 2;
                                                                                                -      nums[n++] = 1;
                                                                                                -    } else {
                                                                                                -      nums[i] = 2;
                                                                                                -    }
                                                                                                -  }
                                                                                                -};
                                                                                                -
                                                                                                -

                                                                                                Explain:

                                                                                                -

                                                                                                [0, m)0[m, n)1[n, k)2

                                                                                                -

                                                                                                Complexity:

                                                                                                -
                                                                                                  -
                                                                                                • Time complexity : O(n).
                                                                                                • -
                                                                                                • Space complexity : O(1).
                                                                                                • -
                                                                                                -

                                                                                                Solution 3

                                                                                                -
                                                                                                /**
                                                                                                - * @param {number[]} nums
                                                                                                - * @return {void} Do not return anything, modify nums in-place instead.
                                                                                                - */
                                                                                                -var sortColors = function(nums) {
                                                                                                -  var j = 0;
                                                                                                -  var k = nums.length - 1;
                                                                                                -  for (var i = 0; i <= k; i++) {
                                                                                                -    if (nums[i] === 0) {
                                                                                                -      swap(nums, i, j++);
                                                                                                -    } else if (nums[i] === 2) {
                                                                                                -      swap(nums, i--, k--);
                                                                                                -    }
                                                                                                -  }
                                                                                                -};
                                                                                                -
                                                                                                -var swap = function (arr, a, b) {
                                                                                                -  var tmp = arr[a];
                                                                                                -  arr[a] = arr[b];
                                                                                                -  arr[b] = tmp;
                                                                                                -};
                                                                                                -
                                                                                                -

                                                                                                Explain:

                                                                                                -

                                                                                                [0, j)0[j, k)1[k, len)2

                                                                                                -

                                                                                                Complexity:

                                                                                                -
                                                                                                  -
                                                                                                • Time complexity : O(n).
                                                                                                • -
                                                                                                • Space complexity : O(1).
                                                                                                • -
                                                                                                github
                                                                                                \ No newline at end of file diff --git a/docs/problem/sort-list.html b/docs/problem/sort-list.html deleted file mode 100644 index e6ea2df..0000000 --- a/docs/problem/sort-list.html +++ /dev/null @@ -1,65 +0,0 @@ -Sort List - LeetCode javascript solutions

                                                                                                148. Sort List

                                                                                                Difficulty:
                                                                                                Related Topics:

                                                                                                Problem

                                                                                                -

                                                                                                Sort a linked list in O(n log n) time using constant space complexity.

                                                                                                -

                                                                                                Example 1:

                                                                                                -
                                                                                                Input: 4->2->1->3
                                                                                                -Output: 1->2->3->4
                                                                                                -
                                                                                                -

                                                                                                Example 2:

                                                                                                -
                                                                                                Input: -1->5->3->4->0
                                                                                                -Output: -1->0->3->4->5
                                                                                                -
                                                                                                -

                                                                                                Solution

                                                                                                -
                                                                                                /**
                                                                                                - * Definition for singly-linked list.
                                                                                                - * function ListNode(val) {
                                                                                                - *     this.val = val;
                                                                                                - *     this.next = null;
                                                                                                - * }
                                                                                                - */
                                                                                                -/**
                                                                                                - * @param {ListNode} head
                                                                                                - * @return {ListNode}
                                                                                                - */
                                                                                                -var sortList = function(head) {
                                                                                                -  if (!head || !head.next) return head;
                                                                                                -  var slow = head;
                                                                                                -  var fast = head;
                                                                                                -  var prev = null;
                                                                                                -  while (fast && fast.next) {
                                                                                                -    prev = slow;
                                                                                                -    slow = slow.next;
                                                                                                -    fast = fast.next.next;
                                                                                                -  }
                                                                                                -  prev.next = null;
                                                                                                -  return merge(sortList(head), sortList(slow));
                                                                                                -};
                                                                                                -
                                                                                                -var merge = function (list1, list2) {
                                                                                                -  var p1 = list1;
                                                                                                -  var p2 = list2;
                                                                                                -  var newHead = new ListNode(0);
                                                                                                -  var now = newHead;
                                                                                                -  while (p1 || p2) {
                                                                                                -    if (!p1 || !p2) {
                                                                                                -      now.next = p1 || p2;
                                                                                                -      break;
                                                                                                -    } else if (p1.val < p2.val) {
                                                                                                -      now.next = p1;
                                                                                                -      p1 = p1.next;
                                                                                                -    } else {
                                                                                                -      now.next = p2;
                                                                                                -      p2 = p2.next;
                                                                                                -    }
                                                                                                -    now = now.next;
                                                                                                -    now.next = null;
                                                                                                -  }
                                                                                                -  return newHead.next;
                                                                                                -};
                                                                                                -
                                                                                                -

                                                                                                Explain:

                                                                                                -

                                                                                                nope.

                                                                                                -

                                                                                                Complexity:

                                                                                                -
                                                                                                  -
                                                                                                • Time complexity : O(nlog(n)).
                                                                                                • -
                                                                                                • Space complexity : O(n).
                                                                                                • -
                                                                                                github
                                                                                                \ No newline at end of file diff --git a/docs/problem/spiral-matrix-ii.html b/docs/problem/spiral-matrix-ii.html deleted file mode 100644 index 60fa7ad..0000000 --- a/docs/problem/spiral-matrix-ii.html +++ /dev/null @@ -1,47 +0,0 @@ -Spiral Matrix II - LeetCode javascript solutions

                                                                                                59. Spiral Matrix II

                                                                                                Difficulty:
                                                                                                Related Topics:
                                                                                                Similar Questions:

                                                                                                Problem

                                                                                                -

                                                                                                Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

                                                                                                -

                                                                                                Example:

                                                                                                -
                                                                                                Input: 3
                                                                                                -Output:
                                                                                                -[
                                                                                                - [ 1, 2, 3 ],
                                                                                                - [ 8, 9, 4 ],
                                                                                                - [ 7, 6, 5 ]
                                                                                                -]
                                                                                                -
                                                                                                -

                                                                                                Solution

                                                                                                -
                                                                                                /**
                                                                                                - * @param {number} n
                                                                                                - * @return {number[][]}
                                                                                                - */
                                                                                                -var generateMatrix = function(n) {
                                                                                                -  var x1 = 0;
                                                                                                -  var x2 = n - 1;
                                                                                                -  var y1 = 0;
                                                                                                -  var y2 = n - 1;
                                                                                                -  var i = 0;
                                                                                                -  var res = Array(n).fill(0).map(_ => Array(n));
                                                                                                -  while (x1 <= x2 && y1 <= y2) {
                                                                                                -    for (var x = x1; x <= x2; x++) res[y1][x] = ++i;
                                                                                                -    for (var y = y1 + 1; y <= y2; y++) res[y][x2] = ++i;
                                                                                                -    for (var x = x2 - 1; x > x1; x--) res[y2][x] = ++i;
                                                                                                -    for (var y = y2; y > y1; y--) res[y][x1] = ++i;
                                                                                                -    x1++;
                                                                                                -    x2--;
                                                                                                -    y1++;
                                                                                                -    y2--;
                                                                                                -  }
                                                                                                -  return res;
                                                                                                -};
                                                                                                -
                                                                                                -

                                                                                                Explain:

                                                                                                -

                                                                                                绕圈,1 => 2 => 3 => 4 => 5

                                                                                                -
                                                                                                111
                                                                                                -452
                                                                                                -432
                                                                                                -
                                                                                                -

                                                                                                Complexity:

                                                                                                -
                                                                                                  -
                                                                                                • Time complexity : O(n^2).
                                                                                                • -
                                                                                                • Space complexity : O(n^2).
                                                                                                • -
                                                                                                github
                                                                                                \ No newline at end of file diff --git a/docs/problem/spiral-matrix.html b/docs/problem/spiral-matrix.html deleted file mode 100644 index f7a95cd..0000000 --- a/docs/problem/spiral-matrix.html +++ /dev/null @@ -1,56 +0,0 @@ -Spiral Matrix - LeetCode javascript solutions

                                                                                                54. Spiral Matrix

                                                                                                Difficulty:
                                                                                                Related Topics:
                                                                                                Similar Questions:

                                                                                                Problem

                                                                                                -

                                                                                                Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

                                                                                                -

                                                                                                Example 1:

                                                                                                -
                                                                                                Input:
                                                                                                -[
                                                                                                - [ 1, 2, 3 ],
                                                                                                - [ 4, 5, 6 ],
                                                                                                - [ 7, 8, 9 ]
                                                                                                -]
                                                                                                -Output: [1,2,3,6,9,8,7,4,5]
                                                                                                -
                                                                                                -

                                                                                                Example 2:

                                                                                                -
                                                                                                Input:
                                                                                                -[
                                                                                                -  [1, 2, 3, 4],
                                                                                                -  [5, 6, 7, 8],
                                                                                                -  [9,10,11,12]
                                                                                                -]
                                                                                                -Output: [1,2,3,4,8,12,11,10,9,5,6,7]
                                                                                                -
                                                                                                -

                                                                                                Solution

                                                                                                -
                                                                                                /**
                                                                                                - * @param {number[][]} matrix
                                                                                                - * @return {number[]}
                                                                                                - */
                                                                                                -var spiralOrder = function(matrix) {
                                                                                                -  var n = matrix.length;
                                                                                                -  var m = (matrix[0] || []).length;
                                                                                                -  var res = [];
                                                                                                -  var x1 = 0;
                                                                                                -  var x2 = m - 1;
                                                                                                -  var y1 = 0;
                                                                                                -  var y2 = n - 1;
                                                                                                -  while (x1 <= x2 && y1 <= y2) {
                                                                                                -    for (var x = x1; x <= x2; x++) res.push(matrix[y1][x]);
                                                                                                -    for (var y = y1 + 1; y <= y2; y++) res.push(matrix[y][x2]);
                                                                                                -    if (x1 < x2 && y1 < y2) {
                                                                                                -      for (var x = x2 - 1; x > x1; x--) res.push(matrix[y2][x]);
                                                                                                -      for (var y = y2; y > y1; y--) res.push(matrix[y][x1]);
                                                                                                -    }
                                                                                                -    x1++;
                                                                                                -    x2--;
                                                                                                -    y1++;
                                                                                                -    y2--;
                                                                                                -  }
                                                                                                -  return res;
                                                                                                -};
                                                                                                -
                                                                                                -

                                                                                                Explain:

                                                                                                -

                                                                                                横的当做 x 轴,竖的当 y 轴。 -x1、x2、y1、y2 是当前遍历的四边形的四个角。

                                                                                                -

                                                                                                Complexity:

                                                                                                -
                                                                                                  -
                                                                                                • Time complexity : O(n). n 为总数。
                                                                                                • -
                                                                                                • Space complexity : O(n).
                                                                                                • -
                                                                                                github
                                                                                                \ No newline at end of file diff --git a/docs/problem/split-array-with-same-average.html b/docs/problem/split-array-with-same-average.html deleted file mode 100644 index dcad31e..0000000 --- a/docs/problem/split-array-with-same-average.html +++ /dev/null @@ -1,37 +0,0 @@ -Split Array With Same Average - LeetCode javascript solutions

                                                                                                823. Split Array With Same Average

                                                                                                Difficulty:
                                                                                                Related Topics:
                                                                                                Similar Questions:

                                                                                                  Problem

                                                                                                  -

                                                                                                  In a given integer array A, we must move every element of A to either list B or list C. (B and C initially start empty.)

                                                                                                  -

                                                                                                  Return true if and only if after such a move, it is possible that the average value of B is equal to the average value of C, and B and C are both non-empty.

                                                                                                  -
                                                                                                  Example :
                                                                                                  -Input: 
                                                                                                  -[1,2,3,4,5,6,7,8]
                                                                                                  -Output: true
                                                                                                  -Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have the average of 4.5.
                                                                                                  -
                                                                                                  -

                                                                                                  Note:

                                                                                                  -
                                                                                                    -
                                                                                                  • The length of A will be in the range [1, 30].
                                                                                                  • -
                                                                                                  • A[i] will be in the range of [0, 10000].
                                                                                                  • -
                                                                                                  -

                                                                                                  Solution

                                                                                                  -
                                                                                                  /**
                                                                                                  - * @param {number[]} A
                                                                                                  - * @return {boolean}
                                                                                                  - */
                                                                                                  -var splitArraySameAverage = function(A) {
                                                                                                  -  var sum = A.reduce((last, num) => (last + num), 0);
                                                                                                  -  return find(A, 0, sum, 0, 0);
                                                                                                  -};
                                                                                                  -
                                                                                                  -var find = function (A, index, sum, sumB, numB) {
                                                                                                  -  if (index >= A.length) return false;
                                                                                                  -  if (numB > 0 && numB < A.length && sumB / numB === (sum - sumB) / (A.length - numB)) return true;
                                                                                                  -  return find(A, index + 1, sum, sumB, numB) || find(A, index + 1, sum, sumB + A[index], numB + 1);
                                                                                                  -};
                                                                                                  -
                                                                                                  -

                                                                                                  Explain:

                                                                                                  -

                                                                                                  nope.

                                                                                                  -

                                                                                                  Complexity:

                                                                                                  -
                                                                                                    -
                                                                                                  • Time complexity : O(2^n).
                                                                                                  • -
                                                                                                  • Space complexity : O(1).
                                                                                                  • -
                                                                                                  github
                                                                                                  \ No newline at end of file diff --git a/docs/problem/sqrtx.html b/docs/problem/sqrtx.html deleted file mode 100644 index 5c68fbf..0000000 --- a/docs/problem/sqrtx.html +++ /dev/null @@ -1,43 +0,0 @@ -Sqrt(x) - LeetCode javascript solutions

                                                                                                  69. Sqrt(x)

                                                                                                  Difficulty:
                                                                                                  Related Topics:
                                                                                                  Similar Questions:

                                                                                                  Problem

                                                                                                  -

                                                                                                  Implement int sqrt(int x).

                                                                                                  -

                                                                                                  Compute and return the square root of x, where x is guaranteed to be a non-negative integer.

                                                                                                  -

                                                                                                  Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.

                                                                                                  -

                                                                                                  Example 1:

                                                                                                  -
                                                                                                  Input: 4
                                                                                                  -Output: 2
                                                                                                  -
                                                                                                  -

                                                                                                  Example 2:

                                                                                                  -
                                                                                                  Input: 8
                                                                                                  -Output: 2
                                                                                                  -Explanation: The square root of 8 is 2.82842..., and since 
                                                                                                  -             the decimal part is truncated, 2 is returned.
                                                                                                  -
                                                                                                  -

                                                                                                  Solution

                                                                                                  -
                                                                                                  /**
                                                                                                  - * @param {number} x
                                                                                                  - * @return {number}
                                                                                                  - */
                                                                                                  -var mySqrt = function(x) {
                                                                                                  -  if (x < 2) return x;
                                                                                                  -  var left = 1;
                                                                                                  -  var right = x;
                                                                                                  -  var mid = 0;
                                                                                                  -  while (left <= right) {
                                                                                                  -    mid = left + Math.floor((right - left) / 2);
                                                                                                  -    if (mid > x / mid) {
                                                                                                  -      right = mid - 1;
                                                                                                  -    } else if ((mid + 1) > x / (mid + 1)) {
                                                                                                  -      return mid;
                                                                                                  -    } else {
                                                                                                  -      left = mid + 1;
                                                                                                  -    }
                                                                                                  -  }
                                                                                                  -};
                                                                                                  -
                                                                                                  -

                                                                                                  Explain:

                                                                                                  -

                                                                                                  nope.

                                                                                                  -

                                                                                                  Complexity:

                                                                                                  -
                                                                                                    -
                                                                                                  • Time complexity : O(log(n)).
                                                                                                  • -
                                                                                                  • Space complexity : O(1).
                                                                                                  • -
                                                                                                  github
                                                                                                  \ No newline at end of file diff --git a/docs/problem/string-to-integer-atoi.html b/docs/problem/string-to-integer-atoi.html deleted file mode 100644 index d90f60d..0000000 --- a/docs/problem/string-to-integer-atoi.html +++ /dev/null @@ -1,75 +0,0 @@ -String to Integer (atoi) - LeetCode javascript solutions

                                                                                                  8. String to Integer (atoi)

                                                                                                  Difficulty:
                                                                                                  Related Topics:
                                                                                                  Similar Questions:

                                                                                                  Problem

                                                                                                  -

                                                                                                  Implement atoi which converts a string to an integer.

                                                                                                  -

                                                                                                  The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

                                                                                                  -

                                                                                                  The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

                                                                                                  -

                                                                                                  If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

                                                                                                  -

                                                                                                  If no valid conversion could be performed, a zero value is returned.

                                                                                                  -

                                                                                                  Note:

                                                                                                  -
                                                                                                    -
                                                                                                  • Only the space character ' ' is considered as whitespace character.
                                                                                                  • -
                                                                                                  • Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. If the numerical value is out of the range of representable values, INTMAX (231 − 1) or INTMIN (−231) is returned.
                                                                                                  • -
                                                                                                  -

                                                                                                  Example 1:

                                                                                                  -
                                                                                                  Input: "42"
                                                                                                  -Output: 42
                                                                                                  -
                                                                                                  -

                                                                                                  Example 2:

                                                                                                  -
                                                                                                  Input: "   -42"
                                                                                                  -Output: -42
                                                                                                  -Explanation: The first non-whitespace character is '-', which is the minus sign.
                                                                                                  -             Then take as many numerical digits as possible, which gets 42.
                                                                                                  -
                                                                                                  -

                                                                                                  Example 3:

                                                                                                  -
                                                                                                  Input: "4193 with words"
                                                                                                  -Output: 4193
                                                                                                  -Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.
                                                                                                  -
                                                                                                  -

                                                                                                  Example 4:

                                                                                                  -
                                                                                                  Input: "words and 987"
                                                                                                  -Output: 0
                                                                                                  -Explanation: The first non-whitespace character is 'w', which is not a numerical 
                                                                                                  -             digit or a +/- sign. Therefore no valid conversion could be performed.
                                                                                                  -
                                                                                                  -

                                                                                                  Example 5:

                                                                                                  -
                                                                                                  Input: "-91283472332"
                                                                                                  -Output: -2147483648
                                                                                                  -Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer.
                                                                                                  -             Thefore INT_MIN (−231) is returned.
                                                                                                  -
                                                                                                  -

                                                                                                  Solution

                                                                                                  -
                                                                                                  /**
                                                                                                  - * @param {string} str
                                                                                                  - * @return {number}
                                                                                                  - */
                                                                                                  -var myAtoi = function(str) {
                                                                                                  -  var i = 0;
                                                                                                  -  var sign = 1;
                                                                                                  -  var res = 0;
                                                                                                  -  var len = str.length;
                                                                                                  -  var INT_MAX = 2147483647;
                                                                                                  -  var INT_MIN = - INT_MAX - 1;
                                                                                                  -
                                                                                                  -  while (str[i] === ' ') i++;
                                                                                                  -
                                                                                                  -  if (str[i] === '+' || str[i] === '-') {
                                                                                                  -    sign = str[i] === '+' ? 1 : -1;
                                                                                                  -    i++;
                                                                                                  -  }
                                                                                                  -
                                                                                                  -  while (str[i] >= '0' && str[i] <= '9') {
                                                                                                  -    res = (res * 10) + (str[i] - 0);
                                                                                                  -    if (sign === 1 && res > INT_MAX) return INT_MAX;
                                                                                                  -    if (sign === -1 && res > INT_MAX + 1) return INT_MIN;
                                                                                                  -    i++;
                                                                                                  -  }
                                                                                                  -
                                                                                                  -  return res * sign;
                                                                                                  -};
                                                                                                  -
                                                                                                  -

                                                                                                  Explain:

                                                                                                  -

                                                                                                  nope.

                                                                                                  -

                                                                                                  Complexity:

                                                                                                  -
                                                                                                    -
                                                                                                  • Time complexity : O(n).
                                                                                                  • -
                                                                                                  • Space complexity : O(1).
                                                                                                  • -
                                                                                                  github
                                                                                                  \ No newline at end of file diff --git a/docs/problem/subarray-sum-equals-k.html b/docs/problem/subarray-sum-equals-k.html deleted file mode 100644 index d48d447..0000000 --- a/docs/problem/subarray-sum-equals-k.html +++ /dev/null @@ -1,42 +0,0 @@ -Subarray Sum Equals K - LeetCode javascript solutions

                                                                                                  560. Subarray Sum Equals K

                                                                                                  Difficulty:
                                                                                                  Related Topics:

                                                                                                  Problem

                                                                                                  -

                                                                                                  Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.

                                                                                                  -

                                                                                                  Example 1:

                                                                                                  -
                                                                                                  Input:nums = [1,1,1], k = 2
                                                                                                  -Output: 2
                                                                                                  -
                                                                                                  -

                                                                                                  Note:

                                                                                                  -
                                                                                                    -
                                                                                                  • The length of the array is in range [1, 20,000].
                                                                                                  • -
                                                                                                  • The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].
                                                                                                  • -
                                                                                                  -

                                                                                                  Solution

                                                                                                  -
                                                                                                  /**
                                                                                                  - * @param {number[]} nums
                                                                                                  - * @param {number} k
                                                                                                  - * @return {number}
                                                                                                  - */
                                                                                                  -var subarraySum = function(nums, k) {
                                                                                                  -  var map = {};
                                                                                                  -  var len = nums.length;
                                                                                                  -  var sum = 0;
                                                                                                  -  var res = 0;
                                                                                                  -
                                                                                                  -  map[0] = 1;
                                                                                                  -
                                                                                                  -  for (var i = 0; i < len; i++) {
                                                                                                  -    sum += nums[i];
                                                                                                  -    res += (map[sum - k] || 0);
                                                                                                  -    map[sum] = (map[sum] || 0) + 1;
                                                                                                  -  }
                                                                                                  -
                                                                                                  -  return res;
                                                                                                  -};
                                                                                                  -
                                                                                                  -

                                                                                                  Explain:

                                                                                                  -

                                                                                                  i 处,map[key] 表示 0 ~ i 中和为 key 的子数组数量。

                                                                                                  -

                                                                                                  i 处,0 ~ i 的和为 sum,此前和为 k 的子数组个数为 map[sum - k]

                                                                                                  -

                                                                                                  Complexity:

                                                                                                  -
                                                                                                    -
                                                                                                  • Time complexity : O(n).
                                                                                                  • -
                                                                                                  • Space complexity : O(n).
                                                                                                  • -
                                                                                                  github
                                                                                                  \ No newline at end of file diff --git a/docs/problem/subsets-ii.html b/docs/problem/subsets-ii.html deleted file mode 100644 index 82603e8..0000000 --- a/docs/problem/subsets-ii.html +++ /dev/null @@ -1,46 +0,0 @@ -Subsets II - LeetCode javascript solutions

                                                                                                  90. Subsets II

                                                                                                  Difficulty:
                                                                                                  Related Topics:
                                                                                                  Similar Questions:

                                                                                                  Problem

                                                                                                  -

                                                                                                  Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).

                                                                                                  -

                                                                                                  Note: The solution set must not contain duplicate subsets.

                                                                                                  -

                                                                                                  Example:

                                                                                                  -
                                                                                                  Input: [1,2,2]
                                                                                                  -Output:
                                                                                                  -[
                                                                                                  -  [2],
                                                                                                  -  [1],
                                                                                                  -  [1,2,2],
                                                                                                  -  [2,2],
                                                                                                  -  [1,2],
                                                                                                  -  []
                                                                                                  -]
                                                                                                  -
                                                                                                  -

                                                                                                  Solution

                                                                                                  -
                                                                                                  /**
                                                                                                  - * @param {number[]} nums
                                                                                                  - * @return {number[][]}
                                                                                                  - */
                                                                                                  -var subsetsWithDup = function(nums) {
                                                                                                  -  var res = [];
                                                                                                  -  nums.sort((a, b) => a - b);
                                                                                                  -  helper(nums, 0, res, []);
                                                                                                  -  return res;
                                                                                                  -};
                                                                                                  -
                                                                                                  -var helper = function (nums, start, res, now) {
                                                                                                  -  res.push(Array.from(now));
                                                                                                  -
                                                                                                  -  for (var i = start; i < nums.length; i++) {
                                                                                                  -    if (i === start || nums[i] !== nums[i - 1]) {
                                                                                                  -      now.push(nums[i]);
                                                                                                  -      helper(nums, i + 1, res, now);
                                                                                                  -      now.pop();
                                                                                                  -    }
                                                                                                  -  }
                                                                                                  -};
                                                                                                  -
                                                                                                  -

                                                                                                  Explain:

                                                                                                  -

                                                                                                  nope.

                                                                                                  -

                                                                                                  Complexity:

                                                                                                  -
                                                                                                    -
                                                                                                  • Time complexity :
                                                                                                  • -
                                                                                                  • Space complexity :
                                                                                                  • -
                                                                                                  github
                                                                                                  \ No newline at end of file diff --git a/docs/problem/subsets.html b/docs/problem/subsets.html deleted file mode 100644 index a46ba9f..0000000 --- a/docs/problem/subsets.html +++ /dev/null @@ -1,49 +0,0 @@ -Subsets - LeetCode javascript solutions

                                                                                                  78. Subsets

                                                                                                  Difficulty:

                                                                                                  Problem

                                                                                                  -

                                                                                                  Given a set of distinct integers, nums, return all possible subsets (the power set).

                                                                                                  -

                                                                                                  Note: The solution set must not contain duplicate subsets.

                                                                                                  -

                                                                                                  Example:

                                                                                                  -
                                                                                                  Input: nums = [1,2,3]
                                                                                                  -Output:
                                                                                                  -[
                                                                                                  -  [3],
                                                                                                  -  [1],
                                                                                                  -  [2],
                                                                                                  -  [1,2,3],
                                                                                                  -  [1,3],
                                                                                                  -  [2,3],
                                                                                                  -  [1,2],
                                                                                                  -  []
                                                                                                  -]
                                                                                                  -
                                                                                                  -

                                                                                                  Solution

                                                                                                  -
                                                                                                  /**
                                                                                                  - * @param {number[]} nums
                                                                                                  - * @return {number[][]}
                                                                                                  - */
                                                                                                  -var subsets = function(nums) {
                                                                                                  -  var res = [];
                                                                                                  -  helper(nums, res, [], 0);
                                                                                                  -  return res;
                                                                                                  -};
                                                                                                  -
                                                                                                  -var helper = function (nums, res, arr, start) {
                                                                                                  -  var len = nums.length;
                                                                                                  -
                                                                                                  -  res.push(Array.from(arr));
                                                                                                  -
                                                                                                  -  if (start === len) return;
                                                                                                  -
                                                                                                  -  for (var i = start; i < len; i++) {
                                                                                                  -    arr.push(nums[i]);
                                                                                                  -    helper(nums, res, arr, i + 1);
                                                                                                  -    arr.pop();
                                                                                                  -  }
                                                                                                  -};
                                                                                                  -
                                                                                                  -

                                                                                                  Explain:

                                                                                                  -

                                                                                                  nope.

                                                                                                  -

                                                                                                  Complexity:

                                                                                                  -
                                                                                                    -
                                                                                                  • Time complexity :
                                                                                                  • -
                                                                                                  • Space complexity :
                                                                                                  • -
                                                                                                  github
                                                                                                  \ No newline at end of file diff --git a/docs/problem/substring-with-concatenation-of-all-words.html b/docs/problem/substring-with-concatenation-of-all-words.html deleted file mode 100644 index 14558f4..0000000 --- a/docs/problem/substring-with-concatenation-of-all-words.html +++ /dev/null @@ -1,61 +0,0 @@ -Substring with Concatenation of All Words - LeetCode javascript solutions

                                                                                                  30. Substring with Concatenation of All Words

                                                                                                  Difficulty:
                                                                                                  Similar Questions:

                                                                                                  Problem

                                                                                                  -

                                                                                                  You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.

                                                                                                  -

                                                                                                  Example 1:

                                                                                                  -
                                                                                                  Input:
                                                                                                  -  s = "barfoothefoobarman",
                                                                                                  -  words = ["foo","bar"]
                                                                                                  -Output: [0,9]
                                                                                                  -Explanation: Substrings starting at index 0 and 9 are "barfoor" and "foobar" respectively.
                                                                                                  -The output order does not matter, returning [9,0] is fine too.
                                                                                                  -
                                                                                                  -

                                                                                                  Example 2:

                                                                                                  -
                                                                                                  Input:
                                                                                                  -  s = "wordgoodstudentgoodword",
                                                                                                  -  words = ["word","student"]
                                                                                                  -Output: []
                                                                                                  -
                                                                                                  -

                                                                                                  Solution

                                                                                                  -
                                                                                                  /**
                                                                                                  - * @param {string} s
                                                                                                  - * @param {string[]} words
                                                                                                  - * @return {number[]}
                                                                                                  - */
                                                                                                  -var findSubstring = function(s, words) {
                                                                                                  -  var sLen = s.length;
                                                                                                  -  var wLen = words.length;
                                                                                                  -  var wordLen = (words[0] || '').length;
                                                                                                  -
                                                                                                  -  if (!sLen || !wLen || !wordLen) return [];
                                                                                                  -
                                                                                                  -  var count = 0;
                                                                                                  -  var tmp = '';
                                                                                                  -  var map1 = {};
                                                                                                  -  var map2 = {};
                                                                                                  -  var res = [];
                                                                                                  -
                                                                                                  -  for (var i = 0; i < wLen; i++) {
                                                                                                  -    map1[words[i]] = (map1[words[i]] || 0) + 1;
                                                                                                  -  }
                                                                                                  -
                                                                                                  -  out: for (var j = 0; j <= sLen - (wLen * wordLen); j++) {
                                                                                                  -    map2 = {};
                                                                                                  -    count = 0;
                                                                                                  -    while (count < wLen) {
                                                                                                  -      tmp = s.substr(j + (count * wordLen), wordLen);
                                                                                                  -      if (map1[tmp] === undefined || map1[tmp] === map2[tmp]) continue out;
                                                                                                  -      map2[tmp] = (map2[tmp] || 0) + 1;
                                                                                                  -      count++;
                                                                                                  -    }
                                                                                                  -    res.push(j);
                                                                                                  -  }
                                                                                                  -
                                                                                                  -  return res;
                                                                                                  -};
                                                                                                  -
                                                                                                  -

                                                                                                  Explain:

                                                                                                  -

                                                                                                  nope.

                                                                                                  -

                                                                                                  Complexity:

                                                                                                  -
                                                                                                    -
                                                                                                  • Time complexity : O(m*n).
                                                                                                  • -
                                                                                                  • Space complexity : O(m).
                                                                                                  • -
                                                                                                  github
                                                                                                  \ No newline at end of file diff --git a/docs/problem/sudoku-solver.html b/docs/problem/sudoku-solver.html deleted file mode 100644 index 267c30a..0000000 --- a/docs/problem/sudoku-solver.html +++ /dev/null @@ -1,65 +0,0 @@ -Sudoku Solver - LeetCode javascript solutions

                                                                                                  37. Sudoku Solver

                                                                                                  Difficulty:
                                                                                                  Related Topics:
                                                                                                  Similar Questions:

                                                                                                  Problem

                                                                                                  -

                                                                                                  Write a program to solve a Sudoku puzzle by filling the empty cells.

                                                                                                  -

                                                                                                  A sudoku solution must satisfy all of the following rules:

                                                                                                  -
                                                                                                    -
                                                                                                  • Each of the digits 1-9 must occur exactly once in each row.
                                                                                                  • -
                                                                                                  • Each of the digits 1-9 must occur exactly once in each column.
                                                                                                  • -
                                                                                                  • Each of the the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.
                                                                                                  • -
                                                                                                  -

                                                                                                  Empty cells are indicated by the character '.'.

                                                                                                  -

                                                                                                  -

                                                                                                  A sudoku puzzle…

                                                                                                  -

                                                                                                  -

                                                                                                  …and its solution numbers marked in red.

                                                                                                  -

                                                                                                  Note:

                                                                                                  -
                                                                                                    -
                                                                                                  • The given board contain only digits 1-9 and the character '.'.
                                                                                                  • -
                                                                                                  • You may assume that the given Sudoku puzzle will have a single unique solution.
                                                                                                  • -
                                                                                                  • The given board size is always 9x9.
                                                                                                  • -
                                                                                                  -

                                                                                                  Solution

                                                                                                  -
                                                                                                  /**
                                                                                                  - * @param {character[][]} board
                                                                                                  - * @return {void} Do not return anything, modify board in-place instead.
                                                                                                  - */
                                                                                                  -var solveSudoku = function(board) {
                                                                                                  -  solve(board);
                                                                                                  -};
                                                                                                  -
                                                                                                  -var solve = function (board) {
                                                                                                  -  for (var i = 0; i < 9; i++) {
                                                                                                  -    for (var j = 0; j < 9; j++) {
                                                                                                  -      if (board[i][j] !== '.') continue;
                                                                                                  -      for (var k = 1; k <= 9; k++) {
                                                                                                  -        if (isValid(board, i, j, '' + k)) {
                                                                                                  -            board[i][j] = '' + k;
                                                                                                  -          if (solve(board)) {
                                                                                                  -            return true;
                                                                                                  -          } else {
                                                                                                  -            board[i][j] = '.';
                                                                                                  -          }
                                                                                                  -        }
                                                                                                  -      }
                                                                                                  -      return false;
                                                                                                  -    }
                                                                                                  -  }
                                                                                                  -  return true;
                                                                                                  -};
                                                                                                  -
                                                                                                  -var isValid = function (board, i, j, num) {
                                                                                                  -  for (var k = 0; k < 9; k++) {
                                                                                                  -    if (board[i][k] === num) return false;
                                                                                                  -    if (board[k][j] === num) return false;
                                                                                                  -    if (board[Math.floor(i / 3) * 3 + Math.floor(k / 3)][Math.floor(j / 3) * 3 + (k % 3)] === num) return false;
                                                                                                  -  }
                                                                                                  -  return true;
                                                                                                  -};
                                                                                                  -
                                                                                                  -

                                                                                                  Explain:

                                                                                                  -

                                                                                                  dfs:

                                                                                                  -

                                                                                                  遍历每个点,尝试填入 1~9 的数字,判断是否可以,不行就回滚,直到可以。

                                                                                                  -

                                                                                                  Complexity:

                                                                                                  -
                                                                                                    -
                                                                                                  • Time complexity : O(9^n). n 为格子数。
                                                                                                  • -
                                                                                                  • Space complexity : O(1).
                                                                                                  • -
                                                                                                  github
                                                                                                  \ No newline at end of file diff --git a/docs/problem/sum-root-to-leaf-numbers.html b/docs/problem/sum-root-to-leaf-numbers.html deleted file mode 100644 index 00d3bef..0000000 --- a/docs/problem/sum-root-to-leaf-numbers.html +++ /dev/null @@ -1,61 +0,0 @@ -Sum Root to Leaf Numbers - LeetCode javascript solutions

                                                                                                  129. Sum Root to Leaf Numbers

                                                                                                  Difficulty:
                                                                                                  Related Topics:

                                                                                                  Problem

                                                                                                  -

                                                                                                  Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.

                                                                                                  -

                                                                                                  An example is the root-to-leaf path 1->2->3 which represents the number 123.

                                                                                                  -

                                                                                                  Find the total sum of all root-to-leaf numbers.

                                                                                                  -

                                                                                                  Note: A leaf is a node with no children.

                                                                                                  -

                                                                                                  Example:

                                                                                                  -
                                                                                                  Input: [1,2,3]
                                                                                                  -    1
                                                                                                  -   / \
                                                                                                  -  2   3
                                                                                                  -Output: 25
                                                                                                  -Explanation:
                                                                                                  -The root-to-leaf path 1->2 represents the number 12.
                                                                                                  -The root-to-leaf path 1->3 represents the number 13.
                                                                                                  -Therefore, sum = 12 + 13 = 25.
                                                                                                  -
                                                                                                  -

                                                                                                  Example 2:

                                                                                                  -
                                                                                                  Input: [4,9,0,5,1]
                                                                                                  -    4
                                                                                                  -   / \
                                                                                                  -  9   0
                                                                                                  - / \
                                                                                                  -5   1
                                                                                                  -Output: 1026
                                                                                                  -Explanation:
                                                                                                  -The root-to-leaf path 4->9->5 represents the number 495.
                                                                                                  -The root-to-leaf path 4->9->1 represents the number 491.
                                                                                                  -The root-to-leaf path 4->0 represents the number 40.
                                                                                                  -Therefore, sum = 495 + 491 + 40 = 1026.
                                                                                                  -
                                                                                                  -

                                                                                                  Solution

                                                                                                  -
                                                                                                  /**
                                                                                                  - * Definition for a binary tree node.
                                                                                                  - * function TreeNode(val) {
                                                                                                  - *     this.val = val;
                                                                                                  - *     this.left = this.right = null;
                                                                                                  - * }
                                                                                                  - */
                                                                                                  -/**
                                                                                                  - * @param {TreeNode} root
                                                                                                  - * @return {number}
                                                                                                  - */
                                                                                                  -var sumNumbers = function(root) {
                                                                                                  -  return sum(0, root);
                                                                                                  -};
                                                                                                  -
                                                                                                  -var sum = function (before, root) {
                                                                                                  -  if (!root) return before;
                                                                                                  -  var val = before * 10 + root.val;
                                                                                                  -  if (!root.left) return sum(val, root.right);
                                                                                                  -  if (!root.right) return sum(val, root.left);
                                                                                                  -  return sum(val, root.left) + sum(val, root.right);
                                                                                                  -};
                                                                                                  -
                                                                                                  -

                                                                                                  Explain:

                                                                                                  -

                                                                                                  nope.

                                                                                                  -

                                                                                                  Complexity:

                                                                                                  -
                                                                                                    -
                                                                                                  • Time complexity : O(n).
                                                                                                  • -
                                                                                                  • Space complexity : O(1).
                                                                                                  • -
                                                                                                  github
                                                                                                  \ No newline at end of file diff --git a/docs/problem/surrounded-regions.html b/docs/problem/surrounded-regions.html deleted file mode 100644 index e56f354..0000000 --- a/docs/problem/surrounded-regions.html +++ /dev/null @@ -1,58 +0,0 @@ -Surrounded Regions - LeetCode javascript solutions

                                                                                                  130. Surrounded Regions

                                                                                                  Difficulty:

                                                                                                  Problem

                                                                                                  -

                                                                                                  Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'.

                                                                                                  -

                                                                                                  A region is captured by flipping all 'O's into 'X's in that surrounded region.

                                                                                                  -

                                                                                                  Example:

                                                                                                  -
                                                                                                  X X X X
                                                                                                  -X O O X
                                                                                                  -X X O X
                                                                                                  -X O X X
                                                                                                  -
                                                                                                  -

                                                                                                  After running your function, the board should be:

                                                                                                  -
                                                                                                  X X X X
                                                                                                  -X X X X
                                                                                                  -X X X X
                                                                                                  -X O X X
                                                                                                  -
                                                                                                  -

                                                                                                  Explanation:

                                                                                                  -

                                                                                                  Surrounded regions shouldn’t be on the border, which means that any 'O' on the border of the board are not flipped to 'X'. Any 'O' that is not on the border and it is not connected to an 'O' on the border will be flipped to 'X'. Two cells are connected if they are adjacent cells connected horizontally or vertically.

                                                                                                  -

                                                                                                  Solution

                                                                                                  -
                                                                                                  /**
                                                                                                  - * @param {character[][]} board
                                                                                                  - * @return {void} Do not return anything, modify board in-place instead.
                                                                                                  - */
                                                                                                  -var solve = function(board) {
                                                                                                  -  var xLen = board.length;
                                                                                                  -  var yLen = (board[0] || []).length;
                                                                                                  -  for (var i = 0; i < xLen; i++) {
                                                                                                  -    dfs(board, i, 0, xLen, yLen);
                                                                                                  -    dfs(board, i, yLen - 1, xLen, yLen);
                                                                                                  -  }
                                                                                                  -  for (var j = 0; j < yLen; j++) {
                                                                                                  -    dfs(board, 0, j, xLen, yLen);
                                                                                                  -    dfs(board, xLen - 1, j, xLen, yLen);
                                                                                                  -  }
                                                                                                  -  for (var m = 0; m < xLen; m++) {
                                                                                                  -    for (var n = 0; n < yLen; n++) {
                                                                                                  -      if (board[m][n] === '-') board[m][n] = 'O';
                                                                                                  -      else if (board[m][n] === 'O') board[m][n] = 'X';
                                                                                                  -    }
                                                                                                  -  }
                                                                                                  -};
                                                                                                  -
                                                                                                  -var dfs = function (board, x, y, xLen, yLen) {
                                                                                                  -  if (x >= 0 && y >= 0 && x < xLen && y < yLen && board[x][y] === 'O') {
                                                                                                  -    board[x][y] = '-';
                                                                                                  -    dfs(board, x + 1, y, xLen, yLen);
                                                                                                  -    dfs(board, x - 1, y, xLen, yLen);
                                                                                                  -    dfs(board, x, y + 1, xLen, yLen);
                                                                                                  -    dfs(board, x, y - 1, xLen, yLen);
                                                                                                  -  }
                                                                                                  -};
                                                                                                  -
                                                                                                  -

                                                                                                  Explain:

                                                                                                  -

                                                                                                  nope.

                                                                                                  -

                                                                                                  Complexity:

                                                                                                  -
                                                                                                    -
                                                                                                  • Time complexity : O(m * n).
                                                                                                  • -
                                                                                                  • Space complexity : O(1).
                                                                                                  • -
                                                                                                  github
                                                                                                  \ No newline at end of file diff --git a/docs/problem/swap-nodes-in-pairs.html b/docs/problem/swap-nodes-in-pairs.html deleted file mode 100644 index cf2ab52..0000000 --- a/docs/problem/swap-nodes-in-pairs.html +++ /dev/null @@ -1,49 +0,0 @@ -Swap Nodes in Pairs - LeetCode javascript solutions

                                                                                                  24. Swap Nodes in Pairs

                                                                                                  Difficulty:
                                                                                                  Related Topics:
                                                                                                  Similar Questions:

                                                                                                  Problem

                                                                                                  -

                                                                                                  Given a linked list, swap every two adjacent nodes and return its head.

                                                                                                  -

                                                                                                  Example:

                                                                                                  -
                                                                                                  Given 1->2->3->4, you should return the list as 2->1->4->3.
                                                                                                  -
                                                                                                  -

                                                                                                  Note:

                                                                                                  -
                                                                                                    -
                                                                                                  • Your algorithm should use only constant extra space.
                                                                                                  • -
                                                                                                  • You may not modify the values in the list's nodes, only nodes itself may be changed.
                                                                                                  • -
                                                                                                  -

                                                                                                  Solution

                                                                                                  -
                                                                                                  /**
                                                                                                  - * Definition for singly-linked list.
                                                                                                  - * function ListNode(val) {
                                                                                                  - *     this.val = val;
                                                                                                  - *     this.next = null;
                                                                                                  - * }
                                                                                                  - */
                                                                                                  -/**
                                                                                                  - * @param {ListNode} head
                                                                                                  - * @return {ListNode}
                                                                                                  - */
                                                                                                  -var swapPairs = function(head) {
                                                                                                  -  var out = new ListNode(0);
                                                                                                  -  var now = out;
                                                                                                  -
                                                                                                  -  out.next = head;
                                                                                                  -
                                                                                                  -  while (now.next && now.next.next) {
                                                                                                  -    now = swap(now, now.next, now.next.next);
                                                                                                  -  }
                                                                                                  -
                                                                                                  -  return out.next;
                                                                                                  -};
                                                                                                  -
                                                                                                  -var swap = function (a, b, c) {
                                                                                                  -  a.next = c;
                                                                                                  -  b.next = c.next;
                                                                                                  -  c.next = b;
                                                                                                  -  return b;
                                                                                                  -};
                                                                                                  -
                                                                                                  -

                                                                                                  Explain:

                                                                                                  -

                                                                                                  nope.

                                                                                                  -

                                                                                                  Complexity:

                                                                                                  -
                                                                                                    -
                                                                                                  • Time complexity : O(n).
                                                                                                  • -
                                                                                                  • Space complexity : O(1).
                                                                                                  • -
                                                                                                  github
                                                                                                  \ No newline at end of file diff --git a/docs/problem/symmetric-tree.html b/docs/problem/symmetric-tree.html deleted file mode 100644 index f081f01..0000000 --- a/docs/problem/symmetric-tree.html +++ /dev/null @@ -1,92 +0,0 @@ -Symmetric Tree - LeetCode javascript solutions

                                                                                                  101. Symmetric Tree

                                                                                                  Difficulty:
                                                                                                  Similar Questions:

                                                                                                    Problem

                                                                                                    -

                                                                                                    Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

                                                                                                    -

                                                                                                    For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

                                                                                                    -
                                                                                                    1
                                                                                                    -   / \
                                                                                                    -  2   2
                                                                                                    - / \ / \
                                                                                                    -3  4 4  3
                                                                                                    -
                                                                                                    -

                                                                                                    But the following [1,2,2,null,3,null,3] is not:

                                                                                                    -
                                                                                                    1
                                                                                                    -   / \
                                                                                                    -  2   2
                                                                                                    -   \   \
                                                                                                    -   3    3
                                                                                                    -
                                                                                                    -

                                                                                                    Note: -Bonus points if you could solve it both recursively and iteratively.

                                                                                                    -

                                                                                                    Solution 1

                                                                                                    -
                                                                                                    /**
                                                                                                    - * Definition for a binary tree node.
                                                                                                    - * function TreeNode(val) {
                                                                                                    - *     this.val = val;
                                                                                                    - *     this.left = this.right = null;
                                                                                                    - * }
                                                                                                    - */
                                                                                                    -/**
                                                                                                    - * @param {TreeNode} root
                                                                                                    - * @return {boolean}
                                                                                                    - */
                                                                                                    -var isSymmetric = function(root) {
                                                                                                    -  if (!root) return true;
                                                                                                    -  return helper(root.left, root.right);
                                                                                                    -};
                                                                                                    -
                                                                                                    -var helper = function (p, q) {
                                                                                                    -  if ((!p && q) || (p && !q) || (p && q && p.val !== q.val)) return false;
                                                                                                    -  if (p && q) return helper(p.left, q.right) && helper(p.right, q.left);
                                                                                                    -  return true;
                                                                                                    -};
                                                                                                    -
                                                                                                    -

                                                                                                    Explain:

                                                                                                    -

                                                                                                    nope.

                                                                                                    -

                                                                                                    Complexity:

                                                                                                    -
                                                                                                      -
                                                                                                    • Time complexity : O(n).
                                                                                                    • -
                                                                                                    • Space complexity : O(1).
                                                                                                    • -
                                                                                                    -

                                                                                                    Solution 2

                                                                                                    -
                                                                                                    /**
                                                                                                    - * Definition for a binary tree node.
                                                                                                    - * function TreeNode(val) {
                                                                                                    - *     this.val = val;
                                                                                                    - *     this.left = this.right = null;
                                                                                                    - * }
                                                                                                    - */
                                                                                                    -/**
                                                                                                    - * @param {TreeNode} root
                                                                                                    - * @return {boolean}
                                                                                                    - */
                                                                                                    -var isSymmetric = function(root) {
                                                                                                    -  if (!root) return true;
                                                                                                    -
                                                                                                    -  var p = [root.left];
                                                                                                    -  var q = [root.right];
                                                                                                    -  var ll = null;
                                                                                                    -  var rr = null;
                                                                                                    -
                                                                                                    -  while (p.length && q.length) {
                                                                                                    -    ll = p.pop();
                                                                                                    -    rr = q.pop();
                                                                                                    -
                                                                                                    -    if (!ll && !rr) continue;
                                                                                                    -    if (!ll || !rr) return false;
                                                                                                    -    if (ll.val !== rr.val) return false;
                                                                                                    -
                                                                                                    -    p.push(ll.left);
                                                                                                    -    p.push(ll.right);
                                                                                                    -    q.push(rr.right);
                                                                                                    -    q.push(rr.left);
                                                                                                    -  }
                                                                                                    -
                                                                                                    -  return true;
                                                                                                    -};
                                                                                                    -
                                                                                                    -

                                                                                                    Explain:

                                                                                                    -

                                                                                                    nope.

                                                                                                    -

                                                                                                    Complexity:

                                                                                                    -
                                                                                                      -
                                                                                                    • Time complexity : O(n).
                                                                                                    • -
                                                                                                    • Space complexity : O(n).
                                                                                                    • -
                                                                                                    github
                                                                                                    \ No newline at end of file diff --git a/docs/problem/text-justification.html b/docs/problem/text-justification.html deleted file mode 100644 index 4bc4c21..0000000 --- a/docs/problem/text-justification.html +++ /dev/null @@ -1,113 +0,0 @@ -Text Justification - LeetCode javascript solutions

                                                                                                    68. Text Justification

                                                                                                    Difficulty:
                                                                                                    Related Topics:
                                                                                                    Similar Questions:

                                                                                                      Problem

                                                                                                      -

                                                                                                      Given an array of words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified.

                                                                                                      -

                                                                                                      You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters.

                                                                                                      -

                                                                                                      Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.

                                                                                                      -

                                                                                                      For the last line of text, it should be left justified and no extra space is inserted between words.

                                                                                                      -

                                                                                                      Note:

                                                                                                      -
                                                                                                        -
                                                                                                      • A word is defined as a character sequence consisting of non-space characters only.
                                                                                                      • -
                                                                                                      • Each word's length is guaranteed to be greater than 0 and not exceed maxWidth.
                                                                                                      • -
                                                                                                      • The input array words contains at least one word.
                                                                                                      • -
                                                                                                      -

                                                                                                      Example 1:

                                                                                                      -
                                                                                                      Input:
                                                                                                      -words = ["This", "is", "an", "example", "of", "text", "justification."]
                                                                                                      -maxWidth = 16
                                                                                                      -Output:
                                                                                                      -[
                                                                                                      -   "This    is    an",
                                                                                                      -   "example  of text",
                                                                                                      -   "justification.  "
                                                                                                      -]
                                                                                                      -
                                                                                                      -

                                                                                                      Example 2:

                                                                                                      -
                                                                                                      Input:
                                                                                                      -words = ["What","must","be","acknowledgment","shall","be"]
                                                                                                      -maxWidth = 16
                                                                                                      -Output:
                                                                                                      -[
                                                                                                      -  "What   must   be",
                                                                                                      -  "acknowledgment  ",
                                                                                                      -  "shall be        "
                                                                                                      -]
                                                                                                      -Explanation: Note that the last line is "shall be    " instead of "shall     be",
                                                                                                      -             because the last line must be left-justified instead of fully-justified.
                                                                                                      -             Note that the second line is also left-justified becase it contains only one word.
                                                                                                      -
                                                                                                      -

                                                                                                      Example 3:

                                                                                                      -
                                                                                                      Input:
                                                                                                      -words = ["Science","is","what","we","understand","well","enough","to","explain",
                                                                                                      -         "to","a","computer.","Art","is","everything","else","we","do"]
                                                                                                      -maxWidth = 20
                                                                                                      -Output:
                                                                                                      -[
                                                                                                      -  "Science  is  what we",
                                                                                                      -  "understand      well",
                                                                                                      -  "enough to explain to",
                                                                                                      -  "a  computer.  Art is",
                                                                                                      -  "everything  else  we",
                                                                                                      -  "do                  "
                                                                                                      -]
                                                                                                      -
                                                                                                      -

                                                                                                      Solution

                                                                                                      -
                                                                                                      /**
                                                                                                      - * @param {string[]} words
                                                                                                      - * @param {number} maxWidth
                                                                                                      - * @return {string[]}
                                                                                                      - */
                                                                                                      -var fullJustify = function(words, maxWidth) {
                                                                                                      -  var len = words.length;
                                                                                                      -  var arr = [];
                                                                                                      -  var width = 0;
                                                                                                      -  var item = null;
                                                                                                      -  var addLen = 0;
                                                                                                      -  var res = [];
                                                                                                      -
                                                                                                      -  for (var i = 0; i < len; i++) {
                                                                                                      -    item = words[i];
                                                                                                      -    addLen = width === 0 ? item.length : (item.length + 1);
                                                                                                      -
                                                                                                      -    if (width + addLen > maxWidth) {
                                                                                                      -      res.push(helper(arr, maxWidth - width, false));
                                                                                                      -      arr = [];
                                                                                                      -      width = 0;
                                                                                                      -      addLen = item.length;
                                                                                                      -    }
                                                                                                      -
                                                                                                      -    arr.push(item);
                                                                                                      -    width += addLen;
                                                                                                      -  }
                                                                                                      -
                                                                                                      -  res.push(helper(arr, maxWidth - width, true));
                                                                                                      -
                                                                                                      -  return res;
                                                                                                      -};
                                                                                                      -
                                                                                                      -var helper = function (arr, left, isLast) {
                                                                                                      -  var len = arr.length;
                                                                                                      -  var num = 0;
                                                                                                      -  var rem = 0;
                                                                                                      -  var res = '';
                                                                                                      -
                                                                                                      -  if (len === 1 || isLast) {
                                                                                                      -    return arr.join(' ') + ' '.repeat(left);
                                                                                                      -  }
                                                                                                      -
                                                                                                      -  num = Math.floor(left / (len - 1));
                                                                                                      -  rem = left % (len - 1);
                                                                                                      -  for (var i = 0; i < len; i++) {
                                                                                                      -    res += arr[i];
                                                                                                      -    if (i < len - 1) res += ' '.repeat(num + 1);
                                                                                                      -    if (i < rem) res += ' ';
                                                                                                      -  }
                                                                                                      -
                                                                                                      -  return res;
                                                                                                      -};
                                                                                                      -
                                                                                                      -

                                                                                                      Explain:

                                                                                                      -

                                                                                                      nope.

                                                                                                      -

                                                                                                      Complexity:

                                                                                                      -
                                                                                                        -
                                                                                                      • Time complexity : O(n).
                                                                                                      • -
                                                                                                      • Space complexity : O(n).
                                                                                                      • -
                                                                                                      github
                                                                                                      \ No newline at end of file diff --git a/docs/problem/trapping-rain-water.html b/docs/problem/trapping-rain-water.html deleted file mode 100644 index ad9c5f5..0000000 --- a/docs/problem/trapping-rain-water.html +++ /dev/null @@ -1,44 +0,0 @@ -Trapping Rain Water - LeetCode javascript solutions

                                                                                                      42. Trapping Rain Water

                                                                                                      Difficulty:
                                                                                                      Related Topics:

                                                                                                      Problem

                                                                                                      -

                                                                                                      Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.

                                                                                                      -

                                                                                                      -

                                                                                                      The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!

                                                                                                      -

                                                                                                      Example:

                                                                                                      -
                                                                                                      Input: [0,1,0,2,1,0,1,3,2,1,2,1]
                                                                                                      -Output: 6
                                                                                                      -
                                                                                                      -

                                                                                                      Solution

                                                                                                      -
                                                                                                      var trap = function(height) {
                                                                                                      -  var res = 0;
                                                                                                      -  var left = 0;
                                                                                                      -  var right = height.length - 1;
                                                                                                      -  var leftMax = 0;
                                                                                                      -  var rightMax = 0;
                                                                                                      -
                                                                                                      -  while (left < right) {
                                                                                                      -    if (height[left] < height[right]) {
                                                                                                      -      if (height[left] >= leftMax) {
                                                                                                      -        leftMax = height[left];
                                                                                                      -      } else {
                                                                                                      -        res += leftMax - height[left];
                                                                                                      -      }
                                                                                                      -      left++;
                                                                                                      -    } else {
                                                                                                      -      if (height[right] >= rightMax) {
                                                                                                      -        rightMax = height[right];
                                                                                                      -      } else {
                                                                                                      -        res += rightMax - height[right];
                                                                                                      -      }
                                                                                                      -      right--;
                                                                                                      -    }
                                                                                                      -  }
                                                                                                      -
                                                                                                      -  return res;
                                                                                                      -};
                                                                                                      -
                                                                                                      -

                                                                                                      Explain:

                                                                                                      -

                                                                                                      双指针

                                                                                                      -

                                                                                                      Complexity:

                                                                                                      -
                                                                                                        -
                                                                                                      • Time complexity : O(n).
                                                                                                      • -
                                                                                                      • Space complexity : O(1).
                                                                                                      • -
                                                                                                      github
                                                                                                      \ No newline at end of file diff --git a/docs/problem/triangle.html b/docs/problem/triangle.html deleted file mode 100644 index 974676c..0000000 --- a/docs/problem/triangle.html +++ /dev/null @@ -1,65 +0,0 @@ -Triangle - LeetCode javascript solutions

                                                                                                      120. Triangle

                                                                                                      Difficulty:
                                                                                                      Similar Questions:

                                                                                                        Problem

                                                                                                        -

                                                                                                        Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.

                                                                                                        -

                                                                                                        For example, given the following triangle

                                                                                                        -
                                                                                                        [
                                                                                                        -     [2],
                                                                                                        -    [3,4],
                                                                                                        -   [6,5,7],
                                                                                                        -  [4,1,8,3]
                                                                                                        -]
                                                                                                        -
                                                                                                        -

                                                                                                        The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).

                                                                                                        -

                                                                                                        Note:

                                                                                                        -

                                                                                                        Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.

                                                                                                        -

                                                                                                        Solution

                                                                                                        -
                                                                                                        /**
                                                                                                        - * @param {number[][]} triangle
                                                                                                        - * @return {number}
                                                                                                        - */
                                                                                                        -var minimumTotal = function(triangle) {
                                                                                                        -  var len = triangle.length;
                                                                                                        -  var len2 = 0;
                                                                                                        -  var res = Number.MAX_SAFE_INTEGER;
                                                                                                        -  var dp = Array(len);
                                                                                                        -
                                                                                                        -  for (var i = 0; i < len; i++) {
                                                                                                        -    len2 = triangle[i].length;
                                                                                                        -    dp[i] = Array(len2).fill(0);
                                                                                                        -    for (var j = 0; j < len2; j++) {
                                                                                                        -      dp[i][j] = getMinParent(dp, i, j) + triangle[i][j];
                                                                                                        -      if (i === (len - 1)) res = Math.min(res, dp[i][j]);
                                                                                                        -    }
                                                                                                        -  }
                                                                                                        -
                                                                                                        -  return res === Number.MAX_SAFE_INTEGER ? 0 : res;
                                                                                                        -};
                                                                                                        -
                                                                                                        -var getMinParent = function (dp, i, j) {
                                                                                                        -  var left = 0;
                                                                                                        -  var right = 0;
                                                                                                        -
                                                                                                        -  if (i === 0) return 0;
                                                                                                        -
                                                                                                        -  if (j === 0) left = Number.MAX_SAFE_INTEGER;
                                                                                                        -  else left = dp[i - 1][j - 1];
                                                                                                        -
                                                                                                        -  if (j === dp[i - 1].length) right = Number.MAX_SAFE_INTEGER;
                                                                                                        -  else right = dp[i - 1][j];
                                                                                                        -
                                                                                                        -  return Math.min(left, right);
                                                                                                        -};
                                                                                                        -
                                                                                                        -

                                                                                                        Explain:

                                                                                                        -

                                                                                                        动态规划:

                                                                                                        -

                                                                                                        dp[i][j] 记录到达 ij 列的点的最小和

                                                                                                        -
                                                                                                          -
                                                                                                        1. 每个点可以由上一行的两个点(或只有一个点)到达,它的值只与这两个点有关
                                                                                                        2. -
                                                                                                        3. 到达某个点的最小和 = min(上一行左边点最小和, 上一行右边点最小和) + 当前点的数值
                                                                                                        4. -
                                                                                                        5. 最后找出最后一行的最小值就好
                                                                                                        6. -
                                                                                                        -

                                                                                                        优化:其实dp只要保留上一行的值就好,我这里保留了所有行的值,可以用滚动数组

                                                                                                        -

                                                                                                        Complexity:

                                                                                                        -
                                                                                                          -
                                                                                                        • Time complexity : O(m*n).
                                                                                                        • -
                                                                                                        • Space complexity : O(m*n).
                                                                                                        • -
                                                                                                        github
                                                                                                        \ No newline at end of file diff --git a/docs/problem/trim-a-binary-search-tree.html b/docs/problem/trim-a-binary-search-tree.html deleted file mode 100644 index e8a3969..0000000 --- a/docs/problem/trim-a-binary-search-tree.html +++ /dev/null @@ -1,66 +0,0 @@ -Trim a Binary Search Tree - LeetCode javascript solutions

                                                                                                        669. Trim a Binary Search Tree

                                                                                                        Difficulty:
                                                                                                        Related Topics:
                                                                                                        Similar Questions:

                                                                                                          Problem

                                                                                                          -

                                                                                                          Given a binary search tree and the lowest and highest boundaries as L and R, trim the tree so that all its elements lies in [L, R] (R >= L). You might need to change the root of the tree, so the result should return the new root of the trimmed binary search tree.

                                                                                                          -

                                                                                                          Example 1:

                                                                                                          -
                                                                                                          Input: 
                                                                                                          -    1
                                                                                                          -   / \
                                                                                                          -  0   2
                                                                                                          -
                                                                                                          -  L = 1
                                                                                                          -  R = 2
                                                                                                          -
                                                                                                          -Output: 
                                                                                                          -    1
                                                                                                          -      \
                                                                                                          -       2
                                                                                                          -
                                                                                                          -

                                                                                                          Example 2:

                                                                                                          -
                                                                                                          Input: 
                                                                                                          -    3
                                                                                                          -   / \
                                                                                                          -  0   4
                                                                                                          -   \
                                                                                                          -    2
                                                                                                          -   /
                                                                                                          -  1
                                                                                                          -
                                                                                                          -  L = 1
                                                                                                          -  R = 3
                                                                                                          -
                                                                                                          -Output: 
                                                                                                          -      3
                                                                                                          -     / 
                                                                                                          -   2   
                                                                                                          -  /
                                                                                                          - 1
                                                                                                          -
                                                                                                          -

                                                                                                          Solution

                                                                                                          -
                                                                                                          /**
                                                                                                          - * Definition for a binary tree node.
                                                                                                          - * function TreeNode(val) {
                                                                                                          - *     this.val = val;
                                                                                                          - *     this.left = this.right = null;
                                                                                                          - * }
                                                                                                          - */
                                                                                                          -/**
                                                                                                          - * @param {TreeNode} root
                                                                                                          - * @param {number} L
                                                                                                          - * @param {number} R
                                                                                                          - * @return {TreeNode}
                                                                                                          - */
                                                                                                          -var trimBST = function(root, L, R) {
                                                                                                          -  if (!root) return null;
                                                                                                          -  if (root.val < L) return trimBST(root.right, L, R);
                                                                                                          -  if (root.val > R) return trimBST(root.left, L, R);
                                                                                                          -  root.left = trimBST(root.left, L, R);
                                                                                                          -  root.right = trimBST(root.right, L, R);
                                                                                                          -  return root;
                                                                                                          -};
                                                                                                          -
                                                                                                          -

                                                                                                          Explain:

                                                                                                          -

                                                                                                          nope.

                                                                                                          -

                                                                                                          Complexity:

                                                                                                          -
                                                                                                            -
                                                                                                          • Time complexity : O(n).
                                                                                                          • -
                                                                                                          • Space complexity : O(1).
                                                                                                          • -
                                                                                                          github
                                                                                                          \ No newline at end of file diff --git a/docs/problem/two-sum-ii-input-array-is-sorted.html b/docs/problem/two-sum-ii-input-array-is-sorted.html deleted file mode 100644 index 8229b80..0000000 --- a/docs/problem/two-sum-ii-input-array-is-sorted.html +++ /dev/null @@ -1,42 +0,0 @@ -Two Sum II - Input array is sorted - LeetCode javascript solutions

                                                                                                          167. Two Sum II - Input array is sorted

                                                                                                          Difficulty:

                                                                                                          Problem

                                                                                                          -

                                                                                                          Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

                                                                                                          -

                                                                                                          The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.

                                                                                                          -

                                                                                                          Note:

                                                                                                          -
                                                                                                            -
                                                                                                          • Your returned answers (both index1 and index2) are not zero-based.
                                                                                                          • -
                                                                                                          • You may assume that each input would have exactly one solution and you may not use the same element twice.
                                                                                                          • -
                                                                                                          -

                                                                                                          Example:

                                                                                                          -
                                                                                                          Input: numbers = [2,7,11,15], target = 9
                                                                                                          -Output: [1,2]
                                                                                                          -Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
                                                                                                          -
                                                                                                          -

                                                                                                          Solution 1

                                                                                                          -
                                                                                                          /**
                                                                                                          - * @param {number[]} numbers
                                                                                                          - * @param {number} target
                                                                                                          - * @return {number[]}
                                                                                                          - */
                                                                                                          -var twoSum = function(numbers, target) {
                                                                                                          -  var sum = 0;
                                                                                                          -  var left = 0;
                                                                                                          -  var right = numbers.length - 1;
                                                                                                          -  while (left < right) {
                                                                                                          -    sum = numbers[left] + numbers[right];
                                                                                                          -    if (sum === target) {
                                                                                                          -      return [left + 1, right + 1];
                                                                                                          -    } else if (sum > target) {
                                                                                                          -      right--;
                                                                                                          -    } else {
                                                                                                          -      left++;
                                                                                                          -    }
                                                                                                          -  }
                                                                                                          -};
                                                                                                          -
                                                                                                          -

                                                                                                          Explain:

                                                                                                          -

                                                                                                          nope.

                                                                                                          -

                                                                                                          Complexity:

                                                                                                          -
                                                                                                            -
                                                                                                          • Time complexity : O(n).
                                                                                                          • -
                                                                                                          • Space complexity : O(1).
                                                                                                          • -
                                                                                                          github
                                                                                                          \ No newline at end of file diff --git a/docs/problem/two-sum.html b/docs/problem/two-sum.html deleted file mode 100644 index e0795dc..0000000 --- a/docs/problem/two-sum.html +++ /dev/null @@ -1,31 +0,0 @@ -Two Sum - LeetCode javascript solutions

                                                                                                          1. Two Sum

                                                                                                          Difficulty:
                                                                                                          Related Topics:

                                                                                                          Problem

                                                                                                          -

                                                                                                          Given an array of integers, return indices of the two numbers such that they add up to a specific target.

                                                                                                          -

                                                                                                          You may assume that each input would have exactly one solution, and you may not use the same element twice.

                                                                                                          -

                                                                                                          Example:

                                                                                                          -
                                                                                                          Given nums = [2, 7, 11, 15], target = 9,
                                                                                                          -Because nums[0] + nums[1] = 2 + 7 = 9,
                                                                                                          -return [0, 1].
                                                                                                          -
                                                                                                          -

                                                                                                          Solution

                                                                                                          -
                                                                                                          /**
                                                                                                          - * @param {number[]} nums
                                                                                                          - * @param {number} target
                                                                                                          - * @return {number[]}
                                                                                                          - */
                                                                                                          -var twoSum = function(nums, target) {
                                                                                                          -  var hash = {};
                                                                                                          -  var len = nums.length;
                                                                                                          -  for (var i = 0; i < len; i++) {
                                                                                                          -    if (nums[i] in hash) return [hash[nums[i]], i];
                                                                                                          -    hash[target - nums[i]] = i
                                                                                                          -  }
                                                                                                          -  return [-1, -1];
                                                                                                          -};
                                                                                                          -
                                                                                                          -

                                                                                                          Explain:

                                                                                                          -

                                                                                                          nope.

                                                                                                          -

                                                                                                          Complexity:

                                                                                                          -
                                                                                                            -
                                                                                                          • Time complexity : O(n).
                                                                                                          • -
                                                                                                          • Space complexity : O(n).
                                                                                                          • -
                                                                                                          github
                                                                                                          \ No newline at end of file diff --git a/docs/problem/ugly-number-ii.html b/docs/problem/ugly-number-ii.html deleted file mode 100644 index acc4eb2..0000000 --- a/docs/problem/ugly-number-ii.html +++ /dev/null @@ -1,46 +0,0 @@ -Ugly Number II - LeetCode javascript solutions

                                                                                                          264. Ugly Number II

                                                                                                          Difficulty:

                                                                                                          Problem

                                                                                                          -

                                                                                                          Write a program to find the n-th ugly number.

                                                                                                          -

                                                                                                          Ugly numbers are** positive numbers** whose prime factors only include 2, 3, 5.

                                                                                                          -

                                                                                                          Example:

                                                                                                          -
                                                                                                          Input: n = 10
                                                                                                          -Output: 12
                                                                                                          -Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.
                                                                                                          -
                                                                                                          -

                                                                                                          **Note: **

                                                                                                          -
                                                                                                            -
                                                                                                          • 1 is typically treated as an ugly number.
                                                                                                          • -
                                                                                                          • n does not exceed 1690.
                                                                                                          • -
                                                                                                          -

                                                                                                          Solution

                                                                                                          -
                                                                                                          /**
                                                                                                          - * @param {number} n
                                                                                                          - * @return {number}
                                                                                                          - */
                                                                                                          -var nthUglyNumber = function(n) {
                                                                                                          -  if (n < 1) return 0;
                                                                                                          -
                                                                                                          -  var dp = [1];
                                                                                                          -  var t2 = 0;
                                                                                                          -  var t3 = 0;
                                                                                                          -  var t5 = 0;
                                                                                                          -
                                                                                                          -  for (var i = 1; i < n; i++) {
                                                                                                          -    dp[i] = Math.min(dp[t2] * 2, dp[t3] * 3, dp[t5] * 5);
                                                                                                          -    if(dp[i] === dp[t2]*2) t2++; 
                                                                                                          -    if(dp[i] === dp[t3]*3) t3++;
                                                                                                          -    if(dp[i] === dp[t5]*5) t5++;
                                                                                                          -  }
                                                                                                          -
                                                                                                          -  return dp[n - 1];
                                                                                                          -};
                                                                                                          -
                                                                                                          -

                                                                                                          Explain:

                                                                                                          -
                                                                                                            -
                                                                                                          1. 除了 1,其它结果都是以前的结果乘 2, 3, 5 得来的;
                                                                                                          2. -
                                                                                                          3. dp[i] = min(dp[t2] * 2, dp[t3] * 3, dp[t5] * 5)t2, t3, t5 是上一次乘 2, 3, 5 的时候;
                                                                                                          4. -
                                                                                                          -

                                                                                                          Complexity:

                                                                                                          -
                                                                                                            -
                                                                                                          • Time complexity : O(n).
                                                                                                          • -
                                                                                                          • Space complexity : O(n).
                                                                                                          • -
                                                                                                          github
                                                                                                          \ No newline at end of file diff --git a/docs/problem/ugly-number.html b/docs/problem/ugly-number.html deleted file mode 100644 index 9f65e20..0000000 --- a/docs/problem/ugly-number.html +++ /dev/null @@ -1,50 +0,0 @@ -Ugly Number - LeetCode javascript solutions

                                                                                                          263. Ugly Number

                                                                                                          Difficulty:
                                                                                                          Related Topics:

                                                                                                          Problem

                                                                                                          -

                                                                                                          Write a program to check whether a given number is an ugly number.

                                                                                                          -

                                                                                                          Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.

                                                                                                          -

                                                                                                          Example 1:

                                                                                                          -
                                                                                                          Input: 6
                                                                                                          -Output: true
                                                                                                          -Explanation: 6 = 2 × 3
                                                                                                          -
                                                                                                          -

                                                                                                          Example 2:

                                                                                                          -
                                                                                                          Input: 8
                                                                                                          -Output: true
                                                                                                          -Explanation: 8 = 2 × 2 × 2
                                                                                                          -
                                                                                                          -

                                                                                                          Example 3:

                                                                                                          -
                                                                                                          Input: 14
                                                                                                          -Output: false 
                                                                                                          -Explanation: 14 is not ugly since it includes another prime factor 7.
                                                                                                          -
                                                                                                          -

                                                                                                          Note:

                                                                                                          -
                                                                                                            -
                                                                                                          • 1 is typically treated as an ugly number.
                                                                                                          • -
                                                                                                          • Input is within the 32-bit signed integer range: [−231, 231 − 1].
                                                                                                          • -
                                                                                                          -

                                                                                                          Solution

                                                                                                          -
                                                                                                          /**
                                                                                                          - * @param {number} num
                                                                                                          - * @return {boolean}
                                                                                                          - */
                                                                                                          -var isUgly = function(num) {
                                                                                                          -  if (num < 1) return false;
                                                                                                          -  if (num === 1) return true;
                                                                                                          -
                                                                                                          -  var divisor = [2, 3, 5];
                                                                                                          -
                                                                                                          -  for (var i = 0; i < divisor.length; i++) {
                                                                                                          -    while (num && num % divisor[i] === 0) {
                                                                                                          -      num = Math.floor(num / divisor[i]);
                                                                                                          -    }
                                                                                                          -  }
                                                                                                          -
                                                                                                          -  return num === 1;
                                                                                                          -};
                                                                                                          -
                                                                                                          -

                                                                                                          Explain:

                                                                                                          -

                                                                                                          nope.

                                                                                                          -

                                                                                                          Complexity:

                                                                                                          -
                                                                                                            -
                                                                                                          • Time complexity : O(log(n)).
                                                                                                          • -
                                                                                                          • Space complexity : O(1).
                                                                                                          • -
                                                                                                          github
                                                                                                          \ No newline at end of file diff --git a/docs/problem/unique-binary-search-trees-ii.html b/docs/problem/unique-binary-search-trees-ii.html deleted file mode 100644 index dda75f9..0000000 --- a/docs/problem/unique-binary-search-trees-ii.html +++ /dev/null @@ -1,65 +0,0 @@ -Unique Binary Search Trees II - LeetCode javascript solutions

                                                                                                          95. Unique Binary Search Trees II

                                                                                                          Difficulty:

                                                                                                          Problem

                                                                                                          -

                                                                                                          Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 … n.

                                                                                                          -

                                                                                                          Example:

                                                                                                          -
                                                                                                          Input: 3
                                                                                                          -Output:
                                                                                                          -[
                                                                                                          -  [1,null,3,2],
                                                                                                          -  [3,2,null,1],
                                                                                                          -  [3,1,null,null,2],
                                                                                                          -  [2,1,3],
                                                                                                          -  [1,null,2,null,3]
                                                                                                          -]
                                                                                                          -Explanation:
                                                                                                          -The above output corresponds to the 5 unique BST's shown below:
                                                                                                          -
                                                                                                          -   1         3     3      2      1
                                                                                                          -    \       /     /      / \      \
                                                                                                          -     3     2     1      1   3      2
                                                                                                          -    /     /       \                 \
                                                                                                          -   2     1         2                 3
                                                                                                          -
                                                                                                          -

                                                                                                          Solution

                                                                                                          -
                                                                                                          /**
                                                                                                          - * Definition for a binary tree node.
                                                                                                          - * function TreeNode(val) {
                                                                                                          - *     this.val = val;
                                                                                                          - *     this.left = this.right = null;
                                                                                                          - * }
                                                                                                          - */
                                                                                                          -/**
                                                                                                          - * @param {number} n
                                                                                                          - * @return {TreeNode[]}
                                                                                                          - */
                                                                                                          -var generateTrees = function(n) {
                                                                                                          -  if (n < 1) return [];
                                                                                                          -  return generate(1, n);
                                                                                                          -};
                                                                                                          -
                                                                                                          -var generate = function (l, r) {
                                                                                                          -  var nodes = [];
                                                                                                          -  var node = null;
                                                                                                          -  var left = [];
                                                                                                          -  var right = [];
                                                                                                          -  for (var i = l; i <= r; i++) {
                                                                                                          -    left = generate(l, i - 1);
                                                                                                          -    right = generate(i + 1, r);
                                                                                                          -    for (var j = 0; j < left.length; j++) {
                                                                                                          -      for (var k = 0; k < right.length; k++) {
                                                                                                          -        node = new TreeNode(i);
                                                                                                          -        node.left = left[j];
                                                                                                          -        node.right = right[k];
                                                                                                          -        nodes.push(node);
                                                                                                          -      }
                                                                                                          -    }
                                                                                                          -  }
                                                                                                          -  return nodes.length ? nodes : [null];
                                                                                                          -};
                                                                                                          -
                                                                                                          -

                                                                                                          Explain:

                                                                                                          -

                                                                                                          例如:有 5 个节点,选取其中 1 个作为 root,还剩 4 个。则左右可分为 (0, 4), (1, 3), (2, 2), (3, 1), (4, 0) 等几种情况,左右的分配用递归得到即可。

                                                                                                          -

                                                                                                          Complexity:

                                                                                                          -
                                                                                                            -
                                                                                                          • Time complexity :
                                                                                                          • -
                                                                                                          • Space complexity :
                                                                                                          • -
                                                                                                          github
                                                                                                          \ No newline at end of file diff --git a/docs/problem/unique-binary-search-trees.html b/docs/problem/unique-binary-search-trees.html deleted file mode 100644 index b3512bb..0000000 --- a/docs/problem/unique-binary-search-trees.html +++ /dev/null @@ -1,37 +0,0 @@ -Unique Binary Search Trees - LeetCode javascript solutions

                                                                                                          96. Unique Binary Search Trees

                                                                                                          Difficulty:

                                                                                                          Problem

                                                                                                          -

                                                                                                          Given n, how many structurally unique BST's (binary search trees) that store values 1 … n?

                                                                                                          -

                                                                                                          Example:

                                                                                                          -
                                                                                                          Input: 3
                                                                                                          -Output: 5
                                                                                                          -Explanation:
                                                                                                          -Given n = 3, there are a total of 5 unique BST's:
                                                                                                          -
                                                                                                          -   1         3     3      2      1
                                                                                                          -    \       /     /      / \      \
                                                                                                          -     3     2     1      1   3      2
                                                                                                          -    /     /       \                 \
                                                                                                          -   2     1         2                 3
                                                                                                          -
                                                                                                          -

                                                                                                          Solution

                                                                                                          -
                                                                                                          /**
                                                                                                          - * @param {number} n
                                                                                                          - * @return {number}
                                                                                                          - */
                                                                                                          -var numTrees = function(n) {
                                                                                                          -  var dp = [1, 1];
                                                                                                          -  for (i = 2; i <= n; i++) {
                                                                                                          -    dp[i] = 0;
                                                                                                          -    for (j = 1; j <= i; j++) {
                                                                                                          -      dp[i] += dp[i - j] * dp[j - 1];
                                                                                                          -    }
                                                                                                          -  }
                                                                                                          -  return dp[n];
                                                                                                          -};
                                                                                                          -
                                                                                                          -

                                                                                                          Explain:

                                                                                                          -

                                                                                                          例如:有 3 个节点,取 1 个作为 root,还剩 2 个。可以左边 0 个,右边 2 个;左边 1 个,右边 1 个;左边 2 个,右边 0 个。即:F(3) = F(0) * F(2) + F(1) * F(1) + F(2) * F(0)。其中 F(0) = F(1) = 1

                                                                                                          -

                                                                                                          Complexity:

                                                                                                          -
                                                                                                            -
                                                                                                          • Time complexity :
                                                                                                          • -
                                                                                                          • Space complexity :
                                                                                                          • -
                                                                                                          github
                                                                                                          \ No newline at end of file diff --git a/docs/problem/unique-paths-ii.html b/docs/problem/unique-paths-ii.html deleted file mode 100644 index 34a4265..0000000 --- a/docs/problem/unique-paths-ii.html +++ /dev/null @@ -1,62 +0,0 @@ -Unique Paths II - LeetCode javascript solutions

                                                                                                          63. Unique Paths II

                                                                                                          Difficulty:
                                                                                                          Similar Questions:

                                                                                                          Problem

                                                                                                          -

                                                                                                          A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).

                                                                                                          -

                                                                                                          The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).

                                                                                                          -

                                                                                                          Now consider if some obstacles are added to the grids. How many unique paths would there be?

                                                                                                          -

                                                                                                          -

                                                                                                          An obstacle and empty space is marked as 1 and 0 respectively in the grid.

                                                                                                          -

                                                                                                          Note: m and n will be at most 100.

                                                                                                          -

                                                                                                          Example 1:

                                                                                                          -
                                                                                                          Input:
                                                                                                          -[
                                                                                                          -  [0,0,0],
                                                                                                          -  [0,1,0],
                                                                                                          -  [0,0,0]
                                                                                                          -]
                                                                                                          -Output: 2
                                                                                                          -Explanation:
                                                                                                          -There is one obstacle in the middle of the 3x3 grid above.
                                                                                                          -There are two ways to reach the bottom-right corner:
                                                                                                          -1. Right -> Right -> Down -> Down
                                                                                                          -2. Down -> Down -> Right -> Right
                                                                                                          -
                                                                                                          -

                                                                                                          Solution

                                                                                                          -
                                                                                                          /**
                                                                                                          - * @param {number[][]} obstacleGrid
                                                                                                          - * @return {number}
                                                                                                          - */
                                                                                                          -var uniquePathsWithObstacles = function(obstacleGrid) {
                                                                                                          -  var m = obstacleGrid.length;
                                                                                                          -  var n = (obstacleGrid[0] || []).length;
                                                                                                          -  var dp = Array(m);
                                                                                                          -  var left = 0;
                                                                                                          -  var top = 0;
                                                                                                          -
                                                                                                          -  if (!m || !n) return 0;
                                                                                                          -
                                                                                                          -  for (var i = 0; i < m; i++) {
                                                                                                          -    dp[i] = Array(n);
                                                                                                          -    for (var j = 0; j < n; j++) {
                                                                                                          -      left = (j === 0 || obstacleGrid[i][j - 1] === 1) ? 0 : dp[i][j - 1];
                                                                                                          -      top = (i === 0 || obstacleGrid[i - 1][j] === 1) ? 0 : dp[i - 1][j];
                                                                                                          -      dp[i][j] = obstacleGrid[i][j] === 1 ? 0 : ((i === 0 && j === 0) ? 1 : (left + top));
                                                                                                          -    }
                                                                                                          -  }
                                                                                                          -
                                                                                                          -  return dp[m - 1][n - 1];
                                                                                                          -};
                                                                                                          -
                                                                                                          -

                                                                                                          Explain:

                                                                                                          -

                                                                                                          dp[i][j] 代表到达该点的路径数量。该点可以从左边点或上边点到达 -也就是 dp[i][j] = dp[i - 1][j] + dp[i][j - 1]

                                                                                                          -

                                                                                                          考虑特殊情况:

                                                                                                          -
                                                                                                            -
                                                                                                          1. 该点为障碍,dp[i][j] = 0;
                                                                                                          2. -
                                                                                                          3. 左边点为障碍或不存在,left = 0;
                                                                                                          4. -
                                                                                                          5. 上边点点为障碍或不存在,top = 0;
                                                                                                          6. -
                                                                                                          7. 左边点与上边点均不存在,即起点,dp[i][j] = 1;
                                                                                                          8. -
                                                                                                          -

                                                                                                          Complexity:

                                                                                                          -
                                                                                                            -
                                                                                                          • Time complexity : O(m*n).
                                                                                                          • -
                                                                                                          • Space complexity : O(m*n).
                                                                                                          • -
                                                                                                          github
                                                                                                          \ No newline at end of file diff --git a/docs/problem/unique-paths.html b/docs/problem/unique-paths.html deleted file mode 100644 index 72e12e9..0000000 --- a/docs/problem/unique-paths.html +++ /dev/null @@ -1,49 +0,0 @@ -Unique Paths - LeetCode javascript solutions

                                                                                                          62. Unique Paths

                                                                                                          Difficulty:

                                                                                                          Problem

                                                                                                          -

                                                                                                          A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).

                                                                                                          -

                                                                                                          The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).

                                                                                                          -

                                                                                                          How many possible unique paths are there?

                                                                                                          -

                                                                                                          -

                                                                                                          Above is a 7 x 3 grid. How many possible unique paths are there?

                                                                                                          -

                                                                                                          Note: m and n will be at most 100.

                                                                                                          -

                                                                                                          Example 1:

                                                                                                          -
                                                                                                          Input: m = 3, n = 2
                                                                                                          -Output: 3
                                                                                                          -Explanation:
                                                                                                          -From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
                                                                                                          -1. Right -> Right -> Down
                                                                                                          -2. Right -> Down -> Right
                                                                                                          -3. Down -> Right -> Right
                                                                                                          -
                                                                                                          -

                                                                                                          Example 2:

                                                                                                          -
                                                                                                          Input: m = 7, n = 3
                                                                                                          -Output: 28
                                                                                                          -
                                                                                                          -

                                                                                                          Solution

                                                                                                          -
                                                                                                          /**
                                                                                                          - * @param {number} m
                                                                                                          - * @param {number} n
                                                                                                          - * @return {number}
                                                                                                          - */
                                                                                                          -var uniquePaths = function(m, n) {
                                                                                                          -  var dp = Array(m);
                                                                                                          -  if (!m || !n) return 0;
                                                                                                          -  for (var i = 0; i < m; i++) {
                                                                                                          -    dp[i] = Array(n);
                                                                                                          -    for (var j = 0; j < n; j++) {
                                                                                                          -      if (j > 0 && i > 0) dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
                                                                                                          -      else if (j > 0 && i === 0) dp[i][j] = dp[i][j - 1];
                                                                                                          -      else if (j === 0 && i > 0) dp[i][j] = dp[i - 1][j];
                                                                                                          -      else dp[i][j] = 1;
                                                                                                          -    }
                                                                                                          -  }
                                                                                                          -  return dp[m - 1][n - 1];
                                                                                                          -};
                                                                                                          -
                                                                                                          -

                                                                                                          Explain:

                                                                                                          -

                                                                                                          dp[i][j] 代表到达该点的路径数量。该点可以从左边点或上边点到达 -也就是 dp[i][j] = dp[i - 1][j] + dp[i][j - 1]

                                                                                                          -

                                                                                                          Complexity:

                                                                                                          -
                                                                                                            -
                                                                                                          • Time complexity : O(m*n).
                                                                                                          • -
                                                                                                          • Space complexity : O(m*n).
                                                                                                          • -
                                                                                                          github
                                                                                                          \ No newline at end of file diff --git a/docs/problem/valid-anagram.html b/docs/problem/valid-anagram.html deleted file mode 100644 index fe5c435..0000000 --- a/docs/problem/valid-anagram.html +++ /dev/null @@ -1,84 +0,0 @@ -Valid Anagram - LeetCode javascript solutions

                                                                                                          242. Valid Anagram

                                                                                                          Difficulty:
                                                                                                          Related Topics:

                                                                                                          Problem

                                                                                                          -

                                                                                                          Given two strings s and **t **, write a function to determine if t is an anagram of s.

                                                                                                          -

                                                                                                          Example 1:

                                                                                                          -
                                                                                                          Input: s = "anagram", t = "nagaram"
                                                                                                          -Output: true
                                                                                                          -
                                                                                                          -

                                                                                                          Example 2:

                                                                                                          -
                                                                                                          Input: s = "rat", t = "car"
                                                                                                          -Output: false
                                                                                                          -
                                                                                                          -

                                                                                                          Note: -You may assume the string contains only lowercase alphabets.

                                                                                                          -

                                                                                                          Follow up: -What if the inputs contain unicode characters? How would you adapt your solution to such case?

                                                                                                          -

                                                                                                          Solution 1

                                                                                                          -
                                                                                                          /**
                                                                                                          - * @param {string} s
                                                                                                          - * @param {string} t
                                                                                                          - * @return {boolean}
                                                                                                          - */
                                                                                                          -var isAnagram = function(s, t) {
                                                                                                          -  var lenA = s.length;
                                                                                                          -  var lenB = t.length;
                                                                                                          -  var map = {};
                                                                                                          -
                                                                                                          -  if (lenA !== lenB) return false;
                                                                                                          -
                                                                                                          -  for (var i = 0; i < lenA; i++) {
                                                                                                          -    if (!map[s[i]]) map[s[i]] = 0;
                                                                                                          -    map[s[i]]++;
                                                                                                          -  }
                                                                                                          -
                                                                                                          -  for (var j = 0; j < lenB; j++) {
                                                                                                          -    if (!map[t[j]]) return false;
                                                                                                          -    map[t[j]]--;
                                                                                                          -  }
                                                                                                          -
                                                                                                          -  return true;
                                                                                                          -};
                                                                                                          -
                                                                                                          -

                                                                                                          Explain:

                                                                                                          -

                                                                                                          nope.

                                                                                                          -

                                                                                                          Complexity:

                                                                                                          -
                                                                                                            -
                                                                                                          • Time complexity : O(n).
                                                                                                          • -
                                                                                                          • Space complexity : O(n).
                                                                                                          • -
                                                                                                          -

                                                                                                          Solution 2

                                                                                                          -
                                                                                                          /**
                                                                                                          - * @param {string} s
                                                                                                          - * @param {string} t
                                                                                                          - * @return {boolean}
                                                                                                          - */
                                                                                                          -var isAnagram = function(s, t) {
                                                                                                          -  var lenA = s.length;
                                                                                                          -  var lenB = t.length;
                                                                                                          -  var map = Array(26);
                                                                                                          -  var index = 0;
                                                                                                          -  var base = 'a'.charCodeAt(0);
                                                                                                          -
                                                                                                          -  if (lenA !== lenB) return false;
                                                                                                          -
                                                                                                          -  for (var i = 0; i < lenA; i++) {
                                                                                                          -    index = s[i].charCodeAt(0) - base;
                                                                                                          -    if (!map[index]) map[index] = 0;
                                                                                                          -    map[index]++;
                                                                                                          -  }
                                                                                                          -
                                                                                                          -  for (var j = 0; j < lenB; j++) {
                                                                                                          -    index = t[j].charCodeAt(0) - base;
                                                                                                          -    if (!map[index]) return false;
                                                                                                          -    map[index]--;
                                                                                                          -  }
                                                                                                          -
                                                                                                          -  return true;
                                                                                                          -};
                                                                                                          -
                                                                                                          -

                                                                                                          Explain:

                                                                                                          -

                                                                                                          nope.

                                                                                                          -

                                                                                                          Complexity:

                                                                                                          -
                                                                                                            -
                                                                                                          • Time complexity : O(n).
                                                                                                          • -
                                                                                                          • Space complexity : O(1).
                                                                                                          • -
                                                                                                          github
                                                                                                          \ No newline at end of file diff --git a/docs/problem/valid-number.html b/docs/problem/valid-number.html deleted file mode 100644 index fe34e23..0000000 --- a/docs/problem/valid-number.html +++ /dev/null @@ -1,65 +0,0 @@ -Valid Number - LeetCode javascript solutions

                                                                                                          65. Valid Number

                                                                                                          Difficulty:
                                                                                                          Related Topics:
                                                                                                          Similar Questions:

                                                                                                          Problem

                                                                                                          -

                                                                                                          Validate if a given string is numeric.

                                                                                                          -

                                                                                                          Some examples: -"0" => true -" 0.1 " => true -"abc" => false -"1 a" => false -"2e10" => true

                                                                                                          -

                                                                                                          Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.

                                                                                                          -

                                                                                                          Update (2015-02-10): -The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.

                                                                                                          -

                                                                                                          Solution

                                                                                                          -
                                                                                                          /**
                                                                                                          - * @param {string} s
                                                                                                          - * @return {boolean}
                                                                                                          - */
                                                                                                          -var isNumber = function(s) {
                                                                                                          -  var state = [
                                                                                                          -    {}, 
                                                                                                          -    {'blank': 1, 'sign': 2, 'digit':3, '.':4}, 
                                                                                                          -    {'digit':3, '.':4},
                                                                                                          -    {'digit':3, '.':5, 'e':6, 'blank':9},
                                                                                                          -    {'digit':5},
                                                                                                          -    {'digit':5, 'e':6, 'blank':9},
                                                                                                          -    {'sign':7, 'digit':8},
                                                                                                          -    {'digit':8},
                                                                                                          -    {'digit':8, 'blank':9},
                                                                                                          -    {'blank':9}
                                                                                                          -  ];
                                                                                                          -  var validState = [3, 5, 8, 9];
                                                                                                          -  var currentState = 1;
                                                                                                          -  var len = s.length;
                                                                                                          -  var str = '';
                                                                                                          -  var type = '';
                                                                                                          -  for (var i = 0; i < len; i++) {
                                                                                                          -    str = s[i];
                                                                                                          -    if (str >= '0' && str <= '9') {
                                                                                                          -      type = 'digit';
                                                                                                          -    } else if (str === '+' || str === '-') {
                                                                                                          -      type = 'sign';
                                                                                                          -    } else if (str === ' ') {
                                                                                                          -      type = 'blank';
                                                                                                          -    } else {
                                                                                                          -      type = str;
                                                                                                          -    }
                                                                                                          -    if (state[currentState][type] === undefined) {
                                                                                                          -      return false;
                                                                                                          -    } else {
                                                                                                          -      currentState = state[currentState][type];
                                                                                                          -    }
                                                                                                          -  }
                                                                                                          -    if (validState.indexOf(currentState) === -1) {
                                                                                                          -    return false;
                                                                                                          -    } else {
                                                                                                          -    return true;
                                                                                                          -    }
                                                                                                          -};
                                                                                                          -
                                                                                                          -

                                                                                                          Explain:

                                                                                                          -

                                                                                                          DFA 确定有限状态自动机

                                                                                                          -

                                                                                                          Complexity:

                                                                                                          -
                                                                                                            -
                                                                                                          • Time complexity : O(n).
                                                                                                          • -
                                                                                                          • Space complexity : O(1).
                                                                                                          • -
                                                                                                          github
                                                                                                          \ No newline at end of file diff --git a/docs/problem/valid-palindrome.html b/docs/problem/valid-palindrome.html deleted file mode 100644 index b092592..0000000 --- a/docs/problem/valid-palindrome.html +++ /dev/null @@ -1,44 +0,0 @@ -Valid Palindrome - LeetCode javascript solutions

                                                                                                          125. Valid Palindrome

                                                                                                          Difficulty:
                                                                                                          Related Topics:

                                                                                                          Problem

                                                                                                          -

                                                                                                          Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

                                                                                                          -

                                                                                                          Note: For the purpose of this problem, we define empty string as valid palindrome.

                                                                                                          -

                                                                                                          Example 1:

                                                                                                          -
                                                                                                          Input: "A man, a plan, a canal: Panama"
                                                                                                          -Output: true
                                                                                                          -
                                                                                                          -

                                                                                                          Example 2:

                                                                                                          -
                                                                                                          Input: "race a car"
                                                                                                          -Output: false
                                                                                                          -
                                                                                                          -

                                                                                                          Solution

                                                                                                          -
                                                                                                          /**
                                                                                                          - * @param {string} s
                                                                                                          - * @return {boolean}
                                                                                                          - */
                                                                                                          -var isPalindrome = function(s) {
                                                                                                          -  var i = 0;
                                                                                                          -  var j = s.length - 1;
                                                                                                          -  var m = '';
                                                                                                          -  var n = '';
                                                                                                          -  while (i < j) {
                                                                                                          -    m = s[i].toLowerCase();
                                                                                                          -    n = s[j].toLowerCase();
                                                                                                          -    if (!isLetterOrDigit(m)) i++;
                                                                                                          -    else if (!isLetterOrDigit(n)) j--;
                                                                                                          -    else if (m === n) { i++; j--; }
                                                                                                          -    else return false;
                                                                                                          -  }
                                                                                                          -  return true;
                                                                                                          -};
                                                                                                          -
                                                                                                          -var isLetterOrDigit = function (c) {
                                                                                                          -  return (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9');
                                                                                                          -};
                                                                                                          -
                                                                                                          -
                                                                                                          -

                                                                                                          Explain:

                                                                                                          -

                                                                                                          nope.

                                                                                                          -

                                                                                                          Complexity:

                                                                                                          -
                                                                                                            -
                                                                                                          • Time complexity : O(n).
                                                                                                          • -
                                                                                                          • Space complexity : O(n).
                                                                                                          • -
                                                                                                          github
                                                                                                          \ No newline at end of file diff --git a/docs/problem/valid-parentheses.html b/docs/problem/valid-parentheses.html deleted file mode 100644 index aa6083b..0000000 --- a/docs/problem/valid-parentheses.html +++ /dev/null @@ -1,58 +0,0 @@ -Valid Parentheses - LeetCode javascript solutions

                                                                                                          20. Valid Parentheses

                                                                                                          Difficulty:
                                                                                                          Related Topics:

                                                                                                          Problem

                                                                                                          -

                                                                                                          Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

                                                                                                          -

                                                                                                          An input string is valid if:

                                                                                                          -
                                                                                                            -
                                                                                                          • Open brackets must be closed by the same type of brackets.
                                                                                                          • -
                                                                                                          • Open brackets must be closed in the correct order.
                                                                                                          • -
                                                                                                          -

                                                                                                          Note that an empty string is also considered valid.

                                                                                                          -

                                                                                                          Example 1:

                                                                                                          -
                                                                                                          Input: "()"
                                                                                                          -Output: true
                                                                                                          -
                                                                                                          -

                                                                                                          Example 2:

                                                                                                          -
                                                                                                          Input: "()[]{}"
                                                                                                          -Output: true
                                                                                                          -
                                                                                                          -

                                                                                                          Example 3:

                                                                                                          -
                                                                                                          Input: "(]"
                                                                                                          -Output: false
                                                                                                          -
                                                                                                          -

                                                                                                          Example 4:

                                                                                                          -
                                                                                                          Input: "([)]"
                                                                                                          -Output: false
                                                                                                          -
                                                                                                          -

                                                                                                          Example 5:

                                                                                                          -
                                                                                                          Input: "{[]}"
                                                                                                          -Output: true
                                                                                                          -
                                                                                                          -

                                                                                                          Solution

                                                                                                          -
                                                                                                          /**
                                                                                                          - * @param {string} s
                                                                                                          - * @return {boolean}
                                                                                                          - */
                                                                                                          -var isValid = function(s) {
                                                                                                          -  var stack = [];
                                                                                                          -  var len = s.length;
                                                                                                          -  var map = {
                                                                                                          -    '(': ')',
                                                                                                          -    '[': ']',
                                                                                                          -    '{': '}'
                                                                                                          -  };
                                                                                                          -  for (var i = 0; i < len; i++) {
                                                                                                          -    if (stack.length > 0 && map[stack[stack.length - 1]] === s[i]) {
                                                                                                          -      stack.pop();
                                                                                                          -    } else {
                                                                                                          -      stack.push(s[i]);
                                                                                                          -    }
                                                                                                          -  }
                                                                                                          -  return stack.length === 0;
                                                                                                          -};
                                                                                                          -
                                                                                                          -

                                                                                                          Explain:

                                                                                                          -

                                                                                                          nope.

                                                                                                          -

                                                                                                          Complexity:

                                                                                                          -
                                                                                                            -
                                                                                                          • Time complexity : O(n).
                                                                                                          • -
                                                                                                          • Space complexity : O(n).
                                                                                                          • -
                                                                                                          github
                                                                                                          \ No newline at end of file diff --git a/docs/problem/valid-sudoku.html b/docs/problem/valid-sudoku.html deleted file mode 100644 index f3a09e2..0000000 --- a/docs/problem/valid-sudoku.html +++ /dev/null @@ -1,78 +0,0 @@ -Valid Sudoku - LeetCode javascript solutions

                                                                                                          36. Valid Sudoku

                                                                                                          Difficulty:
                                                                                                          Related Topics:
                                                                                                          Similar Questions:

                                                                                                          Problem

                                                                                                          -

                                                                                                          Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:

                                                                                                          -
                                                                                                            -
                                                                                                          • Each row must contain the digits 1-9 without repetition.
                                                                                                          • -
                                                                                                          • Each column must contain the digits 1-9 without repetition.
                                                                                                          • -
                                                                                                          • Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without repetition.
                                                                                                          • -
                                                                                                          -

                                                                                                          -

                                                                                                          A partially filled sudoku which is valid.

                                                                                                          -

                                                                                                          The Sudoku board could be partially filled, where empty cells are filled with the character '.'.

                                                                                                          -

                                                                                                          Example 1:

                                                                                                          -
                                                                                                          Input:
                                                                                                          -[
                                                                                                          -  ["5","3",".",".","7",".",".",".","."],
                                                                                                          -  ["6",".",".","1","9","5",".",".","."],
                                                                                                          -  [".","9","8",".",".",".",".","6","."],
                                                                                                          -  ["8",".",".",".","6",".",".",".","3"],
                                                                                                          -  ["4",".",".","8",".","3",".",".","1"],
                                                                                                          -  ["7",".",".",".","2",".",".",".","6"],
                                                                                                          -  [".","6",".",".",".",".","2","8","."],
                                                                                                          -  [".",".",".","4","1","9",".",".","5"],
                                                                                                          -  [".",".",".",".","8",".",".","7","9"]
                                                                                                          -]
                                                                                                          -Output: true
                                                                                                          -
                                                                                                          -

                                                                                                          Example 2:

                                                                                                          -
                                                                                                          Input:
                                                                                                          -[
                                                                                                          -  ["8","3",".",".","7",".",".",".","."],
                                                                                                          -  ["6",".",".","1","9","5",".",".","."],
                                                                                                          -  [".","9","8",".",".",".",".","6","."],
                                                                                                          -  ["8",".",".",".","6",".",".",".","3"],
                                                                                                          -  ["4",".",".","8",".","3",".",".","1"],
                                                                                                          -  ["7",".",".",".","2",".",".",".","6"],
                                                                                                          -  [".","6",".",".",".",".","2","8","."],
                                                                                                          -  [".",".",".","4","1","9",".",".","5"],
                                                                                                          -  [".",".",".",".","8",".",".","7","9"]
                                                                                                          -]
                                                                                                          -Output: false
                                                                                                          -Explanation: Same as Example 1, except with the 5 in the top left corner being 
                                                                                                          -    modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is invalid.
                                                                                                          -
                                                                                                          -

                                                                                                          Note:

                                                                                                          -
                                                                                                            -
                                                                                                          • A Sudoku board (partially filled) could be valid but is not necessarily solvable.
                                                                                                          • -
                                                                                                          • Only the filled cells need to be validated according to the mentioned rules.
                                                                                                          • -
                                                                                                          • The given board contain only digits 1-9 and the character '.'.
                                                                                                          • -
                                                                                                          • The given board size is always 9x9.
                                                                                                          • -
                                                                                                          -

                                                                                                          Solution

                                                                                                          -
                                                                                                          /**
                                                                                                          - * @param {character[][]} board
                                                                                                          - * @return {boolean}
                                                                                                          - */
                                                                                                          -var isValidSudoku = function(board) {
                                                                                                          -  var map = {};
                                                                                                          -  var tmp = 0;
                                                                                                          -  for (var i = 0; i < 9; i++) {
                                                                                                          -    for (var j = 0; j < 9; j++) {
                                                                                                          -      tmp = board[i][j];
                                                                                                          -      if (tmp === '.') continue;
                                                                                                          -      if (map['i' + i + tmp] || map['j' + j + tmp] || map['b' + Math.floor(i / 3) + Math.floor(j / 3) + tmp]) return false;
                                                                                                          -      map['i' + i + tmp] = 1;
                                                                                                          -      map['j' + j + tmp] = 1;
                                                                                                          -      map['b' + Math.floor(i / 3) + Math.floor(j / 3) + tmp] = 1;
                                                                                                          -    }
                                                                                                          -  }
                                                                                                          -  return true;
                                                                                                          -};
                                                                                                          -
                                                                                                          -

                                                                                                          Explain:

                                                                                                          -

                                                                                                          哈希表:

                                                                                                          -

                                                                                                          i、j、b 开头的键分别代表 某行、某列、某块 中,某数字是否已存在

                                                                                                          -

                                                                                                          Complexity:

                                                                                                          -
                                                                                                            -
                                                                                                          • Time complexity : O(n^2).
                                                                                                          • -
                                                                                                          • Space complexity : O(n).
                                                                                                          • -
                                                                                                          github
                                                                                                          \ No newline at end of file diff --git a/docs/problem/validate-binary-search-tree.html b/docs/problem/validate-binary-search-tree.html deleted file mode 100644 index 6503719..0000000 --- a/docs/problem/validate-binary-search-tree.html +++ /dev/null @@ -1,95 +0,0 @@ -Validate Binary Search Tree - LeetCode javascript solutions

                                                                                                          98. Validate Binary Search Tree

                                                                                                          Difficulty:
                                                                                                          Related Topics:

                                                                                                          Problem

                                                                                                          -

                                                                                                          Given a binary tree, determine if it is a valid binary search tree (BST).

                                                                                                          -

                                                                                                          Assume a BST is defined as follows:

                                                                                                          -
                                                                                                            -
                                                                                                          • The left subtree of a node contains only nodes with keys less than the node's key.

                                                                                                          • -
                                                                                                          • The right subtree of a node contains only nodes with keys greater than the node's key.

                                                                                                          • -
                                                                                                          • Both the left and right subtrees must also be binary search trees.

                                                                                                          • -
                                                                                                          -

                                                                                                          Example 1:

                                                                                                          -
                                                                                                          Input:
                                                                                                          -    2
                                                                                                          -   / \
                                                                                                          -  1   3
                                                                                                          -Output: true
                                                                                                          -
                                                                                                          -

                                                                                                          Example 2:

                                                                                                          -
                                                                                                          5
                                                                                                          -   / \
                                                                                                          -  1   4
                                                                                                          -     / \
                                                                                                          -    3   6
                                                                                                          -Output: false
                                                                                                          -Explanation: The input is: [5,1,4,null,null,3,6]. The root node's value
                                                                                                          -             is 5 but its right child's value is 4.
                                                                                                          -
                                                                                                          -

                                                                                                          Solution 1

                                                                                                          -
                                                                                                          /**
                                                                                                          - * Definition for a binary tree node.
                                                                                                          - * function TreeNode(val) {
                                                                                                          - *     this.val = val;
                                                                                                          - *     this.left = this.right = null;
                                                                                                          - * }
                                                                                                          - */
                                                                                                          -/**
                                                                                                          - * @param {TreeNode} root
                                                                                                          - * @return {boolean}
                                                                                                          - */
                                                                                                          -var isValidBST = function(root) {
                                                                                                          -  return helper(root, Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER);
                                                                                                          -};
                                                                                                          -
                                                                                                          -var helper = function (root, min, max) {
                                                                                                          -  if (!root) return true;
                                                                                                          -  if (root.val <= min || root.val >= max) return false;
                                                                                                          -  return helper(root.left, min, root.val) && helper(root.right, root.val, max);
                                                                                                          -};
                                                                                                          -
                                                                                                          -

                                                                                                          Explain:

                                                                                                          -

                                                                                                          nope.

                                                                                                          -

                                                                                                          Complexity:

                                                                                                          -
                                                                                                            -
                                                                                                          • Time complexity : O(n). n 为节点数。
                                                                                                          • -
                                                                                                          • Space complexity : O(1).
                                                                                                          • -
                                                                                                          -

                                                                                                          Solution 2

                                                                                                          -
                                                                                                          /**
                                                                                                          - * Definition for a binary tree node.
                                                                                                          - * function TreeNode(val) {
                                                                                                          - *     this.val = val;
                                                                                                          - *     this.left = this.right = null;
                                                                                                          - * }
                                                                                                          - */
                                                                                                          -/**
                                                                                                          - * @param {TreeNode} root
                                                                                                          - * @return {boolean}
                                                                                                          - */
                                                                                                          -var isValidBST = function(root) {
                                                                                                          -  var prev = null;
                                                                                                          -  var now = root;
                                                                                                          -  var stack = [];
                                                                                                          -
                                                                                                          -  while (now || stack.length) {
                                                                                                          -    while (now) {
                                                                                                          -      stack.push(now);
                                                                                                          -      now = now.left;
                                                                                                          -    }
                                                                                                          -
                                                                                                          -    now = stack.pop();
                                                                                                          -
                                                                                                          -    if (prev && prev.val >= now.val) return false;
                                                                                                          -
                                                                                                          -    prev = now;
                                                                                                          -    now = now.right;
                                                                                                          -  }
                                                                                                          -
                                                                                                          -  return true;
                                                                                                          -};
                                                                                                          -
                                                                                                          -

                                                                                                          Explain:

                                                                                                          -

                                                                                                          nope.

                                                                                                          -

                                                                                                          Complexity:

                                                                                                          -
                                                                                                            -
                                                                                                          • Time complexity : O(n). n 为节点数。
                                                                                                          • -
                                                                                                          • Space complexity : O(n).
                                                                                                          • -
                                                                                                          github
                                                                                                          \ No newline at end of file diff --git a/docs/problem/wildcard-matching.html b/docs/problem/wildcard-matching.html deleted file mode 100644 index 749c68e..0000000 --- a/docs/problem/wildcard-matching.html +++ /dev/null @@ -1,89 +0,0 @@ -Wildcard Matching - LeetCode javascript solutions

                                                                                                          44. Wildcard Matching

                                                                                                          Difficulty:
                                                                                                          Similar Questions:

                                                                                                          Problem

                                                                                                          -

                                                                                                          Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*'.

                                                                                                          -
                                                                                                          '?' Matches any single character.
                                                                                                          -'*' Matches any sequence of characters (including the empty sequence).
                                                                                                          -
                                                                                                          -

                                                                                                          The matching should cover the entire input string (not partial).

                                                                                                          -

                                                                                                          Note:

                                                                                                          -
                                                                                                            -
                                                                                                          • s could be empty and contains only lowercase letters a-z.
                                                                                                          • -
                                                                                                          • p could be empty and contains only lowercase letters a-z, and characters like ? or *.
                                                                                                          • -
                                                                                                          -

                                                                                                          Example 1:

                                                                                                          -
                                                                                                          Input:
                                                                                                          -s = "aa"
                                                                                                          -p = "a"
                                                                                                          -Output: false
                                                                                                          -Explanation: "a" does not match the entire string "aa".
                                                                                                          -
                                                                                                          -

                                                                                                          Example 2:

                                                                                                          -
                                                                                                          Input:
                                                                                                          -s = "aa"
                                                                                                          -p = "*"
                                                                                                          -Output: true
                                                                                                          -Explanation: '*' matches any sequence.
                                                                                                          -
                                                                                                          -

                                                                                                          Example 3:

                                                                                                          -
                                                                                                          Input:
                                                                                                          -s = "cb"
                                                                                                          -p = "?a"
                                                                                                          -Output: false
                                                                                                          -Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'.
                                                                                                          -
                                                                                                          -

                                                                                                          Example 4:

                                                                                                          -
                                                                                                          Input:
                                                                                                          -s = "adceb"
                                                                                                          -p = "*a*b"
                                                                                                          -Output: true
                                                                                                          -Explanation: The first '*' matches the empty sequence, while the second '*' matches the substring "dce".
                                                                                                          -
                                                                                                          -

                                                                                                          Example 5:

                                                                                                          -
                                                                                                          Input:
                                                                                                          -s = "acdcb"
                                                                                                          -p = "a*c?b"
                                                                                                          -Output: false
                                                                                                          -
                                                                                                          -

                                                                                                          Solution

                                                                                                          -
                                                                                                          /**
                                                                                                          - * @param {string} s
                                                                                                          - * @param {string} p
                                                                                                          - * @return {boolean}
                                                                                                          - */
                                                                                                          -var isMatch = function(s, p) {
                                                                                                          -  var dp = Array(p.length + 1).fill(0).map(_ => ({}));
                                                                                                          -  return test(s, p, 0, 0, dp);
                                                                                                          -};
                                                                                                          -
                                                                                                          -var test = function (s, p, sIndex, pIndex, dp) {
                                                                                                          -  if (dp[pIndex][sIndex] !== undefined) return dp[pIndex][sIndex];
                                                                                                          -
                                                                                                          -  var sNow = s[sIndex];
                                                                                                          -  var pNow = p[pIndex];
                                                                                                          -  var res = false;
                                                                                                          -
                                                                                                          -  if (pNow === undefined) return sNow === undefined;
                                                                                                          -  if (sNow === undefined) {
                                                                                                          -    for (var i = pIndex; i < p.length; i++) {
                                                                                                          -      if (p[i] !== '*') return false;
                                                                                                          -    }
                                                                                                          -    return true;
                                                                                                          -  }
                                                                                                          -
                                                                                                          -  if (sNow === pNow || pNow === '?') {
                                                                                                          -    res = test(s, p, sIndex + 1, pIndex + 1, dp);
                                                                                                          -  } else if (pNow === '*') {
                                                                                                          -    res = test(s, p, sIndex, pIndex + 1, dp) || test(s, p, sIndex + 1, pIndex + 1, dp) || test(s, p, sIndex + 1, pIndex, dp);
                                                                                                          -  }
                                                                                                          -
                                                                                                          -  dp[pIndex][sIndex] = res;
                                                                                                          -
                                                                                                          -  return res;
                                                                                                          -};
                                                                                                          -
                                                                                                          -

                                                                                                          Explain:

                                                                                                          -

                                                                                                          dp[i][j] 代表当正则第 i 位匹配字符串第 j 位时,是否 match.

                                                                                                          -

                                                                                                          Complexity:

                                                                                                          -
                                                                                                            -
                                                                                                          • Time complexity : O(m*n).
                                                                                                          • -
                                                                                                          • Space complexity : O(m*n).
                                                                                                          • -
                                                                                                          github
                                                                                                          \ No newline at end of file diff --git a/docs/problem/word-break-ii.html b/docs/problem/word-break-ii.html deleted file mode 100644 index 0a69e76..0000000 --- a/docs/problem/word-break-ii.html +++ /dev/null @@ -1,86 +0,0 @@ -Word Break II - LeetCode javascript solutions

                                                                                                          140. Word Break II

                                                                                                          Difficulty:

                                                                                                          Problem

                                                                                                          -

                                                                                                          Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.

                                                                                                          -

                                                                                                          Note:

                                                                                                          -
                                                                                                            -
                                                                                                          • The same word in the dictionary may be reused multiple times in the segmentation.
                                                                                                          • -
                                                                                                          • You may assume the dictionary does not contain duplicate words.
                                                                                                          • -
                                                                                                          -

                                                                                                          Example 1:

                                                                                                          -
                                                                                                          Input:
                                                                                                          -s = "catsanddog"
                                                                                                          -wordDict = ["cat", "cats", "and", "sand", "dog"]
                                                                                                          -Output:
                                                                                                          -[
                                                                                                          -  "cats and dog",
                                                                                                          -  "cat sand dog"
                                                                                                          -]
                                                                                                          -
                                                                                                          -

                                                                                                          Example 2:

                                                                                                          -
                                                                                                          Input:
                                                                                                          -s = "pineapplepenapple"
                                                                                                          -wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
                                                                                                          -Output:
                                                                                                          -[
                                                                                                          -  "pine apple pen apple",
                                                                                                          -  "pineapple pen apple",
                                                                                                          -  "pine applepen apple"
                                                                                                          -]
                                                                                                          -Explanation: Note that you are allowed to reuse a dictionary word.
                                                                                                          -
                                                                                                          -

                                                                                                          Example 3:

                                                                                                          -
                                                                                                          Input:
                                                                                                          -s = "catsandog"
                                                                                                          -wordDict = ["cats", "dog", "sand", "and", "cat"]
                                                                                                          -Output:
                                                                                                          -[]
                                                                                                          -
                                                                                                          -

                                                                                                          Solution

                                                                                                          -
                                                                                                          /**
                                                                                                          - * @param {string} s
                                                                                                          - * @param {string[]} wordDict
                                                                                                          - * @return {string[]}
                                                                                                          - */
                                                                                                          -var wordBreak = function(s, wordDict) {
                                                                                                          -  var dp = Array(s.length);
                                                                                                          -  var map = {};
                                                                                                          -  var res = [];
                                                                                                          -
                                                                                                          -  for (var i = 0; i < wordDict.length; i++) {
                                                                                                          -    map[wordDict[i]] = true;
                                                                                                          -  }
                                                                                                          -
                                                                                                          -  return find(s, map, dp, 0);
                                                                                                          -};
                                                                                                          -
                                                                                                          -var find = function (s, map, dp, index) {
                                                                                                          -  if (dp[index]) return dp[index];
                                                                                                          -
                                                                                                          -  var str = '';
                                                                                                          -  var tmp = null;
                                                                                                          -  var len = s.length;
                                                                                                          -
                                                                                                          -  dp[index] = [];
                                                                                                          -
                                                                                                          -  for (var i = index; i < len; i++) {
                                                                                                          -    str = s.substring(index, i + 1);
                                                                                                          -    if (!map[str]) continue;
                                                                                                          -    if (i === len - 1) {
                                                                                                          -      dp[index].push(str);
                                                                                                          -      break;
                                                                                                          -    }
                                                                                                          -    tmp = find(s, map, dp, i + 1);
                                                                                                          -    for (var j = 0; j < tmp.length; j++) {
                                                                                                          -      dp[index].push(str + ' ' + tmp[j]);
                                                                                                          -    }
                                                                                                          -  }
                                                                                                          -
                                                                                                          -  return dp[index];
                                                                                                          -};
                                                                                                          -
                                                                                                          -

                                                                                                          Explain:

                                                                                                          -

                                                                                                          dp[i] 代表 s.substring(i)wordDict 里的词组成的方式。

                                                                                                          -

                                                                                                          Complexity:

                                                                                                          -
                                                                                                            -
                                                                                                          • Time complexity : O(n^2).
                                                                                                          • -
                                                                                                          • Space complexity : O(n^2).
                                                                                                          • -
                                                                                                          github
                                                                                                          \ No newline at end of file diff --git a/docs/problem/word-break.html b/docs/problem/word-break.html deleted file mode 100644 index 03716bb..0000000 --- a/docs/problem/word-break.html +++ /dev/null @@ -1,66 +0,0 @@ -Word Break - LeetCode javascript solutions

                                                                                                          139. Word Break

                                                                                                          Difficulty:
                                                                                                          Related Topics:
                                                                                                          Similar Questions:

                                                                                                          Problem

                                                                                                          -

                                                                                                          Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

                                                                                                          -

                                                                                                          Note:

                                                                                                          -
                                                                                                            -
                                                                                                          • The same word in the dictionary may be reused multiple times in the segmentation.
                                                                                                          • -
                                                                                                          • You may assume the dictionary does not contain duplicate words.
                                                                                                          • -
                                                                                                          -

                                                                                                          Example 1:

                                                                                                          -
                                                                                                          Input: s = "leetcode", wordDict = ["leet", "code"]
                                                                                                          -Output: true
                                                                                                          -Explanation: Return true because "leetcode" can be segmented as "leet code".
                                                                                                          -
                                                                                                          -

                                                                                                          Example 2:

                                                                                                          -
                                                                                                          Input: s = "applepenapple", wordDict = ["apple", "pen"]
                                                                                                          -Output: true
                                                                                                          -Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
                                                                                                          -             Note that you are allowed to reuse a dictionary word.
                                                                                                          -
                                                                                                          -

                                                                                                          Example 3:

                                                                                                          -
                                                                                                          Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
                                                                                                          -Output: false
                                                                                                          -
                                                                                                          -

                                                                                                          Solution

                                                                                                          -
                                                                                                          /**
                                                                                                          - * @param {string} s
                                                                                                          - * @param {string[]} wordDict
                                                                                                          - * @return {boolean}
                                                                                                          - */
                                                                                                          -var wordBreak = function(s, wordDict) {
                                                                                                          -  var len = wordDict.length;
                                                                                                          -  var dp = Array(len);
                                                                                                          -  var map = {};
                                                                                                          -  for (var i = 0; i < len; i++) {
                                                                                                          -    map[wordDict[i]] = true;
                                                                                                          -  }
                                                                                                          -  return find(s, map, dp, 0);
                                                                                                          -};
                                                                                                          -
                                                                                                          -var find = function (s, map, dp, index) {
                                                                                                          -  if (dp[index] !== undefined) return dp[index];
                                                                                                          -
                                                                                                          -  var str = '';
                                                                                                          -  var res = false;
                                                                                                          -  var len = s.length;
                                                                                                          -
                                                                                                          -  if (index === len) return true;
                                                                                                          -
                                                                                                          -  for (var i = index; i < len; i++) {
                                                                                                          -    str = s.substring(index, i + 1);
                                                                                                          -    if (map[str] && find(s, map, dp, i + 1)) {
                                                                                                          -      res = true;
                                                                                                          -      break;
                                                                                                          -    }
                                                                                                          -  }
                                                                                                          -
                                                                                                          -  dp[index] = res;
                                                                                                          -  return res;
                                                                                                          -};
                                                                                                          -
                                                                                                          -

                                                                                                          Explain:

                                                                                                          -

                                                                                                          dp[i] 代表 s.substring(i) 是否可以由 wordDict 里的词组成。

                                                                                                          -

                                                                                                          Complexity:

                                                                                                          -
                                                                                                            -
                                                                                                          • Time complexity : O(n^2).
                                                                                                          • -
                                                                                                          • Space complexity : O(n^2).
                                                                                                          • -
                                                                                                          github
                                                                                                          \ No newline at end of file diff --git a/docs/problem/word-ladder-ii.html b/docs/problem/word-ladder-ii.html deleted file mode 100644 index 8fac6e3..0000000 --- a/docs/problem/word-ladder-ii.html +++ /dev/null @@ -1,139 +0,0 @@ -Word Ladder II - LeetCode javascript solutions

                                                                                                          126. Word Ladder II

                                                                                                          Difficulty:
                                                                                                          Similar Questions:

                                                                                                          Problem

                                                                                                          -

                                                                                                          Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:

                                                                                                          -
                                                                                                            -
                                                                                                          • Only one letter can be changed at a time
                                                                                                          • -
                                                                                                          • Each transformed word must exist in the word list. Note that beginWord is not a transformed
                                                                                                          • -
                                                                                                          -

                                                                                                          Note:

                                                                                                          -
                                                                                                            -
                                                                                                          • Return an empty list if there is no such transformation sequence.
                                                                                                          • -
                                                                                                          • All words have the same length.
                                                                                                          • -
                                                                                                          • All words contain only lowercase alphabetic characters.
                                                                                                          • -
                                                                                                          • You may assume no duplicates in the word list.
                                                                                                          • -
                                                                                                          • You may assume beginWord and endWord are non-empty and are not the same.
                                                                                                          • -
                                                                                                          -

                                                                                                          Example 1:

                                                                                                          -
                                                                                                          Input:
                                                                                                          -beginWord = "hit",
                                                                                                          -endWord = "cog",
                                                                                                          -wordList = ["hot","dot","dog","lot","log","cog"]
                                                                                                          -
                                                                                                          -Output:
                                                                                                          -[
                                                                                                          -  ["hit","hot","dot","dog","cog"],
                                                                                                          -  ["hit","hot","lot","log","cog"]
                                                                                                          -]
                                                                                                          -
                                                                                                          -

                                                                                                          Example 2:

                                                                                                          -
                                                                                                          Input:
                                                                                                          -beginWord = "hit"
                                                                                                          -endWord = "cog"
                                                                                                          -wordList = ["hot","dot","dog","lot","log"]
                                                                                                          -
                                                                                                          -Output: []
                                                                                                          -
                                                                                                          -Explanation: The endWord "cog" is not in wordList, therefore no possible transformation.
                                                                                                          -
                                                                                                          -

                                                                                                          Solution

                                                                                                          -
                                                                                                          /**
                                                                                                          - * @param {string} beginWord
                                                                                                          - * @param {string} endWord
                                                                                                          - * @param {string[]} wordList
                                                                                                          - * @return {string[][]}
                                                                                                          - */
                                                                                                          -var findLadders = function(beginWord, endWord, wordList) {
                                                                                                          -  var wordSet = new Set(wordList);
                                                                                                          -  var wordNext = {};
                                                                                                          -  var distance = {};
                                                                                                          -  var result = [];
                                                                                                          -
                                                                                                          -  bfs(beginWord, endWord, wordSet, wordNext, distance);
                                                                                                          -  dfs(beginWord, endWord, result, wordNext, distance, []);
                                                                                                          -
                                                                                                          -  return result;
                                                                                                          -};
                                                                                                          -
                                                                                                          -var dfs = function (word, endWord, result, wordNext, distance, path) {
                                                                                                          -  var neighbors = wordNext[word] || [];
                                                                                                          -
                                                                                                          -  path.push(word);
                                                                                                          -
                                                                                                          -  if (word === endWord) {
                                                                                                          -    result.push(Array.from(path));
                                                                                                          -  } else {
                                                                                                          -    for (var i = 0; i < neighbors.length; i++) {
                                                                                                          -      if (distance[word] + 1 === distance[neighbors[i]]) {
                                                                                                          -        dfs(neighbors[i], endWord, result, wordNext, distance, path);
                                                                                                          -      }
                                                                                                          -    }
                                                                                                          -  }
                                                                                                          -
                                                                                                          -  path.pop();
                                                                                                          -};
                                                                                                          -
                                                                                                          -var bfs = function (beginWord, endWord, wordSet, wordNext, distance) {
                                                                                                          -  var queue = [];
                                                                                                          -  var findLast = false;
                                                                                                          -  var neighbors = [];
                                                                                                          -  var dis = 0;
                                                                                                          -  var word = '';
                                                                                                          -  var len = 0;
                                                                                                          -  var i = 0;
                                                                                                          -
                                                                                                          -  queue.push(beginWord);
                                                                                                          -  distance[beginWord] = 0;
                                                                                                          -
                                                                                                          -  while (len = queue.length) {
                                                                                                          -    findLast = false;
                                                                                                          -
                                                                                                          -    for (i = 0; i < len; i++) {
                                                                                                          -      word = queue.shift();
                                                                                                          -      dis = distance[word];
                                                                                                          -      neighbors = getNeighbors(word, wordSet);
                                                                                                          -      if (!wordNext[word]) wordNext[word] = [];
                                                                                                          -
                                                                                                          -      for (var j = 0; j < neighbors.length; j++) {
                                                                                                          -        wordNext[word].push(neighbors[j]);
                                                                                                          -
                                                                                                          -        if (distance[neighbors[j]] === undefined) {
                                                                                                          -          distance[neighbors[j]] = dis + 1;
                                                                                                          -
                                                                                                          -          if (neighbors[j] === endWord) {
                                                                                                          -            findLast = true;
                                                                                                          -          } else {
                                                                                                          -            queue.push(neighbors[j]);
                                                                                                          -          }
                                                                                                          -        }
                                                                                                          -      }
                                                                                                          -    }
                                                                                                          -    if (findLast) break;
                                                                                                          -  }
                                                                                                          -};
                                                                                                          -
                                                                                                          -var getNeighbors = function (word, wordSet) {
                                                                                                          -  var start = 'a'.charCodeAt(0);
                                                                                                          -  var len = word.length;
                                                                                                          -  var str = '';
                                                                                                          -  var res = [];
                                                                                                          -
                                                                                                          -  for (var i = 0; i < len; i++) {
                                                                                                          -    for (var j = 0; j < 26; j++) {
                                                                                                          -      str = word.substr(0, i) + String.fromCharCode(j + start) + word.substr(i + 1);
                                                                                                          -      if (wordSet.has(str)) res.push(str);
                                                                                                          -    }
                                                                                                          -  }
                                                                                                          -
                                                                                                          -  return res;
                                                                                                          -};
                                                                                                          -
                                                                                                          -

                                                                                                          Explain:

                                                                                                          -
                                                                                                            -
                                                                                                          1. bfs 建立节点树
                                                                                                          2. -
                                                                                                          3. dfs 遍历树得到结果
                                                                                                          4. -
                                                                                                          -

                                                                                                          注意获取改变 1 位的词的时候用 26 个字母遍历,不要直接和其它词对比。

                                                                                                          -

                                                                                                          Complexity:

                                                                                                          -
                                                                                                            -
                                                                                                          • Time complexity :
                                                                                                          • -
                                                                                                          • Space complexity :
                                                                                                          • -
                                                                                                          github
                                                                                                          \ No newline at end of file diff --git a/docs/problem/word-ladder.html b/docs/problem/word-ladder.html deleted file mode 100644 index 70d84cd..0000000 --- a/docs/problem/word-ladder.html +++ /dev/null @@ -1,91 +0,0 @@ -Word Ladder - LeetCode javascript solutions

                                                                                                          127. Word Ladder

                                                                                                          Difficulty:
                                                                                                          Related Topics:

                                                                                                          Problem

                                                                                                          -

                                                                                                          Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:

                                                                                                          -
                                                                                                            -
                                                                                                          • Only one letter can be changed at a time.
                                                                                                          • -
                                                                                                          • Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
                                                                                                          • -
                                                                                                          -

                                                                                                          Note:

                                                                                                          -
                                                                                                            -
                                                                                                          • Return 0 if there is no such transformation sequence.
                                                                                                          • -
                                                                                                          • All words have the same length.
                                                                                                          • -
                                                                                                          • All words contain only lowercase alphabetic characters.
                                                                                                          • -
                                                                                                          • You may assume no duplicates in the word list.
                                                                                                          • -
                                                                                                          • You may assume beginWord and endWord are non-empty and are not the same.
                                                                                                          • -
                                                                                                          -

                                                                                                          Example 1:

                                                                                                          -
                                                                                                          Input:
                                                                                                          -beginWord = "hit",
                                                                                                          -endWord = "cog",
                                                                                                          -wordList = ["hot","dot","dog","lot","log","cog"]
                                                                                                          -
                                                                                                          -Output: 5
                                                                                                          -
                                                                                                          -Explanation: As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
                                                                                                          -return its length 5.
                                                                                                          -
                                                                                                          -

                                                                                                          Example 2:

                                                                                                          -
                                                                                                          Input:
                                                                                                          -beginWord = "hit"
                                                                                                          -endWord = "cog"
                                                                                                          -wordList = ["hot","dot","dog","lot","log"]
                                                                                                          -
                                                                                                          -Output: 0
                                                                                                          -
                                                                                                          -Explanation: The endWord "cog" is not in wordList, therefore no possible transformation.
                                                                                                          -
                                                                                                          -

                                                                                                          Solution

                                                                                                          -
                                                                                                          /**
                                                                                                          - * @param {string} beginWord
                                                                                                          - * @param {string} endWord
                                                                                                          - * @param {string[]} wordList
                                                                                                          - * @return {number}
                                                                                                          - */
                                                                                                          -var ladderLength = function(beginWord, endWord, wordList) {
                                                                                                          -  var wordSet = new Set(wordList);
                                                                                                          -  var queue = [];
                                                                                                          -  var step = 0;
                                                                                                          -  var word = '';
                                                                                                          -  var len = 0;
                                                                                                          -  var i = 0;
                                                                                                          -
                                                                                                          -  pushNextWord(beginWord, queue, wordSet);
                                                                                                          -  step = 2;
                                                                                                          -
                                                                                                          -  while (len = queue.length) {
                                                                                                          -    for (i = 0; i < len; i++) {
                                                                                                          -      word = queue.shift();
                                                                                                          -      if (word === endWord) return step;
                                                                                                          -      pushNextWord(word, queue, wordSet);
                                                                                                          -    }
                                                                                                          -    step++;
                                                                                                          -  }
                                                                                                          -
                                                                                                          -  return 0;
                                                                                                          -};
                                                                                                          -
                                                                                                          -var pushNextWord = function (word, queue, wordSet) {
                                                                                                          -  var start = 'a'.charCodeAt(0);
                                                                                                          -  var len = word.length;
                                                                                                          -  var str = '';
                                                                                                          -
                                                                                                          -  wordSet.delete(word);
                                                                                                          -
                                                                                                          -  for (var i = 0; i < len; i++) {
                                                                                                          -    for (var j = 0; j < 26; j++) {
                                                                                                          -      str = word.substr(0, i) + String.fromCharCode(j + start) + word.substr(i + 1);
                                                                                                          -
                                                                                                          -      if (wordSet.has(str)) {
                                                                                                          -        queue.push(str);
                                                                                                          -        wordSet.delete(str);
                                                                                                          -      }
                                                                                                          -    }
                                                                                                          -  }
                                                                                                          -};
                                                                                                          -
                                                                                                          -

                                                                                                          Explain:

                                                                                                          -

                                                                                                          nope.

                                                                                                          -

                                                                                                          Complexity:

                                                                                                          -
                                                                                                            -
                                                                                                          • Time complexity : O(n).
                                                                                                          • -
                                                                                                          • Space complexity : O(n).
                                                                                                          • -
                                                                                                          github
                                                                                                          \ No newline at end of file diff --git a/docs/problem/word-search.html b/docs/problem/word-search.html deleted file mode 100644 index 653583f..0000000 --- a/docs/problem/word-search.html +++ /dev/null @@ -1,117 +0,0 @@ -Word Search - LeetCode javascript solutions

                                                                                                          79. Word Search

                                                                                                          Difficulty:
                                                                                                          Related Topics:
                                                                                                          Similar Questions:

                                                                                                          Problem

                                                                                                          -

                                                                                                          Given a 2D board and a word, find if the word exists in the grid.

                                                                                                          -

                                                                                                          The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

                                                                                                          -

                                                                                                          Example:

                                                                                                          -
                                                                                                          board =
                                                                                                          -[
                                                                                                          -  ['A','B','C','E'],
                                                                                                          -  ['S','F','C','S'],
                                                                                                          -  ['A','D','E','E']
                                                                                                          -]
                                                                                                          -
                                                                                                          -Given word = "ABCCED", return true.
                                                                                                          -Given word = "SEE", return true.
                                                                                                          -Given word = "ABCB", return false.
                                                                                                          -
                                                                                                          -

                                                                                                          Solution 1

                                                                                                          -
                                                                                                          /**
                                                                                                          - * @param {character[][]} board
                                                                                                          - * @param {string} word
                                                                                                          - * @return {boolean}
                                                                                                          - */
                                                                                                          -var exist = function(board, word) {
                                                                                                          -  var len1 = board.length;
                                                                                                          -  var len2 = (board[0] || []).length;
                                                                                                          -  var len3 = word.length;
                                                                                                          -  var visited = null;
                                                                                                          -
                                                                                                          -  if (!len1 || !len2 || !len3) return false;
                                                                                                          -
                                                                                                          -  for (var i = 0; i < len1; i++) {
                                                                                                          -    for (var j = 0; j < len2; j++) {
                                                                                                          -      visited = Array(len1).fill(0).map(_ => Array(len2));
                                                                                                          -      if (helper(board, word, i, j, 0, visited)) return true;
                                                                                                          -    }
                                                                                                          -  }
                                                                                                          -
                                                                                                          -  return false;
                                                                                                          -};
                                                                                                          -
                                                                                                          -var helper = function (board, word, m, n, k, visited) {
                                                                                                          -  if (k === word.length) return true;
                                                                                                          -  if (m < 0 || m >= board.length) return false;
                                                                                                          -  if (n < 0 || n >= board[m].length) return false;
                                                                                                          -  if (visited[m][n]) return false;
                                                                                                          -  if (board[m][n] !== word[k]) return false;
                                                                                                          -
                                                                                                          -  var res = false;
                                                                                                          -
                                                                                                          -  visited[m][n] = true;
                                                                                                          -
                                                                                                          -  res = helper(board, word, m - 1, n, k + 1, visited)
                                                                                                          -        || helper(board, word, m + 1, n, k + 1, visited)
                                                                                                          -        || helper(board, word, m, n - 1, k + 1, visited)
                                                                                                          -        || helper(board, word, m, n + 1, k + 1, visited);
                                                                                                          -
                                                                                                          -  if (!res) visited[m][n] = false;
                                                                                                          -
                                                                                                          -  return res;
                                                                                                          -};
                                                                                                          -
                                                                                                          -

                                                                                                          Explain:

                                                                                                          -

                                                                                                          nope.

                                                                                                          -

                                                                                                          Complexity:

                                                                                                          -
                                                                                                            -
                                                                                                          • Time complexity : O(3 * n * n * k). nboard 字符总数kword 长度。
                                                                                                          • -
                                                                                                          • Space complexity : O(n).
                                                                                                          • -
                                                                                                          -

                                                                                                          Solution 2

                                                                                                          -
                                                                                                          /**
                                                                                                          - * @param {character[][]} board
                                                                                                          - * @param {string} word
                                                                                                          - * @return {boolean}
                                                                                                          - */
                                                                                                          -var exist = function(board, word) {
                                                                                                          -  var len1 = board.length;
                                                                                                          -  var len2 = (board[0] || []).length;
                                                                                                          -  var len3 = word.length;
                                                                                                          -
                                                                                                          -  if (!len1 || !len2 || !len3) return false;
                                                                                                          -
                                                                                                          -  for (var i = 0; i < len1; i++) {
                                                                                                          -    for (var j = 0; j < len2; j++) {
                                                                                                          -      if (helper(board, word, i, j, 0)) return true;
                                                                                                          -    }
                                                                                                          -  }
                                                                                                          -
                                                                                                          -  return false;
                                                                                                          -};
                                                                                                          -
                                                                                                          -var helper = function (board, word, m, n, k) {
                                                                                                          -  if (k === word.length) return true;
                                                                                                          -  if (m < 0 || m >= board.length) return false;
                                                                                                          -  if (n < 0 || n >= board[m].length) return false;
                                                                                                          -  if (board[m][n] !== word[k]) return false;
                                                                                                          -
                                                                                                          -  var res = false;
                                                                                                          -  var char = board[m][n];
                                                                                                          -
                                                                                                          -  board[m][n] = '#';
                                                                                                          -
                                                                                                          -  res = helper(board, word, m - 1, n, k + 1)
                                                                                                          -        || helper(board, word, m + 1, n, k + 1)
                                                                                                          -        || helper(board, word, m, n - 1, k + 1)
                                                                                                          -        || helper(board, word, m, n + 1, k + 1);
                                                                                                          -
                                                                                                          -  if (!res) board[m][n] = char;
                                                                                                          -
                                                                                                          -  return res;
                                                                                                          -};
                                                                                                          -
                                                                                                          -

                                                                                                          Explain:

                                                                                                          -

                                                                                                          上一方法的优化,用过的字符不再用 visited 数组存储,直接修改用过的字符为 #

                                                                                                          -

                                                                                                          Complexity:

                                                                                                          -
                                                                                                            -
                                                                                                          • Time complexity : O(3 * n * k). nboard 字符总数kword 长度。
                                                                                                          • -
                                                                                                          • Space complexity : O(1).
                                                                                                          • -
                                                                                                          github
                                                                                                          \ No newline at end of file diff --git a/docs/problem/zigzag-conversion.html b/docs/problem/zigzag-conversion.html deleted file mode 100644 index c9ce78d..0000000 --- a/docs/problem/zigzag-conversion.html +++ /dev/null @@ -1,54 +0,0 @@ -ZigZag Conversion - LeetCode javascript solutions

                                                                                                          6. ZigZag Conversion

                                                                                                          Difficulty:
                                                                                                          Related Topics:
                                                                                                          Similar Questions:

                                                                                                            Problem

                                                                                                            -

                                                                                                            The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

                                                                                                            -
                                                                                                            P   A   H   N
                                                                                                            -A P L S I I G
                                                                                                            -Y   I   R
                                                                                                            -
                                                                                                            -

                                                                                                            And then read line by line: "PAHNAPLSIIGYIR"

                                                                                                            -

                                                                                                            Write the code that will take a string and make this conversion given a number of rows:

                                                                                                            -
                                                                                                            string convert(string s, int numRows);
                                                                                                            -
                                                                                                            -

                                                                                                            Example 1:

                                                                                                            -
                                                                                                            Input: s = "PAYPALISHIRING", numRows = 3
                                                                                                            -Output: "PAHNAPLSIIGYIR"
                                                                                                            -
                                                                                                            -

                                                                                                            Example 2:

                                                                                                            -
                                                                                                            Input: s = "PAYPALISHIRING", numRows = 4
                                                                                                            -Output: "PINALSIGYAHRPI"
                                                                                                            -Explanation:
                                                                                                            -
                                                                                                            -P     I    N
                                                                                                            -A   L S  I G
                                                                                                            -Y A   H R
                                                                                                            -P     I
                                                                                                            -
                                                                                                            -

                                                                                                            Solution

                                                                                                            -
                                                                                                            /**
                                                                                                            - * @param {string} s
                                                                                                            - * @param {number} numRows
                                                                                                            - * @return {string}
                                                                                                            - */
                                                                                                            -var convert = function(s, numRows) {
                                                                                                            -  if (s.length <= numRows || numRows < 2) return s;
                                                                                                            -  var len = s.length;
                                                                                                            -  var num = 2 * (numRows - 1);
                                                                                                            -  var res = Array(numRows).fill('');
                                                                                                            -  var tmp = 0;
                                                                                                            -  for (var i = 0; i < len; i++) {
                                                                                                            -    tmp = i % num;
                                                                                                            -    if (tmp < numRows) {
                                                                                                            -      res[tmp] += s[i];
                                                                                                            -    } else {
                                                                                                            -      res[num - tmp] += s[i];
                                                                                                            -    }
                                                                                                            -  }
                                                                                                            -  return res.join('');
                                                                                                            -};
                                                                                                            -
                                                                                                            -

                                                                                                            Explain:

                                                                                                            -

                                                                                                            曲线每 2 * (numRows - 1) 个数按规律出现。

                                                                                                            -

                                                                                                            Complexity:

                                                                                                            -
                                                                                                              -
                                                                                                            • Time complexity : O(n).
                                                                                                            • -
                                                                                                            • Space complexity : O(n).
                                                                                                            • -
                                                                                                            github
                                                                                                            \ No newline at end of file diff --git a/docs/tag/array/index.html b/docs/tag/array/index.html deleted file mode 100644 index 8b72e51..0000000 --- a/docs/tag/array/index.html +++ /dev/null @@ -1 +0,0 @@ -LeetCode javascript solutions
                                                                                                            Difficulty:
                                                                                                            IDTitleDifficulty
                                                                                                            1Two SumEasy
                                                                                                            4Median of Two Sorted ArraysHard
                                                                                                            11Container With Most WaterMedium
                                                                                                            153SumMedium
                                                                                                            163Sum ClosestMedium
                                                                                                            184SumMedium
                                                                                                            26Remove Duplicates from Sorted ArrayEasy
                                                                                                            27Remove ElementEasy
                                                                                                            31Next PermutationMedium
                                                                                                            33Search in Rotated Sorted ArrayMedium
                                                                                                            34Search for a RangeMedium
                                                                                                            35Search Insert PositionEasy
                                                                                                            39Combination SumMedium
                                                                                                            40Combination Sum IIMedium
                                                                                                            41First Missing PositiveHard
                                                                                                            42Trapping Rain WaterHard
                                                                                                            45Jump Game IIHard
                                                                                                            48Rotate ImageMedium
                                                                                                            53Maximum SubarrayEasy
                                                                                                            54Spiral MatrixMedium
                                                                                                            55Jump GameMedium
                                                                                                            56Merge IntervalsMedium
                                                                                                            57Insert IntervalHard
                                                                                                            59Spiral Matrix IIMedium
                                                                                                            62Unique PathsMedium
                                                                                                            63Unique Paths IIMedium
                                                                                                            64Minimum Path SumMedium
                                                                                                            66Plus OneEasy
                                                                                                            73Set Matrix ZeroesMedium
                                                                                                            74Search a 2D MatrixMedium
                                                                                                            github
                                                                                                            \ No newline at end of file diff --git a/docs/tag/array/page/2.html b/docs/tag/array/page/2.html deleted file mode 100644 index fd99919..0000000 --- a/docs/tag/array/page/2.html +++ /dev/null @@ -1 +0,0 @@ -LeetCode javascript solutions
                                                                                                            Difficulty:
                                                                                                            IDTitleDifficulty
                                                                                                            75Sort ColorsMedium
                                                                                                            78SubsetsMedium
                                                                                                            79Word SearchMedium
                                                                                                            80Remove Duplicates from Sorted Array IIMedium
                                                                                                            81Search in Rotated Sorted Array IIMedium
                                                                                                            84Largest Rectangle in HistogramHard
                                                                                                            85Maximal RectangleHard
                                                                                                            88Merge Sorted ArrayEasy
                                                                                                            90Subsets IIMedium
                                                                                                            105Construct Binary Tree from Preorder and Inorder TraversalMedium
                                                                                                            106Construct Binary Tree from Inorder and Postorder TraversalMedium
                                                                                                            118Pascal's TriangleEasy
                                                                                                            119Pascal's Triangle IIEasy
                                                                                                            120TriangleMedium
                                                                                                            121Best Time to Buy and Sell StockEasy
                                                                                                            122Best Time to Buy and Sell Stock IIEasy
                                                                                                            123Best Time to Buy and Sell Stock IIIHard
                                                                                                            126Word Ladder IIHard
                                                                                                            128Longest Consecutive SequenceHard
                                                                                                            152Maximum Product SubarrayMedium
                                                                                                            153Find Minimum in Rotated Sorted ArrayMedium
                                                                                                            154Find Minimum in Rotated Sorted Array IIHard
                                                                                                            162Find Peak ElementMedium
                                                                                                            167Two Sum II - Input array is sortedEasy
                                                                                                            169Majority ElementEasy
                                                                                                            238Product of Array Except SelfMedium
                                                                                                            283Move ZeroesEasy
                                                                                                            560Subarray Sum Equals KMedium
                                                                                                            566Reshape the MatrixEasy
                                                                                                            861Flipping an ImageEasy
                                                                                                            github
                                                                                                            \ No newline at end of file diff --git a/docs/tag/array/page/3.html b/docs/tag/array/page/3.html deleted file mode 100644 index b368de0..0000000 --- a/docs/tag/array/page/3.html +++ /dev/null @@ -1 +0,0 @@ -LeetCode javascript solutions
                                                                                                            Difficulty:
                                                                                                            IDTitleDifficulty
                                                                                                            864Image OverlapMedium
                                                                                                            github
                                                                                                            \ No newline at end of file diff --git a/docs/tag/backtracking/index.html b/docs/tag/backtracking/index.html deleted file mode 100644 index 26096a8..0000000 --- a/docs/tag/backtracking/index.html +++ /dev/null @@ -1 +0,0 @@ -LeetCode javascript solutions
                                                                                                            Difficulty:
                                                                                                            IDTitleDifficulty
                                                                                                            10Regular Expression MatchingHard
                                                                                                            17Letter Combinations of a Phone NumberMedium
                                                                                                            22Generate ParenthesesMedium
                                                                                                            37Sudoku SolverHard
                                                                                                            39Combination SumMedium
                                                                                                            40Combination Sum IIMedium
                                                                                                            44Wildcard MatchingHard
                                                                                                            46PermutationsMedium
                                                                                                            47Permutations IIMedium
                                                                                                            51N-QueensHard
                                                                                                            52N-Queens IIHard
                                                                                                            60Permutation SequenceMedium
                                                                                                            77CombinationsMedium
                                                                                                            78SubsetsMedium
                                                                                                            79Word SearchMedium
                                                                                                            89Gray CodeMedium
                                                                                                            90Subsets IIMedium
                                                                                                            93Restore IP AddressesMedium
                                                                                                            126Word Ladder IIHard
                                                                                                            131Palindrome PartitioningMedium
                                                                                                            140Word Break IIHard
                                                                                                            401Binary WatchEasy
                                                                                                            github
                                                                                                            \ No newline at end of file diff --git a/docs/tag/binary-search/index.html b/docs/tag/binary-search/index.html deleted file mode 100644 index 340e100..0000000 --- a/docs/tag/binary-search/index.html +++ /dev/null @@ -1 +0,0 @@ -LeetCode javascript solutions
                                                                                                            Difficulty:
                                                                                                            IDTitleDifficulty
                                                                                                            4Median of Two Sorted ArraysHard
                                                                                                            29Divide Two IntegersMedium
                                                                                                            33Search in Rotated Sorted ArrayMedium
                                                                                                            34Search for a RangeMedium
                                                                                                            35Search Insert PositionEasy
                                                                                                            50Pow(x, n)Medium
                                                                                                            69Sqrt(x)Easy
                                                                                                            74Search a 2D MatrixMedium
                                                                                                            81Search in Rotated Sorted Array IIMedium
                                                                                                            153Find Minimum in Rotated Sorted ArrayMedium
                                                                                                            154Find Minimum in Rotated Sorted Array IIHard
                                                                                                            162Find Peak ElementMedium
                                                                                                            167Two Sum II - Input array is sortedEasy
                                                                                                            174Dungeon GameHard
                                                                                                            240Search a 2D Matrix IIMedium
                                                                                                            4544Sum IIMedium
                                                                                                            github
                                                                                                            \ No newline at end of file diff --git a/docs/tag/bit-manipulation/index.html b/docs/tag/bit-manipulation/index.html deleted file mode 100644 index cfda173..0000000 --- a/docs/tag/bit-manipulation/index.html +++ /dev/null @@ -1 +0,0 @@ -LeetCode javascript solutions
                                                                                                            Difficulty:
                                                                                                            IDTitleDifficulty
                                                                                                            78SubsetsMedium
                                                                                                            136Single NumberEasy
                                                                                                            137Single Number IIMedium
                                                                                                            169Majority ElementEasy
                                                                                                            401Binary WatchEasy
                                                                                                            github
                                                                                                            \ No newline at end of file diff --git a/docs/tag/brainteaser/index.html b/docs/tag/brainteaser/index.html deleted file mode 100644 index f5d6f4e..0000000 --- a/docs/tag/brainteaser/index.html +++ /dev/null @@ -1 +0,0 @@ -LeetCode javascript solutions
                                                                                                            Difficulty:
                                                                                                            IDTitleDifficulty
                                                                                                            292Nim GameEasy
                                                                                                            github
                                                                                                            \ No newline at end of file diff --git a/docs/tag/breadth-first-search/index.html b/docs/tag/breadth-first-search/index.html deleted file mode 100644 index 23d1ba1..0000000 --- a/docs/tag/breadth-first-search/index.html +++ /dev/null @@ -1 +0,0 @@ -LeetCode javascript solutions
                                                                                                            Difficulty:
                                                                                                            IDTitleDifficulty
                                                                                                            101Symmetric TreeEasy
                                                                                                            102Binary Tree Level Order TraversalMedium
                                                                                                            103Binary Tree Zigzag Level Order TraversalMedium
                                                                                                            107Binary Tree Level Order Traversal IIEasy
                                                                                                            111Minimum Depth of Binary TreeEasy
                                                                                                            126Word Ladder IIHard
                                                                                                            127Word LadderMedium
                                                                                                            130Surrounded RegionsMedium
                                                                                                            133Clone GraphMedium
                                                                                                            199Binary Tree Right Side ViewMedium
                                                                                                            200Number of IslandsMedium
                                                                                                            207Course ScheduleMedium
                                                                                                            github
                                                                                                            \ No newline at end of file diff --git a/docs/tag/depth-first-search/index.html b/docs/tag/depth-first-search/index.html deleted file mode 100644 index c5adce8..0000000 --- a/docs/tag/depth-first-search/index.html +++ /dev/null @@ -1 +0,0 @@ -LeetCode javascript solutions
                                                                                                            Difficulty:
                                                                                                            IDTitleDifficulty
                                                                                                            98Validate Binary Search TreeMedium
                                                                                                            99Recover Binary Search TreeHard
                                                                                                            100Same TreeEasy
                                                                                                            101Symmetric TreeEasy
                                                                                                            104Maximum Depth of Binary TreeEasy
                                                                                                            105Construct Binary Tree from Preorder and Inorder TraversalMedium
                                                                                                            106Construct Binary Tree from Inorder and Postorder TraversalMedium
                                                                                                            108Convert Sorted Array to Binary Search TreeEasy
                                                                                                            109Convert Sorted List to Binary Search TreeMedium
                                                                                                            110Balanced Binary TreeEasy
                                                                                                            111Minimum Depth of Binary TreeEasy
                                                                                                            112Path SumEasy
                                                                                                            113Path Sum IIMedium
                                                                                                            114Flatten Binary Tree to Linked ListMedium
                                                                                                            116Populating Next Right Pointers in Each NodeMedium
                                                                                                            117Populating Next Right Pointers in Each Node IIMedium
                                                                                                            124Binary Tree Maximum Path SumHard
                                                                                                            129Sum Root to Leaf NumbersMedium
                                                                                                            130Surrounded RegionsMedium
                                                                                                            133Clone GraphMedium
                                                                                                            199Binary Tree Right Side ViewMedium
                                                                                                            200Number of IslandsMedium
                                                                                                            207Course ScheduleMedium
                                                                                                            547Friend CirclesMedium
                                                                                                            github
                                                                                                            \ No newline at end of file diff --git a/docs/tag/design/index.html b/docs/tag/design/index.html deleted file mode 100644 index c5b0432..0000000 --- a/docs/tag/design/index.html +++ /dev/null @@ -1 +0,0 @@ -LeetCode javascript solutions
                                                                                                            Difficulty:
                                                                                                            IDTitleDifficulty
                                                                                                            146LRU CacheHard
                                                                                                            155Min StackEasy
                                                                                                            173Binary Search Tree IteratorMedium
                                                                                                            208Implement Trie (Prefix Tree)Medium
                                                                                                            github
                                                                                                            \ No newline at end of file diff --git a/docs/tag/divide-and-conquer/index.html b/docs/tag/divide-and-conquer/index.html deleted file mode 100644 index c8a480b..0000000 --- a/docs/tag/divide-and-conquer/index.html +++ /dev/null @@ -1 +0,0 @@ -LeetCode javascript solutions
                                                                                                            Difficulty:
                                                                                                            IDTitleDifficulty
                                                                                                            4Median of Two Sorted ArraysHard
                                                                                                            23Merge k Sorted ListsHard
                                                                                                            53Maximum SubarrayEasy
                                                                                                            169Majority ElementEasy
                                                                                                            215Kth Largest Element in an ArrayMedium
                                                                                                            240Search a 2D Matrix IIMedium
                                                                                                            github
                                                                                                            \ No newline at end of file diff --git a/docs/tag/dynamic-programming/index.html b/docs/tag/dynamic-programming/index.html deleted file mode 100644 index 690ccb7..0000000 --- a/docs/tag/dynamic-programming/index.html +++ /dev/null @@ -1 +0,0 @@ -LeetCode javascript solutions
                                                                                                            Difficulty:
                                                                                                            IDTitleDifficulty
                                                                                                            5Longest Palindromic SubstringMedium
                                                                                                            10Regular Expression MatchingHard
                                                                                                            32Longest Valid ParenthesesHard
                                                                                                            44Wildcard MatchingHard
                                                                                                            53Maximum SubarrayEasy
                                                                                                            62Unique PathsMedium
                                                                                                            63Unique Paths IIMedium
                                                                                                            64Minimum Path SumMedium
                                                                                                            70Climbing StairsEasy
                                                                                                            72Edit DistanceHard
                                                                                                            85Maximal RectangleHard
                                                                                                            87Scramble StringHard
                                                                                                            91Decode WaysMedium
                                                                                                            95Unique Binary Search Trees IIMedium
                                                                                                            96Unique Binary Search TreesMedium
                                                                                                            97Interleaving StringHard
                                                                                                            115Distinct SubsequencesHard
                                                                                                            120TriangleMedium
                                                                                                            121Best Time to Buy and Sell StockEasy
                                                                                                            123Best Time to Buy and Sell Stock IIIHard
                                                                                                            132Palindrome Partitioning IIHard
                                                                                                            139Word BreakMedium
                                                                                                            140Word Break IIHard
                                                                                                            152Maximum Product SubarrayMedium
                                                                                                            174Dungeon GameHard
                                                                                                            198House RobberEasy
                                                                                                            221Maximal SquareMedium
                                                                                                            264Ugly Number IIMedium
                                                                                                            322Coin ChangeMedium
                                                                                                            github
                                                                                                            \ No newline at end of file diff --git a/docs/tag/graph/index.html b/docs/tag/graph/index.html deleted file mode 100644 index 19d7520..0000000 --- a/docs/tag/graph/index.html +++ /dev/null @@ -1 +0,0 @@ -LeetCode javascript solutions
                                                                                                            Difficulty:
                                                                                                            IDTitleDifficulty
                                                                                                            133Clone GraphMedium
                                                                                                            207Course ScheduleMedium
                                                                                                            github
                                                                                                            \ No newline at end of file diff --git a/docs/tag/greedy/index.html b/docs/tag/greedy/index.html deleted file mode 100644 index 86ac7eb..0000000 --- a/docs/tag/greedy/index.html +++ /dev/null @@ -1 +0,0 @@ -LeetCode javascript solutions
                                                                                                            Difficulty:
                                                                                                            IDTitleDifficulty
                                                                                                            44Wildcard MatchingHard
                                                                                                            45Jump Game IIHard
                                                                                                            55Jump GameMedium
                                                                                                            122Best Time to Buy and Sell Stock IIEasy
                                                                                                            134Gas StationMedium
                                                                                                            135CandyHard
                                                                                                            316Remove Duplicate LettersHard
                                                                                                            github
                                                                                                            \ No newline at end of file diff --git a/docs/tag/hash-table/index.html b/docs/tag/hash-table/index.html deleted file mode 100644 index 9249eae..0000000 --- a/docs/tag/hash-table/index.html +++ /dev/null @@ -1 +0,0 @@ -LeetCode javascript solutions
                                                                                                            Difficulty:
                                                                                                            IDTitleDifficulty
                                                                                                            1Two SumEasy
                                                                                                            3Longest Substring Without Repeating CharactersMedium
                                                                                                            184SumMedium
                                                                                                            30Substring with Concatenation of All WordsHard
                                                                                                            36Valid SudokuMedium
                                                                                                            37Sudoku SolverHard
                                                                                                            49Group AnagramsMedium
                                                                                                            76Minimum Window SubstringHard
                                                                                                            85Maximal RectangleHard
                                                                                                            94Binary Tree Inorder TraversalMedium
                                                                                                            136Single NumberEasy
                                                                                                            138Copy List with Random PointerMedium
                                                                                                            149Max Points on a LineHard
                                                                                                            166Fraction to Recurring DecimalMedium
                                                                                                            202Happy NumberEasy
                                                                                                            242Valid AnagramEasy
                                                                                                            4544Sum IIMedium
                                                                                                            560Subarray Sum Equals KMedium
                                                                                                            749Shortest Completing WordMedium
                                                                                                            github
                                                                                                            \ No newline at end of file diff --git a/docs/tag/heap/index.html b/docs/tag/heap/index.html deleted file mode 100644 index 51718c1..0000000 --- a/docs/tag/heap/index.html +++ /dev/null @@ -1 +0,0 @@ -LeetCode javascript solutions
                                                                                                            Difficulty:
                                                                                                            IDTitleDifficulty
                                                                                                            23Merge k Sorted ListsHard
                                                                                                            215Kth Largest Element in an ArrayMedium
                                                                                                            264Ugly Number IIMedium
                                                                                                            github
                                                                                                            \ No newline at end of file diff --git a/docs/tag/linked-list/index.html b/docs/tag/linked-list/index.html deleted file mode 100644 index e2845b5..0000000 --- a/docs/tag/linked-list/index.html +++ /dev/null @@ -1 +0,0 @@ -LeetCode javascript solutions
                                                                                                            Difficulty:
                                                                                                            IDTitleDifficulty
                                                                                                            2Add Two NumbersMedium
                                                                                                            19Remove Nth Node From End of ListMedium
                                                                                                            21Merge Two Sorted ListsEasy
                                                                                                            23Merge k Sorted ListsHard
                                                                                                            24Swap Nodes in PairsMedium
                                                                                                            25Reverse Nodes in k-GroupHard
                                                                                                            61Rotate ListMedium
                                                                                                            82Remove Duplicates from Sorted List IIMedium
                                                                                                            83Remove Duplicates from Sorted ListEasy
                                                                                                            86Partition ListMedium
                                                                                                            92Reverse Linked List IIMedium
                                                                                                            109Convert Sorted List to Binary Search TreeMedium
                                                                                                            138Copy List with Random PointerMedium
                                                                                                            141Linked List CycleEasy
                                                                                                            142Linked List Cycle IIMedium
                                                                                                            143Reorder ListMedium
                                                                                                            147Insertion Sort ListMedium
                                                                                                            148Sort ListMedium
                                                                                                            160Intersection of Two Linked ListsEasy
                                                                                                            206Reverse Linked ListEasy
                                                                                                            234Palindrome Linked ListEasy
                                                                                                            github
                                                                                                            \ No newline at end of file diff --git a/docs/tag/math/index.html b/docs/tag/math/index.html deleted file mode 100644 index 4d6adae..0000000 --- a/docs/tag/math/index.html +++ /dev/null @@ -1 +0,0 @@ -LeetCode javascript solutions
                                                                                                            Difficulty:
                                                                                                            IDTitleDifficulty
                                                                                                            2Add Two NumbersMedium
                                                                                                            7Reverse IntegerEasy
                                                                                                            8String to Integer (atoi)Medium
                                                                                                            9Palindrome NumberEasy
                                                                                                            12Integer to RomanMedium
                                                                                                            13Roman to IntegerEasy
                                                                                                            29Divide Two IntegersMedium
                                                                                                            43Multiply StringsMedium
                                                                                                            50Pow(x, n)Medium
                                                                                                            60Permutation SequenceMedium
                                                                                                            65Valid NumberHard
                                                                                                            66Plus OneEasy
                                                                                                            67Add BinaryEasy
                                                                                                            69Sqrt(x)Easy
                                                                                                            149Max Points on a LineHard
                                                                                                            166Fraction to Recurring DecimalMedium
                                                                                                            168Excel Sheet Column TitleEasy
                                                                                                            171Excel Sheet Column NumberEasy
                                                                                                            172Factorial Trailing ZeroesEasy
                                                                                                            202Happy NumberEasy
                                                                                                            258Add DigitsEasy
                                                                                                            263Ugly NumberEasy
                                                                                                            264Ugly Number IIMedium
                                                                                                            415Add StringsEasy
                                                                                                            537Complex Number MultiplicationMedium
                                                                                                            823Split Array With Same AverageHard
                                                                                                            github
                                                                                                            \ No newline at end of file diff --git a/docs/tag/sort/index.html b/docs/tag/sort/index.html deleted file mode 100644 index 4e0353c..0000000 --- a/docs/tag/sort/index.html +++ /dev/null @@ -1 +0,0 @@ -LeetCode javascript solutions
                                                                                                            Difficulty:
                                                                                                            IDTitleDifficulty
                                                                                                            56Merge IntervalsMedium
                                                                                                            57Insert IntervalHard
                                                                                                            75Sort ColorsMedium
                                                                                                            147Insertion Sort ListMedium
                                                                                                            148Sort ListMedium
                                                                                                            164Maximum GapHard
                                                                                                            179Largest NumberMedium
                                                                                                            242Valid AnagramEasy
                                                                                                            github
                                                                                                            \ No newline at end of file diff --git a/docs/tag/stack/index.html b/docs/tag/stack/index.html deleted file mode 100644 index 3fd5cac..0000000 --- a/docs/tag/stack/index.html +++ /dev/null @@ -1 +0,0 @@ -LeetCode javascript solutions
                                                                                                            Difficulty:
                                                                                                            IDTitleDifficulty
                                                                                                            20Valid ParenthesesEasy
                                                                                                            42Trapping Rain WaterHard
                                                                                                            71Simplify PathMedium
                                                                                                            84Largest Rectangle in HistogramHard
                                                                                                            85Maximal RectangleHard
                                                                                                            94Binary Tree Inorder TraversalMedium
                                                                                                            103Binary Tree Zigzag Level Order TraversalMedium
                                                                                                            144Binary Tree Preorder TraversalMedium
                                                                                                            145Binary Tree Postorder TraversalHard
                                                                                                            150Evaluate Reverse Polish NotationMedium
                                                                                                            155Min StackEasy
                                                                                                            173Binary Search Tree IteratorMedium
                                                                                                            316Remove Duplicate LettersHard
                                                                                                            github
                                                                                                            \ No newline at end of file diff --git a/docs/tag/string/index.html b/docs/tag/string/index.html deleted file mode 100644 index 0f54454..0000000 --- a/docs/tag/string/index.html +++ /dev/null @@ -1 +0,0 @@ -LeetCode javascript solutions
                                                                                                            Difficulty:
                                                                                                            IDTitleDifficulty
                                                                                                            3Longest Substring Without Repeating CharactersMedium
                                                                                                            5Longest Palindromic SubstringMedium
                                                                                                            6ZigZag ConversionMedium
                                                                                                            8String to Integer (atoi)Medium
                                                                                                            10Regular Expression MatchingHard
                                                                                                            12Integer to RomanMedium
                                                                                                            13Roman to IntegerEasy
                                                                                                            14Longest Common PrefixEasy
                                                                                                            17Letter Combinations of a Phone NumberMedium
                                                                                                            20Valid ParenthesesEasy
                                                                                                            22Generate ParenthesesMedium
                                                                                                            28Implement strStr()Easy
                                                                                                            30Substring with Concatenation of All WordsHard
                                                                                                            32Longest Valid ParenthesesHard
                                                                                                            38Count and SayEasy
                                                                                                            43Multiply StringsMedium
                                                                                                            44Wildcard MatchingHard
                                                                                                            49Group AnagramsMedium
                                                                                                            58Length of Last WordEasy
                                                                                                            65Valid NumberHard
                                                                                                            67Add BinaryEasy
                                                                                                            68Text JustificationHard
                                                                                                            71Simplify PathMedium
                                                                                                            72Edit DistanceHard
                                                                                                            76Minimum Window SubstringHard
                                                                                                            87Scramble StringHard
                                                                                                            91Decode WaysMedium
                                                                                                            93Restore IP AddressesMedium
                                                                                                            97Interleaving StringHard
                                                                                                            115Distinct SubsequencesHard
                                                                                                            github
                                                                                                            \ No newline at end of file diff --git a/docs/tag/string/page/2.html b/docs/tag/string/page/2.html deleted file mode 100644 index 0691cf3..0000000 --- a/docs/tag/string/page/2.html +++ /dev/null @@ -1 +0,0 @@ -LeetCode javascript solutions
                                                                                                            Difficulty:
                                                                                                            IDTitleDifficulty
                                                                                                            125Valid PalindromeEasy
                                                                                                            126Word Ladder IIHard
                                                                                                            151Reverse Words in a StringMedium
                                                                                                            165Compare Version NumbersMedium
                                                                                                            537Complex Number MultiplicationMedium
                                                                                                            557Reverse Words in a String IIIEasy
                                                                                                            862Find And Replace in StringMedium
                                                                                                            github
                                                                                                            \ No newline at end of file diff --git a/docs/tag/topological-sort/index.html b/docs/tag/topological-sort/index.html deleted file mode 100644 index 491cdc8..0000000 --- a/docs/tag/topological-sort/index.html +++ /dev/null @@ -1 +0,0 @@ -LeetCode javascript solutions
                                                                                                            Difficulty:
                                                                                                            IDTitleDifficulty
                                                                                                            207Course ScheduleMedium
                                                                                                            github
                                                                                                            \ No newline at end of file diff --git a/docs/tag/tree/index.html b/docs/tag/tree/index.html deleted file mode 100644 index ada67d6..0000000 --- a/docs/tag/tree/index.html +++ /dev/null @@ -1 +0,0 @@ -LeetCode javascript solutions
                                                                                                            Difficulty:
                                                                                                            IDTitleDifficulty
                                                                                                            94Binary Tree Inorder TraversalMedium
                                                                                                            95Unique Binary Search Trees IIMedium
                                                                                                            96Unique Binary Search TreesMedium
                                                                                                            98Validate Binary Search TreeMedium
                                                                                                            99Recover Binary Search TreeHard
                                                                                                            100Same TreeEasy
                                                                                                            101Symmetric TreeEasy
                                                                                                            102Binary Tree Level Order TraversalMedium
                                                                                                            103Binary Tree Zigzag Level Order TraversalMedium
                                                                                                            104Maximum Depth of Binary TreeEasy
                                                                                                            105Construct Binary Tree from Preorder and Inorder TraversalMedium
                                                                                                            106Construct Binary Tree from Inorder and Postorder TraversalMedium
                                                                                                            107Binary Tree Level Order Traversal IIEasy
                                                                                                            108Convert Sorted Array to Binary Search TreeEasy
                                                                                                            110Balanced Binary TreeEasy
                                                                                                            111Minimum Depth of Binary TreeEasy
                                                                                                            112Path SumEasy
                                                                                                            113Path Sum IIMedium
                                                                                                            114Flatten Binary Tree to Linked ListMedium
                                                                                                            116Populating Next Right Pointers in Each NodeMedium
                                                                                                            117Populating Next Right Pointers in Each Node IIMedium
                                                                                                            124Binary Tree Maximum Path SumHard
                                                                                                            129Sum Root to Leaf NumbersMedium
                                                                                                            144Binary Tree Preorder TraversalMedium
                                                                                                            145Binary Tree Postorder TraversalHard
                                                                                                            173Binary Search Tree IteratorMedium
                                                                                                            199Binary Tree Right Side ViewMedium
                                                                                                            226Invert Binary TreeEasy
                                                                                                            617Merge Two Binary TreesEasy
                                                                                                            623Add One Row to TreeMedium
                                                                                                            github
                                                                                                            \ No newline at end of file diff --git a/docs/tag/tree/page/2.html b/docs/tag/tree/page/2.html deleted file mode 100644 index 631598f..0000000 --- a/docs/tag/tree/page/2.html +++ /dev/null @@ -1 +0,0 @@ -LeetCode javascript solutions
                                                                                                            Difficulty:
                                                                                                            IDTitleDifficulty
                                                                                                            669Trim a Binary Search TreeEasy
                                                                                                            github
                                                                                                            \ No newline at end of file diff --git a/docs/tag/trie/index.html b/docs/tag/trie/index.html deleted file mode 100644 index 185ff01..0000000 --- a/docs/tag/trie/index.html +++ /dev/null @@ -1 +0,0 @@ -LeetCode javascript solutions
                                                                                                            Difficulty:
                                                                                                            IDTitleDifficulty
                                                                                                            208Implement Trie (Prefix Tree)Medium
                                                                                                            github
                                                                                                            \ No newline at end of file diff --git a/docs/tag/two-pointers/index.html b/docs/tag/two-pointers/index.html deleted file mode 100644 index 0c2e09c..0000000 --- a/docs/tag/two-pointers/index.html +++ /dev/null @@ -1 +0,0 @@ -LeetCode javascript solutions
                                                                                                            Difficulty:
                                                                                                            IDTitleDifficulty
                                                                                                            3Longest Substring Without Repeating CharactersMedium
                                                                                                            11Container With Most WaterMedium
                                                                                                            153SumMedium
                                                                                                            163Sum ClosestMedium
                                                                                                            184SumMedium
                                                                                                            19Remove Nth Node From End of ListMedium
                                                                                                            26Remove Duplicates from Sorted ArrayEasy
                                                                                                            27Remove ElementEasy
                                                                                                            28Implement strStr()Easy
                                                                                                            30Substring with Concatenation of All WordsHard
                                                                                                            42Trapping Rain WaterHard
                                                                                                            61Rotate ListMedium
                                                                                                            75Sort ColorsMedium
                                                                                                            76Minimum Window SubstringHard
                                                                                                            80Remove Duplicates from Sorted Array IIMedium
                                                                                                            86Partition ListMedium
                                                                                                            88Merge Sorted ArrayEasy
                                                                                                            125Valid PalindromeEasy
                                                                                                            141Linked List CycleEasy
                                                                                                            142Linked List Cycle IIMedium
                                                                                                            167Two Sum II - Input array is sortedEasy
                                                                                                            234Palindrome Linked ListEasy
                                                                                                            283Move ZeroesEasy
                                                                                                            github
                                                                                                            \ No newline at end of file diff --git a/docs/tag/union-find/index.html b/docs/tag/union-find/index.html deleted file mode 100644 index 17ebaef..0000000 --- a/docs/tag/union-find/index.html +++ /dev/null @@ -1 +0,0 @@ -LeetCode javascript solutions
                                                                                                            Difficulty:
                                                                                                            IDTitleDifficulty
                                                                                                            128Longest Consecutive SequenceHard
                                                                                                            130Surrounded RegionsMedium
                                                                                                            200Number of IslandsMedium
                                                                                                            547Friend CirclesMedium
                                                                                                            \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 4637f79..ce6163e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -23,9 +23,9 @@ "dev": true }, "ansi-regex": { - "version": "3.0.0", - "resolved": "http://registry.npm.taobao.org/ansi-regex/download/ansi-regex-3.0.0.tgz", - "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=", + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==", "dev": true }, "ansi-styles": { @@ -212,9 +212,9 @@ } }, "camelcase": { - "version": "4.1.0", - "resolved": "http://registry.npm.taobao.org/camelcase/download/camelcase-4.1.0.tgz", - "integrity": "sha1-1UVjW+HjPFQmScaRc+Xeas+uNN0=", + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", + "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", "dev": true }, "chalk": { @@ -243,22 +243,16 @@ } }, "cliui": { - "version": "4.1.0", - "resolved": "http://registry.npm.taobao.org/cliui/download/cliui-4.1.0.tgz", - "integrity": "sha1-NIQi2+gtgAswIu709qwQvy5NG0k=", + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-5.0.0.tgz", + "integrity": "sha512-PYeGSEmmHM6zvoef2w8TPzlrnNpXIjTipYK780YswmIP9vjxmd6Y2a3CB2Ks6/AU8NHjZugXvo8w3oWM2qnwXA==", "dev": true, "requires": { - "string-width": "2.1.1", - "strip-ansi": "4.0.0", - "wrap-ansi": "2.1.0" + "string-width": "^3.1.0", + "strip-ansi": "^5.2.0", + "wrap-ansi": "^5.1.0" } }, - "code-point-at": { - "version": "1.1.0", - "resolved": "http://registry.npm.taobao.org/code-point-at/download/code-point-at-1.1.0.tgz", - "integrity": "sha1-DQcLTQQ6W+ozovGkDi7bPZpMz3c=", - "dev": true - }, "color-convert": { "version": "1.9.1", "resolved": "http://registry.npm.taobao.org/color-convert/download/color-convert-1.9.1.tgz", @@ -315,17 +309,6 @@ "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=", "dev": true }, - "cross-spawn": { - "version": "5.1.0", - "resolved": "http://registry.npm.taobao.org/cross-spawn/download/cross-spawn-5.1.0.tgz", - "integrity": "sha1-6L0O/uWPz/b4+UUQoKVUu/ojVEk=", - "dev": true, - "requires": { - "lru-cache": "4.1.2", - "shebang-command": "1.2.0", - "which": "1.3.0" - } - }, "css-select": { "version": "1.2.0", "resolved": "http://registry.npm.taobao.org/css-select/download/css-select-1.2.0.tgz", @@ -355,7 +338,7 @@ }, "decamelize": { "version": "1.2.0", - "resolved": "http://registry.npm.taobao.org/decamelize/download/decamelize-1.2.0.tgz", + "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", "integrity": "sha1-9lNNFRSCabIDUue+4m9QH5oZEpA=", "dev": true }, @@ -418,6 +401,12 @@ "domelementtype": "1.3.0" } }, + "emoji-regex": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-7.0.3.tgz", + "integrity": "sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA==", + "dev": true + }, "entities": { "version": "1.1.1", "resolved": "http://registry.npm.taobao.org/entities/download/entities-1.1.1.tgz", @@ -452,21 +441,6 @@ "integrity": "sha1-Cr9PHKpbyx96nYrMbepPqqBLrJs=", "dev": true }, - "execa": { - "version": "0.7.0", - "resolved": "http://registry.npm.taobao.org/execa/download/execa-0.7.0.tgz", - "integrity": "sha1-lEvs00zEHuMqY6n68nrVpl/Fl3c=", - "dev": true, - "requires": { - "cross-spawn": "5.1.0", - "get-stream": "3.0.0", - "is-stream": "1.1.0", - "npm-run-path": "2.0.2", - "p-finally": "1.0.0", - "signal-exit": "3.0.2", - "strip-eof": "1.0.0" - } - }, "fbjs": { "version": "0.6.1", "resolved": "http://registry.npm.taobao.org/fbjs/download/fbjs-0.6.1.tgz", @@ -489,12 +463,12 @@ } }, "find-up": { - "version": "2.1.0", - "resolved": "http://registry.npm.taobao.org/find-up/download/find-up-2.1.0.tgz", - "integrity": "sha1-RdG35QbHF93UgndaK3eSCjwMV6c=", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", + "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", "dev": true, "requires": { - "locate-path": "2.0.0" + "locate-path": "^3.0.0" } }, "follow-redirects": { @@ -518,15 +492,9 @@ } }, "get-caller-file": { - "version": "1.0.2", - "resolved": "http://registry.npm.taobao.org/get-caller-file/download/get-caller-file-1.0.2.tgz", - "integrity": "sha1-9wLmMSfn4jHBYKgMFVSstw1QR+U=", - "dev": true - }, - "get-stream": { - "version": "3.0.0", - "resolved": "http://registry.npm.taobao.org/get-stream/download/get-stream-3.0.0.tgz", - "integrity": "sha1-jpQ9E1jcN1VQVOy+LtsFqhdO3hQ=", + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", "dev": true }, "glob": { @@ -599,12 +567,6 @@ "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", "dev": true }, - "invert-kv": { - "version": "1.0.0", - "resolved": "http://registry.npm.taobao.org/invert-kv/download/invert-kv-1.0.0.tgz", - "integrity": "sha1-EEqOSqym09jNFXqO+L+rLXo//bY=", - "dev": true - }, "is-buffer": { "version": "1.1.6", "resolved": "http://registry.npm.taobao.org/is-buffer/download/is-buffer-1.1.6.tgz", @@ -613,28 +575,16 @@ }, "is-fullwidth-code-point": { "version": "2.0.0", - "resolved": "http://registry.npm.taobao.org/is-fullwidth-code-point/download/is-fullwidth-code-point-2.0.0.tgz", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=", "dev": true }, - "is-stream": { - "version": "1.1.0", - "resolved": "http://registry.npm.taobao.org/is-stream/download/is-stream-1.1.0.tgz", - "integrity": "sha1-EtSj3U5o4Lec6428hBc66A2RykQ=", - "dev": true - }, "isarray": { "version": "1.0.0", "resolved": "http://registry.npm.taobao.org/isarray/download/isarray-1.0.0.tgz", "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=", "dev": true }, - "isexe": { - "version": "2.0.0", - "resolved": "http://registry.npm.taobao.org/isexe/download/isexe-2.0.0.tgz", - "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=", - "dev": true - }, "js-tokens": { "version": "3.0.2", "resolved": "http://registry.npm.taobao.org/js-tokens/download/js-tokens-3.0.2.tgz", @@ -663,23 +613,14 @@ "source-map": "0.4.4" } }, - "lcid": { - "version": "1.0.0", - "resolved": "http://registry.npm.taobao.org/lcid/download/lcid-1.0.0.tgz", - "integrity": "sha1-MIrMr6C8SDo4Z7S28rlQYlHRuDU=", - "dev": true, - "requires": { - "invert-kv": "1.0.0" - } - }, "locate-path": { - "version": "2.0.0", - "resolved": "http://registry.npm.taobao.org/locate-path/download/locate-path-2.0.0.tgz", - "integrity": "sha1-K1aLJl7slExtnA3pw9u7ygNUzY4=", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz", + "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==", "dev": true, "requires": { - "p-locate": "2.0.0", - "path-exists": "3.0.0" + "p-locate": "^3.0.0", + "path-exists": "^3.0.0" } }, "lodash": { @@ -697,31 +638,6 @@ "js-tokens": "3.0.2" } }, - "lru-cache": { - "version": "4.1.2", - "resolved": "http://registry.npm.taobao.org/lru-cache/download/lru-cache-4.1.2.tgz", - "integrity": "sha1-RSNLLm4vKzPaElYkxGZJKaAiTD8=", - "dev": true, - "requires": { - "pseudomap": "1.0.2", - "yallist": "2.1.2" - } - }, - "mem": { - "version": "1.1.0", - "resolved": "http://registry.npm.taobao.org/mem/download/mem-1.1.0.tgz", - "integrity": "sha1-Xt1StIXKHZAP5kiVUFOZoN+kX3Y=", - "dev": true, - "requires": { - "mimic-fn": "1.2.0" - } - }, - "mimic-fn": { - "version": "1.2.0", - "resolved": "http://registry.npm.taobao.org/mimic-fn/download/mimic-fn-1.2.0.tgz", - "integrity": "sha1-ggyGo5M0ZA6ZUWkovQP8qIBX0CI=", - "dev": true - }, "minimatch": { "version": "3.0.4", "resolved": "http://registry.npm.taobao.org/minimatch/download/minimatch-3.0.4.tgz", @@ -752,15 +668,6 @@ "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", "dev": true }, - "npm-run-path": { - "version": "2.0.2", - "resolved": "http://registry.npm.taobao.org/npm-run-path/download/npm-run-path-2.0.2.tgz", - "integrity": "sha1-NakjLfo11wZ7TLLd8jV7GHFTbF8=", - "dev": true, - "requires": { - "path-key": "2.0.1" - } - }, "nth-check": { "version": "1.0.1", "resolved": "http://registry.npm.taobao.org/nth-check/download/nth-check-1.0.1.tgz", @@ -770,12 +677,6 @@ "boolbase": "1.0.0" } }, - "number-is-nan": { - "version": "1.0.1", - "resolved": "http://registry.npm.taobao.org/number-is-nan/download/number-is-nan-1.0.1.tgz", - "integrity": "sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0=", - "dev": true - }, "object-assign": { "version": "2.1.1", "resolved": "http://registry.npm.taobao.org/object-assign/download/object-assign-2.1.1.tgz", @@ -791,45 +692,28 @@ "wrappy": "1.0.2" } }, - "os-locale": { - "version": "2.1.0", - "resolved": "http://registry.npm.taobao.org/os-locale/download/os-locale-2.1.0.tgz", - "integrity": "sha1-QrwpAKa1uL0XN2yOiCtlr8zyS/I=", - "dev": true, - "requires": { - "execa": "0.7.0", - "lcid": "1.0.0", - "mem": "1.1.0" - } - }, - "p-finally": { - "version": "1.0.0", - "resolved": "http://registry.npm.taobao.org/p-finally/download/p-finally-1.0.0.tgz", - "integrity": "sha1-P7z7FbiZpEEjs0ttzBi3JDNqLK4=", - "dev": true - }, "p-limit": { - "version": "1.2.0", - "resolved": "http://registry.npm.taobao.org/p-limit/download/p-limit-1.2.0.tgz", - "integrity": "sha1-DpK2vty1nwIsE9DxlJ3ILRWQnxw=", + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", "dev": true, "requires": { - "p-try": "1.0.0" + "p-try": "^2.0.0" } }, "p-locate": { - "version": "2.0.0", - "resolved": "http://registry.npm.taobao.org/p-locate/download/p-locate-2.0.0.tgz", - "integrity": "sha1-IKAQOyIqcMj9OcwuWAaA893l7EM=", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz", + "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==", "dev": true, "requires": { - "p-limit": "1.2.0" + "p-limit": "^2.0.0" } }, "p-try": { - "version": "1.0.0", - "resolved": "http://registry.npm.taobao.org/p-try/download/p-try-1.0.0.tgz", - "integrity": "sha1-y8ec26+P1CKOE/Yh8rGiN8GyB7M=", + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", "dev": true }, "parse5": { @@ -843,7 +727,7 @@ }, "path-exists": { "version": "3.0.0", - "resolved": "http://registry.npm.taobao.org/path-exists/download/path-exists-3.0.0.tgz", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-3.0.0.tgz", "integrity": "sha1-zg6+ql94yxiSXqfYENe1mwEP1RU=", "dev": true }, @@ -853,12 +737,6 @@ "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", "dev": true }, - "path-key": { - "version": "2.0.1", - "resolved": "http://registry.npm.taobao.org/path-key/download/path-key-2.0.1.tgz", - "integrity": "sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=", - "dev": true - }, "private": { "version": "0.1.8", "resolved": "http://registry.npm.taobao.org/private/download/private-0.1.8.tgz", @@ -880,12 +758,6 @@ "asap": "2.0.6" } }, - "pseudomap": { - "version": "1.0.2", - "resolved": "http://registry.npm.taobao.org/pseudomap/download/pseudomap-1.0.2.tgz", - "integrity": "sha1-8FKijacOYYkX7wqKw0wa5aaChrM=", - "dev": true - }, "q": { "version": "1.5.1", "resolved": "http://registry.npm.taobao.org/q/download/q-1.5.1.tgz", @@ -969,14 +841,14 @@ }, "require-directory": { "version": "2.1.1", - "resolved": "http://registry.npm.taobao.org/require-directory/download/require-directory-2.1.1.tgz", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", "integrity": "sha1-jGStX9MNqxyXbiNE/+f3kqam30I=", "dev": true }, "require-main-filename": { - "version": "1.0.1", - "resolved": "http://registry.npm.taobao.org/require-main-filename/download/require-main-filename-1.0.1.tgz", - "integrity": "sha1-l/cXtp1IeE9fUmpsWqj/3aBVpNE=", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz", + "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", "dev": true }, "safe-buffer": { @@ -993,40 +865,19 @@ }, "set-blocking": { "version": "2.0.0", - "resolved": "http://registry.npm.taobao.org/set-blocking/download/set-blocking-2.0.0.tgz", + "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", "integrity": "sha1-BF+XgtARrppoA93TgrJDkrPYkPc=", "dev": true }, - "shebang-command": { - "version": "1.2.0", - "resolved": "http://registry.npm.taobao.org/shebang-command/download/shebang-command-1.2.0.tgz", - "integrity": "sha1-RKrGW2lbAzmJaMOfNj/uXer98eo=", - "dev": true, - "requires": { - "shebang-regex": "1.0.0" - } - }, - "shebang-regex": { - "version": "1.0.0", - "resolved": "http://registry.npm.taobao.org/shebang-regex/download/shebang-regex-1.0.0.tgz", - "integrity": "sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM=", - "dev": true - }, "showdown": { - "version": "1.8.6", - "resolved": "http://registry.npm.taobao.org/showdown/download/showdown-1.8.6.tgz", - "integrity": "sha1-kepO47elRIqspoIKTifmkMatdxw=", + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/showdown/-/showdown-1.9.1.tgz", + "integrity": "sha512-9cGuS382HcvExtf5AHk7Cb4pAeQQ+h0eTr33V1mu+crYWV4KvWAw6el92bDrqGEk5d46Ai/fhbEUwqJ/mTCNEA==", "dev": true, "requires": { - "yargs": "10.1.2" + "yargs": "^14.2" } }, - "signal-exit": { - "version": "3.0.2", - "resolved": "http://registry.npm.taobao.org/signal-exit/download/signal-exit-3.0.2.tgz", - "integrity": "sha1-tf3AjxKH6hF4Yo5BXiUTK3NkbG0=", - "dev": true - }, "source-map": { "version": "0.4.4", "resolved": "http://registry.npm.taobao.org/source-map/download/source-map-0.4.4.tgz", @@ -1036,6 +887,17 @@ "amdefine": "1.0.1" } }, + "string-width": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz", + "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==", + "dev": true, + "requires": { + "emoji-regex": "^7.0.1", + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^5.1.0" + } + }, "string_decoder": { "version": "1.1.1", "resolved": "http://registry.npm.taobao.org/string_decoder/download/string_decoder-1.1.1.tgz", @@ -1045,31 +907,15 @@ "safe-buffer": "5.1.2" } }, - "string-width": { - "version": "2.1.1", - "resolved": "http://registry.npm.taobao.org/string-width/download/string-width-2.1.1.tgz", - "integrity": "sha1-q5Pyeo3BPSjKyBXEYhQ6bZASrp4=", - "dev": true, - "requires": { - "is-fullwidth-code-point": "2.0.0", - "strip-ansi": "4.0.0" - } - }, "strip-ansi": { - "version": "4.0.0", - "resolved": "http://registry.npm.taobao.org/strip-ansi/download/strip-ansi-4.0.0.tgz", - "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", "dev": true, "requires": { - "ansi-regex": "3.0.0" + "ansi-regex": "^4.1.0" } }, - "strip-eof": { - "version": "1.0.0", - "resolved": "http://registry.npm.taobao.org/strip-eof/download/strip-eof-1.0.0.tgz", - "integrity": "sha1-u0P/VZim6wXYm1n80SnJgzE2Br8=", - "dev": true - }, "supports-color": { "version": "5.4.0", "resolved": "http://registry.npm.taobao.org/supports-color/download/supports-color-5.4.0.tgz", @@ -1115,66 +961,21 @@ "integrity": "sha1-DjaExsuZlbQ+/J3wPkw2XZX9nMA=", "dev": true }, - "which": { - "version": "1.3.0", - "resolved": "http://registry.npm.taobao.org/which/download/which-1.3.0.tgz", - "integrity": "sha1-/wS9/AEO5UfXgL7DjhrBwnd9JTo=", - "dev": true, - "requires": { - "isexe": "2.0.0" - } - }, "which-module": { "version": "2.0.0", - "resolved": "http://registry.npm.taobao.org/which-module/download/which-module-2.0.0.tgz", + "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.0.tgz", "integrity": "sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho=", "dev": true }, "wrap-ansi": { - "version": "2.1.0", - "resolved": "http://registry.npm.taobao.org/wrap-ansi/download/wrap-ansi-2.1.0.tgz", - "integrity": "sha1-2Pw9KE3QV5T+hJc8rs3Rz4JP3YU=", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-5.1.0.tgz", + "integrity": "sha512-QC1/iN/2/RPVJ5jYK8BGttj5z83LmSKmvbvrXPNCLZSEb32KKVDJDl/MOt2N01qU2H/FkzEa9PKto1BqDjtd7Q==", "dev": true, "requires": { - "string-width": "1.0.2", - "strip-ansi": "3.0.1" - }, - "dependencies": { - "ansi-regex": { - "version": "2.1.1", - "resolved": "http://registry.npm.taobao.org/ansi-regex/download/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=", - "dev": true - }, - "is-fullwidth-code-point": { - "version": "1.0.0", - "resolved": "http://registry.npm.taobao.org/is-fullwidth-code-point/download/is-fullwidth-code-point-1.0.0.tgz", - "integrity": "sha1-754xOG8DGn8NZDr4L95QxFfvAMs=", - "dev": true, - "requires": { - "number-is-nan": "1.0.1" - } - }, - "string-width": { - "version": "1.0.2", - "resolved": "http://registry.npm.taobao.org/string-width/download/string-width-1.0.2.tgz", - "integrity": "sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=", - "dev": true, - "requires": { - "code-point-at": "1.1.0", - "is-fullwidth-code-point": "1.0.0", - "strip-ansi": "3.0.1" - } - }, - "strip-ansi": { - "version": "3.0.1", - "resolved": "http://registry.npm.taobao.org/strip-ansi/download/strip-ansi-3.0.1.tgz", - "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", - "dev": true, - "requires": { - "ansi-regex": "2.1.1" - } - } + "ansi-styles": "^3.2.0", + "string-width": "^3.0.0", + "strip-ansi": "^5.0.0" } }, "wrappy": { @@ -1184,44 +985,38 @@ "dev": true }, "y18n": { - "version": "3.2.1", - "resolved": "http://registry.npm.taobao.org/y18n/download/y18n-3.2.1.tgz", - "integrity": "sha1-bRX7qITAhnnA136I53WegR4H+kE=", - "dev": true - }, - "yallist": { - "version": "2.1.2", - "resolved": "http://registry.npm.taobao.org/yallist/download/yallist-2.1.2.tgz", - "integrity": "sha1-HBH5IY8HYImkfdUS+TxmmaaoHVI=", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.0.tgz", + "integrity": "sha512-r9S/ZyXu/Xu9q1tYlpsLIsa3EeLXXk0VwlxqTcFRfg9EhMW+17kbt9G0NrgCmhGb5vT2hyhJZLfDGx+7+5Uj/w==", "dev": true }, "yargs": { - "version": "10.1.2", - "resolved": "http://registry.npm.taobao.org/yargs/download/yargs-10.1.2.tgz", - "integrity": "sha1-RU0HTCsWpRpD4vt4B+T53mnMtcU=", + "version": "14.2.3", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-14.2.3.tgz", + "integrity": "sha512-ZbotRWhF+lkjijC/VhmOT9wSgyBQ7+zr13+YLkhfsSiTriYsMzkTUFP18pFhWwBeMa5gUc1MzbhrO6/VB7c9Xg==", "dev": true, "requires": { - "cliui": "4.1.0", - "decamelize": "1.2.0", - "find-up": "2.1.0", - "get-caller-file": "1.0.2", - "os-locale": "2.1.0", - "require-directory": "2.1.1", - "require-main-filename": "1.0.1", - "set-blocking": "2.0.0", - "string-width": "2.1.1", - "which-module": "2.0.0", - "y18n": "3.2.1", - "yargs-parser": "8.1.0" + "cliui": "^5.0.0", + "decamelize": "^1.2.0", + "find-up": "^3.0.0", + "get-caller-file": "^2.0.1", + "require-directory": "^2.1.1", + "require-main-filename": "^2.0.0", + "set-blocking": "^2.0.0", + "string-width": "^3.0.0", + "which-module": "^2.0.0", + "y18n": "^4.0.0", + "yargs-parser": "^15.0.1" } }, "yargs-parser": { - "version": "8.1.0", - "resolved": "http://registry.npm.taobao.org/yargs-parser/download/yargs-parser-8.1.0.tgz", - "integrity": "sha1-8TdqM7Ziml0GN4KUTacyYx6WaVA=", + "version": "15.0.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-15.0.1.tgz", + "integrity": "sha512-0OAMV2mAZQrs3FkNpDQcBk1x5HXb8X4twADss4S0Iuk+2dGnLOE/fRHrsYm542GduMveyA77OF4wrNJuanRCWw==", "dev": true, "requires": { - "camelcase": "4.1.0" + "camelcase": "^5.0.0", + "decamelize": "^1.2.0" } } } diff --git a/package.json b/package.json index 96ea87c..8682ec3 100644 --- a/package.json +++ b/package.json @@ -8,6 +8,7 @@ }, "scripts": { "build": "node build/index.js", + "create:random": "node create/random.js", "create": "node create/index.js" }, "repository": { @@ -30,6 +31,6 @@ "fs-extra": "^6.0.0", "highlight.js": "^9.12.0", "react-jsx": "^1.0.0", - "showdown": "^1.8.6" + "showdown": "^1.9.1" } }