\ No newline at end of file
diff --git a/docs/difficulty/easy/page/2.html b/docs/difficulty/easy/page/2.html
new file mode 100644
index 0000000..ada671a
--- /dev/null
+++ b/docs/difficulty/easy/page/2.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/difficulty/easy/page/3.html b/docs/difficulty/easy/page/3.html
new file mode 100644
index 0000000..18cc0da
--- /dev/null
+++ b/docs/difficulty/easy/page/3.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/difficulty/easy/page/4.html b/docs/difficulty/easy/page/4.html
new file mode 100644
index 0000000..ccb6fcf
--- /dev/null
+++ b/docs/difficulty/easy/page/4.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/difficulty/easy/page/5.html b/docs/difficulty/easy/page/5.html
new file mode 100644
index 0000000..1d09a58
--- /dev/null
+++ b/docs/difficulty/easy/page/5.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/difficulty/hard/index.html b/docs/difficulty/hard/index.html
new file mode 100644
index 0000000..dfc939b
--- /dev/null
+++ b/docs/difficulty/hard/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/difficulty/hard/page/2.html b/docs/difficulty/hard/page/2.html
new file mode 100644
index 0000000..74af0c8
--- /dev/null
+++ b/docs/difficulty/hard/page/2.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/difficulty/hard/page/3.html b/docs/difficulty/hard/page/3.html
new file mode 100644
index 0000000..5b91fcd
--- /dev/null
+++ b/docs/difficulty/hard/page/3.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/difficulty/medium/index.html b/docs/difficulty/medium/index.html
new file mode 100644
index 0000000..ac692c9
--- /dev/null
+++ b/docs/difficulty/medium/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/difficulty/medium/page/2.html b/docs/difficulty/medium/page/2.html
new file mode 100644
index 0000000..33e764f
--- /dev/null
+++ b/docs/difficulty/medium/page/2.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/difficulty/medium/page/3.html b/docs/difficulty/medium/page/3.html
new file mode 100644
index 0000000..6ac0e68
--- /dev/null
+++ b/docs/difficulty/medium/page/3.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/difficulty/medium/page/4.html b/docs/difficulty/medium/page/4.html
new file mode 100644
index 0000000..3feff5f
--- /dev/null
+++ b/docs/difficulty/medium/page/4.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/difficulty/medium/page/5.html b/docs/difficulty/medium/page/5.html
new file mode 100644
index 0000000..5ae8f3d
--- /dev/null
+++ b/docs/difficulty/medium/page/5.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/difficulty/medium/page/6.html b/docs/difficulty/medium/page/6.html
new file mode 100644
index 0000000..a011959
--- /dev/null
+++ b/docs/difficulty/medium/page/6.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/difficulty/medium/page/7.html b/docs/difficulty/medium/page/7.html
new file mode 100644
index 0000000..6058212
--- /dev/null
+++ b/docs/difficulty/medium/page/7.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/difficulty/medium/page/8.html b/docs/difficulty/medium/page/8.html
new file mode 100644
index 0000000..e98136f
--- /dev/null
+++ b/docs/difficulty/medium/page/8.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/difficulty/medium/page/9.html b/docs/difficulty/medium/page/9.html
new file mode 100644
index 0000000..7bb321d
--- /dev/null
+++ b/docs/difficulty/medium/page/9.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/index.html b/docs/index.html
new file mode 100644
index 0000000..8aae285
--- /dev/null
+++ b/docs/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/page/10.html b/docs/page/10.html
new file mode 100644
index 0000000..d9f4a2b
--- /dev/null
+++ b/docs/page/10.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/page/11.html b/docs/page/11.html
new file mode 100644
index 0000000..cc6dd58
--- /dev/null
+++ b/docs/page/11.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/page/12.html b/docs/page/12.html
new file mode 100644
index 0000000..ebfc9ec
--- /dev/null
+++ b/docs/page/12.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/page/13.html b/docs/page/13.html
new file mode 100644
index 0000000..b21ab06
--- /dev/null
+++ b/docs/page/13.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/page/14.html b/docs/page/14.html
new file mode 100644
index 0000000..59f98ab
--- /dev/null
+++ b/docs/page/14.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/page/15.html b/docs/page/15.html
new file mode 100644
index 0000000..2cc4903
--- /dev/null
+++ b/docs/page/15.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/page/16.html b/docs/page/16.html
new file mode 100644
index 0000000..ff1a7b3
--- /dev/null
+++ b/docs/page/16.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/page/2.html b/docs/page/2.html
new file mode 100644
index 0000000..999cfb2
--- /dev/null
+++ b/docs/page/2.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/page/3.html b/docs/page/3.html
new file mode 100644
index 0000000..c741bd7
--- /dev/null
+++ b/docs/page/3.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/page/4.html b/docs/page/4.html
new file mode 100644
index 0000000..3ecd8ed
--- /dev/null
+++ b/docs/page/4.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/page/5.html b/docs/page/5.html
new file mode 100644
index 0000000..90fd4b6
--- /dev/null
+++ b/docs/page/5.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/page/6.html b/docs/page/6.html
new file mode 100644
index 0000000..8beb35a
--- /dev/null
+++ b/docs/page/6.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/page/7.html b/docs/page/7.html
new file mode 100644
index 0000000..59379db
--- /dev/null
+++ b/docs/page/7.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/page/8.html b/docs/page/8.html
new file mode 100644
index 0000000..ff67aa8
--- /dev/null
+++ b/docs/page/8.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/page/9.html b/docs/page/9.html
new file mode 100644
index 0000000..aab976d
--- /dev/null
+++ b/docs/page/9.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
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.**
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++;
+ } elseif (sum > target) {
+ r--;
+ } else {
+ return sum;
+ }
+ if (Math.abs(sum - target) < Math.abs(res - target)) res = sum;
+ }
+ }
+ return res;
+};
+
\ No newline at end of file
diff --git a/docs/problem/3sum.html b/docs/problem/3sum.html
new file mode 100644
index 0000000..412106a
--- /dev/null
+++ b/docs/problem/3sum.html
@@ -0,0 +1,52 @@
+3Sum - LeetCode javascript solutions
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++;
+ } elseif (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).
+
\ No newline at end of file
diff --git a/docs/problem/4sum-ii.html b/docs/problem/4sum-ii.html
new file mode 100644
index 0000000..31cfcbb
--- /dev/null
+++ b/docs/problem/4sum-ii.html
@@ -0,0 +1,55 @@
+4Sum II - LeetCode javascript solutions
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.
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/4sum.html b/docs/problem/4sum.html
new file mode 100644
index 0000000..2d56f20
--- /dev/null
+++ b/docs/problem/4sum.html
@@ -0,0 +1,72 @@
+4Sum - LeetCode javascript solutions
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++;
+ } elseif (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;
+};
+
\ 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
new file mode 100644
index 0000000..43519f0
--- /dev/null
+++ b/docs/problem/add-one-row-to-tree.html
@@ -0,0 +1,98 @@
+Add One Row to Tree - LeetCode javascript solutions
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'soriginal 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.
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 :
+
\ No newline at end of file
diff --git a/docs/problem/add-two-numbers-ii.html b/docs/problem/add-two-numbers-ii.html
new file mode 100644
index 0000000..0d356a0
--- /dev/null
+++ b/docs/problem/add-two-numbers-ii.html
@@ -0,0 +1,82 @@
+Add Two Numbers II - LeetCode javascript solutions
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.
\ No newline at end of file
diff --git a/docs/problem/add-two-numbers.html b/docs/problem/add-two-numbers.html
new file mode 100644
index 0000000..de3c79c
--- /dev/null
+++ b/docs/problem/add-two-numbers.html
@@ -0,0 +1,47 @@
+Add Two Numbers - LeetCode javascript solutions
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.
/**
+ * 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)).
+
\ No newline at end of file
diff --git a/docs/problem/all-ancestors-of-a-node-in-a-directed-acyclic-graph.html b/docs/problem/all-ancestors-of-a-node-in-a-directed-acyclic-graph.html
new file mode 100644
index 0000000..14e2957
--- /dev/null
+++ b/docs/problem/all-ancestors-of-a-node-in-a-directed-acyclic-graph.html
@@ -0,0 +1,79 @@
+All Ancestors of a Node in a Directed Acyclic Graph - LeetCode javascript solutions
2192. All Ancestors of a Node in a Directed Acyclic Graph
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 listanswer**, 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:
+
+
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, and2 do not have any ancestors.
+- Node3 has two ancestors 0and1.
+- Node4 has two ancestors 0and2.
+- Node5 has three ancestors 0, 1, and3.
+- Node6 has five ancestors 0, 1, 2, 3, and4.
+- Node7 has four ancestors 0, 1, 2, and3.
+
+
Example 2:
+
+
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.
+- Node0 does not have any ancestor.
+- Node1 has one ancestor 0.
+- Node2 has two ancestors 0and1.
+- Node3 has three ancestors 0, 1, and2.
+- Node4 has four ancestors 0, 1, 2, and3.
+
+
+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
+
/**
+ * @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(newSet(res));
+ }
+ return ancestorMap[i];
+};
+
+
Explain:
+
nope.
+
Complexity:
+
+
Time complexity : O(n).
+
Space complexity : O(n).
+
\ No newline at end of file
diff --git a/docs/problem/all-nodes-distance-k-in-binary-tree.html b/docs/problem/all-nodes-distance-k-in-binary-tree.html
new file mode 100644
index 0000000..69d85a1
--- /dev/null
+++ b/docs/problem/all-nodes-distance-k-in-binary-tree.html
@@ -0,0 +1,80 @@
+All Nodes Distance K in Binary Tree - LeetCode javascript solutions
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:
+
+
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 2fromthe target node (withvalue5) have values 7, 4, and1.
+
\ No newline at end of file
diff --git a/docs/problem/all-possible-full-binary-trees.html b/docs/problem/all-possible-full-binary-trees.html
new file mode 100644
index 0000000..823b17b
--- /dev/null
+++ b/docs/problem/all-possible-full-binary-trees.html
@@ -0,0 +1,61 @@
+All Possible Full Binary Trees - LeetCode javascript solutions
Given an integer n, return **a list of all possible *full binary trees* with** nnodes. 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:
+
+
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
+
/**
+ * 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)).
+
\ No newline at end of file
diff --git a/docs/problem/amount-of-time-for-binary-tree-to-be-infected.html b/docs/problem/amount-of-time-for-binary-tree-to-be-infected.html
new file mode 100644
index 0000000..63a14b0
--- /dev/null
+++ b/docs/problem/amount-of-time-for-binary-tree-to-be-infected.html
@@ -0,0 +1,85 @@
+Amount of Time for Binary Tree to Be Infected - LeetCode javascript solutions
2385. Amount of Time for Binary Tree to Be Infected
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 *booleanelementsanswer, whereanswer[i]istrueif the subarraynums[l[i]], nums[l[i]+1], ... , nums[r[i]]* can be rearranged to form an arithmetic sequence, and** falseotherwise.
+
+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
+
/**
+ * @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) {
+ returnfalse;
+ }
+ }
+ returntrue;
+};
+
+
Explain:
+
nope.
+
Complexity:
+
+
Time complexity : O(n * m).
+
Space complexity : O(n).
+
\ No newline at end of file
diff --git a/docs/problem/assign-cookies.html b/docs/problem/assign-cookies.html
new file mode 100644
index 0000000..8b53dfb
--- /dev/null
+++ b/docs/problem/assign-cookies.html
@@ -0,0 +1,50 @@
+Assign Cookies - LeetCode javascript solutions
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 and2 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 onlymake the child whose greed factor is1 content.
+You need to output 1.
+
+
Example 2:
+
Input: g = [1,2], s = [1,2,3]
+Output: 2
+Explanation: You have 2 children and3 cookies. The greed factors of2 children are 1, 2.
+You have 3 cookies and their sizes are big enough to gratify all ofthe 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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/asteroid-collision.html b/docs/problem/asteroid-collision.html
new file mode 100644
index 0000000..8f5b843
--- /dev/null
+++ b/docs/problem/asteroid-collision.html
@@ -0,0 +1,60 @@
+Asteroid Collision - LeetCode javascript solutions
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 10and-5 collide resulting in10. The 5and10 never collide.
+
+
Example 2:
+
Input: asteroids = [8,-8]
+Output: []
+Explanation: The 8and-8 collide exploding each other.
+
+
Example 3:
+
Input: asteroids = [10,2,-5]
+Output: [10]
+Explanation: The 2and-5 collide resulting in-5. The 10and-5 collide resulting in10.
+
+
+Constraints:
+
+
2 <= asteroids.length <= 104
+
-1000 <= asteroids[i] <= 1000
+
asteroids[i] != 0
+
+
Solution
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/backspace-string-compare.html b/docs/problem/backspace-string-compare.html
new file mode 100644
index 0000000..541c888
--- /dev/null
+++ b/docs/problem/backspace-string-compare.html
@@ -0,0 +1,62 @@
+Backspace String Compare - LeetCode javascript solutions
Given two strings s and t, return trueif 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
+
/**
+ * @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]) returnfalse;
+ i--;
+ j--;
+ }
+ returntrue;
+};
+
+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).
+
\ No newline at end of file
diff --git a/docs/problem/bag-of-tokens.html b/docs/problem/bag-of-tokens.html
new file mode 100644
index 0000000..2acb262
--- /dev/null
+++ b/docs/problem/bag-of-tokens.html
@@ -0,0 +1,69 @@
+Bag of Tokens - LeetCode javascript solutions
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 tokeni.
+
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 leasttokens[i], you may play tokeni, losing tokens[i] power and gaining 1 score.
+
Face-down: If your current score is at least1, you may play tokeni, 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 token1 (100) face-up, reducing your power to 50 and increasing your score to 1.
+
There is no need to play token0, 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 token0 (100) face-up, reducing power to 100 and increasing score to 1.
+
Play token3 (400) face-down, increasing power to 500 and reducing score to 0.
+
Play token1 (200) face-up, reducing power to 300 and increasing score to 1.
+
Play token2 (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
+
/**
+ * @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);
+ } elseif (score > 0) {
+ score -= 1;
+ power += tokens[right--];
+ } else {
+ break;
+ }
+ }
+ return maxScore;
+};
+
+
Explain:
+
nope.
+
Complexity:
+
+
Time complexity : O(n * log(n)).
+
Space complexity : O(1).
+
\ No newline at end of file
diff --git a/docs/problem/balanced-binary-tree.html b/docs/problem/balanced-binary-tree.html
new file mode 100644
index 0000000..9b51130
--- /dev/null
+++ b/docs/problem/balanced-binary-tree.html
@@ -0,0 +1,55 @@
+Balanced Binary Tree - LeetCode javascript solutions
\ 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
new file mode 100644
index 0000000..d201d70
--- /dev/null
+++ b/docs/problem/best-time-to-buy-and-sell-stock-ii.html
@@ -0,0 +1,43 @@
+Best Time to Buy and Sell Stock II - LeetCode javascript solutions
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).
Input: [1,2,3,4,5]
+Output: 4
+Explanation: Buy onday1 (price = 1) and sell onday5 (price = 5), profit = 5-1 = 4.
+ Note that you cannot buy onday1, buy onday2and sell them later, as you are
+ engaging multiple transactions atthe same time. You must sell before buying again.
+
+
Example 3:
+
Input: [7,6,4,3,1]
+Output:0
+Explanation: In thiscase, 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).
+
\ 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
new file mode 100644
index 0000000..f039dfa
--- /dev/null
+++ b/docs/problem/best-time-to-buy-and-sell-stock-iii.html
@@ -0,0 +1,49 @@
+Best Time to Buy and Sell Stock III - LeetCode javascript solutions
Input: [1,2,3,4,5]
+Output: 4
+Explanation: Buy onday1 (price = 1) and sell onday5 (price = 5), profit = 5-1 = 4.
+ Note that you cannot buy onday1, buy onday2and sell them later, as you are
+ engaging multiple transactions atthe same time. You must sell before buying again.
+
+
Example 3:
+
Input: [7,6,4,3,1]
+Output:0
+Explanation: In thiscase, 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).
+
\ No newline at end of file
diff --git a/docs/problem/best-time-to-buy-and-sell-stock-with-transaction-fee.html b/docs/problem/best-time-to-buy-and-sell-stock-with-transaction-fee.html
new file mode 100644
index 0000000..474678c
--- /dev/null
+++ b/docs/problem/best-time-to-buy-and-sell-stock-with-transaction-fee.html
@@ -0,0 +1,55 @@
+Best Time to Buy and Sell Stock with Transaction Fee - LeetCode javascript solutions
714. Best Time to Buy and Sell Stock with Transaction Fee
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.
+
/**
+ * @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;
+ }
+ returnMath.max(hasStock, hasNoStock);
+};
+
+
Explain:
+
nope.
+
Complexity:
+
+
Time complexity : O(n).
+
Space complexity : O(1).
+
\ 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
new file mode 100644
index 0000000..536f4ff
--- /dev/null
+++ b/docs/problem/best-time-to-buy-and-sell-stock.html
@@ -0,0 +1,38 @@
+Best Time to Buy and Sell Stock - LeetCode javascript solutions
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 onday2 (price = 1) and sell onday5 (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 thiscase, 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];
+ elseif (prices[i] - minPrice > maxProfit) maxProfit = prices[i] - minPrice;
+ }
+ return maxProfit;
+};
+
+
Explain:
+
nope.
+
Complexity:
+
+
Time complexity : O(n).
+
Space complexity : O(1).
+
\ No newline at end of file
diff --git a/docs/problem/binary-search-tree-iterator.html b/docs/problem/binary-search-tree-iterator.html
new file mode 100644
index 0000000..a75094d
--- /dev/null
+++ b/docs/problem/binary-search-tree-iterator.html
@@ -0,0 +1,62 @@
+Binary Search Tree Iterator - LeetCode javascript solutions
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: 9exists in nums and its indexis4
+
+
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
+
/**
+ * @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;
+ } elseif (nums[mid] > target) {
+ right = mid - 1;
+ } else {
+ left = mid + 1;
+ }
+ }
+ return-1;
+};
+
+
Explain:
+
nope.
+
Complexity:
+
+
Time complexity : O(log(n)).
+
Space complexity : O(1).
+
\ No newline at end of file
diff --git a/docs/problem/binary-tree-inorder-traversal.html b/docs/problem/binary-tree-inorder-traversal.html
new file mode 100644
index 0000000..162b440
--- /dev/null
+++ b/docs/problem/binary-tree-inorder-traversal.html
@@ -0,0 +1,82 @@
+Binary Tree Inorder Traversal - LeetCode javascript solutions
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).
+
\ 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
new file mode 100644
index 0000000..9785b97
--- /dev/null
+++ b/docs/problem/binary-tree-level-order-traversal-ii.html
@@ -0,0 +1,159 @@
+Binary Tree Level Order Traversal II - LeetCode javascript solutions
/**
+ * 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).
+
\ 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
new file mode 100644
index 0000000..8a52651
--- /dev/null
+++ b/docs/problem/binary-tree-level-order-traversal.html
@@ -0,0 +1,92 @@
+Binary Tree Level Order Traversal - LeetCode javascript solutions
\ 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
new file mode 100644
index 0000000..0b7d984
--- /dev/null
+++ b/docs/problem/binary-tree-maximum-path-sum.html
@@ -0,0 +1,56 @@
+Binary Tree Maximum Path Sum - LeetCode javascript solutions
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.
/**
+ * 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) return0;
+ var left = Math.max(maxSum(node.left), 0);
+ var right = Math.max(maxSum(node.right), 0);
+ max = Math.max(left + right + node.val, max);
+ returnMath.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).
+
\ No newline at end of file
diff --git a/docs/problem/binary-tree-postorder-traversal.html b/docs/problem/binary-tree-postorder-traversal.html
new file mode 100644
index 0000000..dcbeb41
--- /dev/null
+++ b/docs/problem/binary-tree-postorder-traversal.html
@@ -0,0 +1,82 @@
+Binary Tree Postorder Traversal - LeetCode javascript solutions
/**
+ * 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).
+
\ No newline at end of file
diff --git a/docs/problem/binary-tree-preorder-traversal.html b/docs/problem/binary-tree-preorder-traversal.html
new file mode 100644
index 0000000..55ab9fa
--- /dev/null
+++ b/docs/problem/binary-tree-preorder-traversal.html
@@ -0,0 +1,78 @@
+Binary Tree Preorder Traversal - LeetCode javascript solutions
/**
+ * 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).
+
\ 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
new file mode 100644
index 0000000..41655cf
--- /dev/null
+++ b/docs/problem/binary-tree-right-side-view.html
@@ -0,0 +1,77 @@
+Binary Tree Right Side View - LeetCode javascript solutions
\ 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
new file mode 100644
index 0000000..8c4e097
--- /dev/null
+++ b/docs/problem/binary-tree-zigzag-level-order-traversal.html
@@ -0,0 +1,65 @@
+Binary Tree Zigzag Level Order Traversal - LeetCode javascript solutions
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
+ / \
+ 920
+ / \
+ 157
+
+
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).
+
\ No newline at end of file
diff --git a/docs/problem/binary-trees-with-factors.html b/docs/problem/binary-trees-with-factors.html
new file mode 100644
index 0000000..af983d5
--- /dev/null
+++ b/docs/problem/binary-trees-with-factors.html
@@ -0,0 +1,58 @@
+Binary Trees With Factors - LeetCode javascript solutions
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 modulo109 + 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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/binary-watch.html b/docs/problem/binary-watch.html
new file mode 100644
index 0000000..86b706f
--- /dev/null
+++ b/docs/problem/binary-watch.html
@@ -0,0 +1,84 @@
+Binary Watch - LeetCode javascript solutions
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.
/**
+ * @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 :
+
\ No newline at end of file
diff --git a/docs/problem/bitwise-and-of-numbers-range.html b/docs/problem/bitwise-and-of-numbers-range.html
new file mode 100644
index 0000000..906adec
--- /dev/null
+++ b/docs/problem/bitwise-and-of-numbers-range.html
@@ -0,0 +1,43 @@
+Bitwise AND of Numbers Range - LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/problem/build-an-array-with-stack-operations.html b/docs/problem/build-an-array-with-stack-operations.html
new file mode 100644
index 0000000..f60541b
--- /dev/null
+++ b/docs/problem/build-an-array-with-stack-operations.html
@@ -0,0 +1,78 @@
+Build an Array With Stack Operations - LeetCode javascript solutions
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 lastelement is the top ofthe stack.
+Read 1fromthe stream and push ittothe stack. s = [1].
+Read 2fromthe stream and push ittothe stack. s = [1,2].
+Pop theintegeronthetopofthestack. s = [1].
+Read 3fromthe stream and push ittothe 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 lastelement is the top ofthe stack.
+Read 1fromthe stream and push ittothe stack. s = [1].
+Read 2fromthe stream and push ittothe stack. s = [1,2].
+Read 3fromthe stream and push ittothe stack. s = [1,2,3].
+
+
Example 3:
+
Input: target = [1,2], n = 4
+Output: ["Push","Push"]
+Explanation: Initially the stack s is empty. The lastelement is the top ofthe stack.
+Read 1fromthe stream and push ittothe stack. s = [1].
+Read 2fromthe stream and push ittothe stack. s = [1,2].
+Since the stack (fromthe bottom tothe top) is equal to target, we stopthe stack operations.
+The answers that readinteger3fromthe stream are not accepted.
+
+
+Constraints:
+
+
1 <= target.length <= 100
+
1 <= n <= 100
+
1 <= target[i] <= n
+
target is strictly increasing.
+
+
Solution
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/build-array-where-you-can-find-the-maximum-exactly-k-comparisons.html b/docs/problem/build-array-where-you-can-find-the-maximum-exactly-k-comparisons.html
new file mode 100644
index 0000000..c8b6a07
--- /dev/null
+++ b/docs/problem/build-array-where-you-can-find-the-maximum-exactly-k-comparisons.html
@@ -0,0 +1,73 @@
+Build Array Where You Can Find The Maximum Exactly K Comparisons - LeetCode javascript solutions
1420. Build Array Where You Can Find The Maximum Exactly K Comparisons
You are given three integers n, m and k. Consider the following algorithm to find the maximum element of an array of positive integers:
+
+
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]
+
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
+
/**
+ * @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) return1;
+ if (n === 0) return0;
+ if (maxSoFar === m && k > 0) return0;
+ 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).
+
\ No newline at end of file
diff --git a/docs/problem/bulb-switcher.html b/docs/problem/bulb-switcher.html
new file mode 100644
index 0000000..2bece2a
--- /dev/null
+++ b/docs/problem/bulb-switcher.html
@@ -0,0 +1,46 @@
+Bulb Switcher - LeetCode javascript solutions
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:
+
+
Input: n = 3
+Output: 1
+Explanation: At first, thethree bulbs are [off, off, off].
+After thefirstround, thethree bulbs are [on, on, on].
+After thesecondround, thethree bulbs are [on, off, on].
+After thethirdround, thethree bulbs are [on, off, off].
+So you should return1 because there is only one bulb is on.
+
For the kth 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 kth light bulb is dark; if k has an odd number of divisors, then the final state of the kth 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).
+
\ No newline at end of file
diff --git a/docs/problem/bus-routes.html b/docs/problem/bus-routes.html
new file mode 100644
index 0000000..36b49fc
--- /dev/null
+++ b/docs/problem/bus-routes.html
@@ -0,0 +1,92 @@
+Bus Routes - LeetCode javascript solutions
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 thefirst bus tothe bus stop7, then take thesecond bus tothe bus stop6.
+
/**
+ * @param {number[][]} routes
+ * @param {number} source
+ * @param {number} target
+ * @return {number}
+ */
+var numBusesToDestination = function(routes, source, target) {
+ if (source === target) return0;
+ 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).
+
\ No newline at end of file
diff --git a/docs/problem/buy-two-chocolates.html b/docs/problem/buy-two-chocolates.html
new file mode 100644
index 0000000..9842184
--- /dev/null
+++ b/docs/problem/buy-two-chocolates.html
@@ -0,0 +1,51 @@
+Buy Two Chocolates - LeetCode javascript solutions
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 at1and2 units respectively. You will have 3 - 3 = 0 units of money afterwards. Thus, we return0.
+
+
Example 2:
+
Input: prices = [3,2,3], money = 3
+Output:3
+Explanation: You cannot buy 2 chocolates without going in debt, so we return3.
+
\ No newline at end of file
diff --git a/docs/problem/calculate-money-in-leetcode-bank.html b/docs/problem/calculate-money-in-leetcode-bank.html
new file mode 100644
index 0000000..523a48e
--- /dev/null
+++ b/docs/problem/calculate-money-in-leetcode-bank.html
@@ -0,0 +1,47 @@
+Calculate Money in Leetcode Bank - LeetCode javascript solutions
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 the10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice thatonthe2nd Monday, Hercy only puts in $2.
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/can-make-arithmetic-progression-from-sequence.html b/docs/problem/can-make-arithmetic-progression-from-sequence.html
new file mode 100644
index 0000000..e97625b
--- /dev/null
+++ b/docs/problem/can-make-arithmetic-progression-from-sequence.html
@@ -0,0 +1,39 @@
+Can Make Arithmetic Progression From Sequence - LeetCode javascript solutions
1502. Can Make Arithmetic Progression From Sequence
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, returnfalse.
+
+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 2and-2 respectively, between each consecutive elements.
+
\ No newline at end of file
diff --git a/docs/problem/candy.html b/docs/problem/candy.html
new file mode 100644
index 0000000..8c6e820
--- /dev/null
+++ b/docs/problem/candy.html
@@ -0,0 +1,47 @@
+Candy - LeetCode javascript solutions
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 tothefirst, secondandthird child with2, 1, 2 candies respectively.
+
+
Example 2:
+
Input: [1,2,2]
+Output: 4
+Explanation: You can allocate tothefirst, secondandthird child with1, 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;
+};
+
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.
+
+
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 beno excess liquid soall 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 tothe top glass ofthe tower (which is indexed as (0, 0)). There is one cup of excess liquid. The glass indexed as (1, 0) andthe glass indexed as (1, 1) will share the excess liquid equally, andeach will get half cup of champange.
+
\ No newline at end of file
diff --git a/docs/problem/cheapest-flights-within-k-stops.html b/docs/problem/cheapest-flights-within-k-stops.html
new file mode 100644
index 0000000..f8fba06
--- /dev/null
+++ b/docs/problem/cheapest-flights-within-k-stops.html
@@ -0,0 +1,84 @@
+Cheapest Flights Within K Stops - LeetCode javascript solutions
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:
+
+
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:
+
+
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 1stop from city 0to2is marked in redandhas cost 100 + 100 = 200.
+
+
Example 3:
+
+
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 0to2is marked in redandhas 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
+
/**
+ * @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) return0;
+ 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).
+
\ No newline at end of file
diff --git a/docs/problem/check-if-all-as-appears-before-all-bs.html b/docs/problem/check-if-all-as-appears-before-all-bs.html
new file mode 100644
index 0000000..9f8b06c
--- /dev/null
+++ b/docs/problem/check-if-all-as-appears-before-all-bs.html
@@ -0,0 +1,50 @@
+Check if All A's Appears Before All B's - LeetCode javascript solutions
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, and2, whilethe'b's are at indices 3, 4, and5.
+Hence, every 'a' appears before every 'b'and we returntrue.
+
+
Example 2:
+
Input: s = "abab"
+Output: false
+Explanation:
+There is an'a'at index 2anda'b'at index 1.
+Hence, not every 'a' appears before every 'b'and we returnfalse.
+
+
Example 3:
+
Input: s = "bbb"
+Output:true
+Explanation:
+There are no 'a's, hence, every 'a' appears before every 'b' and we returntrue.
+
+
+Constraints:
+
+
1 <= s.length <= 100
+
s[i] is either 'a' or 'b'.
+
+
Solution
+
/**
+ * @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) returnfalse;
+ hasB = s[i] === 'b';
+ }
+ returntrue;
+};
+
+
Explain:
+
nope.
+
Complexity:
+
+
Time complexity : O(n).
+
Space complexity : O(1).
+
\ No newline at end of file
diff --git a/docs/problem/check-if-array-is-sorted-and-rotated.html b/docs/problem/check-if-array-is-sorted-and-rotated.html
new file mode 100644
index 0000000..708a09f
--- /dev/null
+++ b/docs/problem/check-if-array-is-sorted-and-rotated.html
@@ -0,0 +1,55 @@
+Check if Array Is Sorted and Rotated - LeetCode javascript solutions
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.
+
\ No newline at end of file
diff --git a/docs/problem/check-if-there-is-a-valid-partition-for-the-array.html b/docs/problem/check-if-there-is-a-valid-partition-for-the-array.html
new file mode 100644
index 0000000..529a64d
--- /dev/null
+++ b/docs/problem/check-if-there-is-a-valid-partition-for-the-array.html
@@ -0,0 +1,50 @@
+Check if There is a Valid Partition For The Array - LeetCode javascript solutions
2369. Check if There is a Valid Partition For The Array
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 exactly2 equal elements. For example, the subarray [2,2] is good.
+
The subarray consists of exactly3 equal elements. For example, the subarray [4,4,4] is good.
+
The subarray consists of exactly3 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.
+
\ No newline at end of file
diff --git a/docs/problem/check-if-two-string-arrays-are-equivalent.html b/docs/problem/check-if-two-string-arrays-are-equivalent.html
new file mode 100644
index 0000000..812c7a3
--- /dev/null
+++ b/docs/problem/check-if-two-string-arrays-are-equivalent.html
@@ -0,0 +1,64 @@
+Check If Two String Arrays are Equivalent - LeetCode javascript solutions
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 8and10.Return8as 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
+
/**
+ * @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) return0;
+ if (target <= 0) return0;
+ 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) returnMath.min(num1, num2);
+ return diff1 < diff2 ? num1 : num2;
+};
+
+
Explain:
+
nope.
+
Complexity:
+
+
Time complexity : O(n * m ^ 3).
+
Space complexity : O(m).
+
\ No newline at end of file
diff --git a/docs/problem/coin-change-ii.html b/docs/problem/coin-change-ii.html
new file mode 100644
index 0000000..2dbacb6
--- /dev/null
+++ b/docs/problem/coin-change-ii.html
@@ -0,0 +1,68 @@
+Coin Change II - LeetCode javascript solutions
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.
\ No newline at end of file
diff --git a/docs/problem/combination-sum-ii.html b/docs/problem/combination-sum-ii.html
new file mode 100644
index 0000000..a8fd29a
--- /dev/null
+++ b/docs/problem/combination-sum-ii.html
@@ -0,0 +1,64 @@
+Combination Sum II - LeetCode javascript solutions
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.
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:
+
与之前一题不同的地方是:
+
+
候选数字可能有重复的
+
单个候选数字不能重复使用
+
+
Complexity:
+
+
Time complexity : O(n^2).
+
Space complexity : O(n^2).
+
\ No newline at end of file
diff --git a/docs/problem/combination-sum-iv.html b/docs/problem/combination-sum-iv.html
new file mode 100644
index 0000000..1be2bdb
--- /dev/null
+++ b/docs/problem/combination-sum-iv.html
@@ -0,0 +1,57 @@
+Combination Sum IV - LeetCode javascript solutions
Given an array of distinct integers nums and a target integer target, return the number of possible combinations that add up totarget.
+
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
+
/**
+ * @param {number[]} nums
+ * @param {number} target
+ * @return {number}
+ */
+var combinationSum4 = function(nums, target, map = {}) {
+ if (target === 0) return1;
+ 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).
+
\ No newline at end of file
diff --git a/docs/problem/combination-sum.html b/docs/problem/combination-sum.html
new file mode 100644
index 0000000..02b3bc1
--- /dev/null
+++ b/docs/problem/combination-sum.html
@@ -0,0 +1,58 @@
+Combination Sum - LeetCode javascript solutions
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).
+
\ No newline at end of file
diff --git a/docs/problem/combinations.html b/docs/problem/combinations.html
new file mode 100644
index 0000000..39c91f5
--- /dev/null
+++ b/docs/problem/combinations.html
@@ -0,0 +1,50 @@
+Combinations - LeetCode javascript solutions
/**
+ * @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 :
+
\ No newline at end of file
diff --git a/docs/problem/combine-two-tables.html b/docs/problem/combine-two-tables.html
new file mode 100644
index 0000000..f77bdfa
--- /dev/null
+++ b/docs/problem/combine-two-tables.html
@@ -0,0 +1,36 @@
+Combine Two Tables - LeetCode javascript solutions
+-------------+---------+
+| 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 :
+
\ No newline at end of file
diff --git a/docs/problem/compare-version-numbers.html b/docs/problem/compare-version-numbers.html
new file mode 100644
index 0000000..7347970
--- /dev/null
+++ b/docs/problem/compare-version-numbers.html
@@ -0,0 +1,46 @@
+Compare Version Numbers - LeetCode javascript solutions
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.
/**
+ * @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) return1;
+ if (t1 < t2) return-1;
+ }
+ return0;
+};
+
+
Explain:
+
nope.
+
Complexity:
+
+
Time complexity : O(n).
+
Space complexity : O(1).
+
\ No newline at end of file
diff --git a/docs/problem/complex-number-multiplication.html b/docs/problem/complex-number-multiplication.html
new file mode 100644
index 0000000..13314e7
--- /dev/null
+++ b/docs/problem/complex-number-multiplication.html
@@ -0,0 +1,80 @@
+Complex Number Multiplication - LeetCode javascript solutions
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 convertittothe form of0+2i.
+
+
Example 2:
+
Input: "1+-1i", "1+-1i"
+Output: "0+-2i"
+Explanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convertittothe form of0+-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 :
+
\ No newline at end of file
diff --git a/docs/problem/consecutive-numbers.html b/docs/problem/consecutive-numbers.html
new file mode 100644
index 0000000..71b9d23
--- /dev/null
+++ b/docs/problem/consecutive-numbers.html
@@ -0,0 +1,55 @@
+Consecutive Numbers - LeetCode javascript solutions
# 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 :
+
\ No newline at end of file
diff --git a/docs/problem/constrained-subsequence-sum.html b/docs/problem/constrained-subsequence-sum.html
new file mode 100644
index 0000000..b0a5901
--- /dev/null
+++ b/docs/problem/constrained-subsequence-sum.html
@@ -0,0 +1,78 @@
+Constrained Subsequence Sum - LeetCode javascript solutions
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
+
/**
+ * @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
+
/**
+ * @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);
+ }
+ returnMath.max(...nums);
+};
+
+
Explain:
+
Monotonic Deque.
+
Complexity:
+
+
Time complexity : O(n).
+
Space complexity : O(n).
+
\ 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
new file mode 100644
index 0000000..308f465
--- /dev/null
+++ b/docs/problem/construct-binary-tree-from-inorder-and-postorder-traversal.html
@@ -0,0 +1,58 @@
+Construct Binary Tree from Inorder and Postorder Traversal - LeetCode javascript solutions
106. Construct Binary Tree from Inorder and Postorder Traversal
\ 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
new file mode 100644
index 0000000..15a1514
--- /dev/null
+++ b/docs/problem/construct-binary-tree-from-preorder-and-inorder-traversal.html
@@ -0,0 +1,62 @@
+Construct Binary Tree from Preorder and Inorder Traversal - LeetCode javascript solutions
105. Construct Binary Tree from Preorder and Inorder Traversal
/**
+ * 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) returnnull;
+
+ 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:
+
+
preorder[0] 是 root
+
在 inorder 里找到 root,左边是 root.left,右边是 root.right。
+
递归
+
+
Complexity:
+
+
Time complexity :
+
Space complexity :
+
\ No newline at end of file
diff --git a/docs/problem/construct-string-from-binary-tree.html b/docs/problem/construct-string-from-binary-tree.html
new file mode 100644
index 0000000..46b8508
--- /dev/null
+++ b/docs/problem/construct-string-from-binary-tree.html
@@ -0,0 +1,50 @@
+Construct String from Binary Tree - LeetCode javascript solutions
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:
+
+
Input: root = [1,2,3,4]
+Output:"1(2(4))(3)"
+Explanation: Originally, it needs tobe"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:
+
+
Input: root = [1,2,3,null,4]
+Output: "1(2()(4))(3)"
+Explanation: Almost the same asthefirst example, except we cannot omit thefirst parenthesis pair to break theone-to-one mapping relationship between the input andthe output.
+
+
+Constraints:
+
+
The number of nodes in the tree is in the range [1, 104].
+
-1000 <= Node.val <= 1000
+
+
Solution
+
/**
+ * 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).
+
\ No newline at end of file
diff --git a/docs/problem/construct-the-lexicographically-largest-valid-sequence.html b/docs/problem/construct-the-lexicographically-largest-valid-sequence.html
new file mode 100644
index 0000000..e7259e9
--- /dev/null
+++ b/docs/problem/construct-the-lexicographically-largest-valid-sequence.html
@@ -0,0 +1,60 @@
+Construct the Lexicographically Largest Valid Sequence - LeetCode javascript solutions
1718. Construct the Lexicographically Largest Valid Sequence
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
+
/**
+ * @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;
+ }
+ returnnull;
+};
+
+
Explain:
+
Backtrack and DFS.
+
Complexity:
+
+
Time complexity : O(n * n).
+
Space complexity : O(n).
+
\ No newline at end of file
diff --git a/docs/problem/container-with-most-water.html b/docs/problem/container-with-most-water.html
new file mode 100644
index 0000000..c070f31
--- /dev/null
+++ b/docs/problem/container-with-most-water.html
@@ -0,0 +1,30 @@
+Container With Most Water - LeetCode javascript solutions
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;
+};
+
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] isthe longest contiguous subarray with an equalnumberof0and1.
+
+
Example 2:
+
Input: nums = [0,1,0]
+Output: 2
+Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray withequalnumberof0and1.
+
+
+Constraints:
+
+
1 <= nums.length <= 105
+
nums[i] is either 0 or 1.
+
+
Solution
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/convert-an-array-into-a-2d-array-with-conditions.html b/docs/problem/convert-an-array-into-a-2d-array-with-conditions.html
new file mode 100644
index 0000000..ae8b783
--- /dev/null
+++ b/docs/problem/convert-an-array-into-a-2d-array-with-conditions.html
@@ -0,0 +1,58 @@
+Convert an Array Into a 2D Array With Conditions - LeetCode javascript solutions
2610. Convert an Array Into a 2D Array With Conditions
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
+
/**
+ * @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).
+
\ 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
new file mode 100644
index 0000000..6714d88
--- /dev/null
+++ b/docs/problem/convert-sorted-array-to-binary-search-tree.html
@@ -0,0 +1,46 @@
+Convert Sorted Array to Binary Search Tree - LeetCode javascript solutions
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
+
\ 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
new file mode 100644
index 0000000..684d069
--- /dev/null
+++ b/docs/problem/convert-sorted-list-to-binary-search-tree.html
@@ -0,0 +1,63 @@
+Convert Sorted List to Binary Search Tree - LeetCode javascript solutions
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) returnnull;
+
+ 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).
+
\ 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
new file mode 100644
index 0000000..5681b57
--- /dev/null
+++ b/docs/problem/copy-list-with-random-pointer.html
@@ -0,0 +1,45 @@
+Copy List with Random Pointer - LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/problem/count-all-valid-pickup-and-delivery-options.html b/docs/problem/count-all-valid-pickup-and-delivery-options.html
new file mode 100644
index 0000000..85d3549
--- /dev/null
+++ b/docs/problem/count-all-valid-pickup-and-delivery-options.html
@@ -0,0 +1,54 @@
+Count All Valid Pickup and Delivery Options - LeetCode javascript solutions
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 isafterof 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
+
/**
+ * @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) return1;
+ 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).
+
\ No newline at end of file
diff --git a/docs/problem/count-and-say.html b/docs/problem/count-and-say.html
new file mode 100644
index 0000000..070b0f7
--- /dev/null
+++ b/docs/problem/count-and-say.html
@@ -0,0 +1,71 @@
+Count and Say - LeetCode javascript solutions
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 :
+
\ No newline at end of file
diff --git a/docs/problem/count-days-spent-together.html b/docs/problem/count-days-spent-together.html
new file mode 100644
index 0000000..e8ca520
--- /dev/null
+++ b/docs/problem/count-days-spent-together.html
@@ -0,0 +1,69 @@
+Count Days Spent Together - LeetCode javascript solutions
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 15to August 18. Bob will be in Rome from August 16to August 19. They are both in Rome together on August 16th, 17th, and18th, so the answer is3.
+
+
Example 2:
+
Input: arriveAlice = "10-01", leaveAlice = "10-31", arriveBob = "11-01", leaveBob = "12-31"
+Output:0
+Explanation: There isno day when Alice and Bob are in Rome together, so we return0.
+
+
+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.
\ No newline at end of file
diff --git a/docs/problem/count-nice-pairs-in-an-array.html b/docs/problem/count-nice-pairs-in-an-array.html
new file mode 100644
index 0000000..8cf60c7
--- /dev/null
+++ b/docs/problem/count-nice-pairs-in-an-array.html
@@ -0,0 +1,56 @@
+Count Nice Pairs in an Array - LeetCode javascript solutions
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 modulo109 + 7.
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/count-nodes-equal-to-average-of-subtree.html b/docs/problem/count-nodes-equal-to-average-of-subtree.html
new file mode 100644
index 0000000..b52e5b5
--- /dev/null
+++ b/docs/problem/count-nodes-equal-to-average-of-subtree.html
@@ -0,0 +1,65 @@
+Count Nodes Equal to Average of Subtree - LeetCode javascript solutions
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:
+
+
Input: root = [4,8,5,0,1,null,6]
+Output: 5
+Explanation:
+For the node withvalue4: The averageof its subtree is (4 + 8 + 5 + 0 + 1 + 6) / 6 = 24 / 6 = 4.
+For the node withvalue5: The averageof its subtree is (5 + 6) / 2 = 11 / 2 = 5.
+For the node withvalue0: The averageof its subtree is 0 / 1 = 0.
+For the node withvalue1: The averageof its subtree is 1 / 1 = 1.
+For the node withvalue6: The averageof its subtree is 6 / 1 = 6.
+
+
Example 2:
+
+
Input: root = [1]
+Output: 1
+Explanation: For the node withvalue1: The averageof 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
+
/**
+ * 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).
+
\ No newline at end of file
diff --git a/docs/problem/count-number-of-homogenous-substrings.html b/docs/problem/count-number-of-homogenous-substrings.html
new file mode 100644
index 0000000..9336fc1
--- /dev/null
+++ b/docs/problem/count-number-of-homogenous-substrings.html
@@ -0,0 +1,59 @@
+Count Number of Homogenous Substrings - LeetCode javascript solutions
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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/count-number-of-ways-to-place-houses.html b/docs/problem/count-number-of-ways-to-place-houses.html
new file mode 100644
index 0000000..2262907
--- /dev/null
+++ b/docs/problem/count-number-of-ways-to-place-houses.html
@@ -0,0 +1,52 @@
+Count Number of Ways to Place Houses - LeetCode javascript solutions
There is a street with n * 2plots, 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 modulo109 + 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 sideof the street.
+3. A house is placed on the other sideof the street.
+4. Two houses are placed, one on each sideof the street.
+
+
Example 2:
+
+
Input: n = 2
+Output:9
+Explanation: The 9 possible arrangements are shown in the diagram above.
+
+
+Constraints:
+
+
1 <= n <= 104
+
+
Solution
+
/**
+ * @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;
+ returnNumber((BigInt(tmp) * BigInt(tmp)) % BigInt(mod));
+};
+
+
Explain:
+
nope.
+
Complexity:
+
+
Time complexity : O(n).
+
Space complexity : O(1).
+
\ No newline at end of file
diff --git a/docs/problem/count-of-matches-in-tournament.html b/docs/problem/count-of-matches-in-tournament.html
new file mode 100644
index 0000000..a7731c2
--- /dev/null
+++ b/docs/problem/count-of-matches-in-tournament.html
@@ -0,0 +1,53 @@
+Count of Matches in Tournament - LeetCode javascript solutions
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, and4 teams advance.
+- 2nd Round: Teams = 4, Matches = 2, and2 teams advance.
+- 3rd Round: Teams = 2, Matches = 1, and1 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, and7teams advance.
+- 2nd Round: Teams = 7, Matches = 3, and4teams advance.
+- 3rd Round: Teams = 4, Matches = 2, and2teams advance.
+- 4th Round: Teams = 2, Matches = 1, and1 team is declared the winner.
+Total number of matches = 7 + 3 + 2 + 1 = 13.
+
\ No newline at end of file
diff --git a/docs/problem/count-of-smaller-numbers-after-self.html b/docs/problem/count-of-smaller-numbers-after-self.html
new file mode 100644
index 0000000..2039431
--- /dev/null
+++ b/docs/problem/count-of-smaller-numbers-after-self.html
@@ -0,0 +1,70 @@
+Count of Smaller Numbers After Self - LeetCode javascript solutions
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 therightof5 there are 2 smaller elements (2and1).
+To therightof2 there is only 1 smaller element (1).
+To therightof6 there is 1 smaller element (1).
+To therightof1 there is 0 smaller element.
+
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 0and2 are happy.
+
+
Example 2:
+
Input: n = 2, preferences = [[1], [0]], pairs = [[1, 0]]
+Output: 0
+Explanation: Both friends 0and1 are happy.
+
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
+
/**
+ * @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) return1;
+ 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).
+
\ No newline at end of file
diff --git a/docs/problem/count-ways-to-build-good-strings.html b/docs/problem/count-ways-to-build-good-strings.html
new file mode 100644
index 0000000..4eb9ed8
--- /dev/null
+++ b/docs/problem/count-ways-to-build-good-strings.html
@@ -0,0 +1,64 @@
+Count Ways To Build Good Strings - LeetCode javascript solutions
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 modulo109 + 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 inthis 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
+
/**
+ * @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 = newArray(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).
+
\ No newline at end of file
diff --git a/docs/problem/counting-bits.html b/docs/problem/counting-bits.html
new file mode 100644
index 0000000..9f3e23d
--- /dev/null
+++ b/docs/problem/counting-bits.html
@@ -0,0 +1,65 @@
+Counting Bits - LeetCode javascript solutions
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.
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).
+
\ No newline at end of file
diff --git a/docs/problem/create-binary-tree-from-descriptions.html b/docs/problem/create-binary-tree-from-descriptions.html
new file mode 100644
index 0000000..c8c4cf7
--- /dev/null
+++ b/docs/problem/create-binary-tree-from-descriptions.html
@@ -0,0 +1,70 @@
+Create Binary Tree From Descriptions - LeetCode javascript solutions
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:
+
+
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 nodeis the nodewith value 50 since it has no parent.
+The resulting binary tree is shown in the diagram.
+
+
Example 2:
+
+
Input: descriptions = [[1,2,1],[2,3,0],[3,4,1]]
+Output: [1,2,null,null,3,4]
+Explanation: The root nodeis the nodewith 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
+
/**
+ * 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).
+
\ No newline at end of file
diff --git a/docs/problem/customers-who-never-order.html b/docs/problem/customers-who-never-order.html
new file mode 100644
index 0000000..c64bfa1
--- /dev/null
+++ b/docs/problem/customers-who-never-order.html
@@ -0,0 +1,73 @@
+Customers Who Never Order - LeetCode javascript solutions
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 |
++----+-------+
+
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 :
+
\ No newline at end of file
diff --git a/docs/problem/daily-temperatures.html b/docs/problem/daily-temperatures.html
new file mode 100644
index 0000000..a2c5631
--- /dev/null
+++ b/docs/problem/daily-temperatures.html
@@ -0,0 +1,46 @@
+Daily Temperatures - LeetCode javascript solutions
Given an array of integers temperatures represents the daily temperatures, return an arrayanswersuch thatanswer[i]is the number of days you have to wait after theithday to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead.
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" (12) or "L" (12).
+
+
Example 2:
+
Input:"226"
+Output:3
+Explanation: It could be decoded as "BZ" (226), "VF" (226), or "BBF" (226).
+
+
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') return0;
+
+ 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).
+
\ No newline at end of file
diff --git a/docs/problem/decoded-string-at-index.html b/docs/problem/decoded-string-at-index.html
new file mode 100644
index 0000000..64d041b
--- /dev/null
+++ b/docs/problem/decoded-string-at-index.html
@@ -0,0 +1,86 @@
+Decoded String at Index - LeetCode javascript solutions
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 stringis"leetleetcodeleetleetcodeleetleetcode".
+The 10th letter in the stringis"o".
+
+
Example 2:
+
Input: s = "ha22", k = 5
+Output:"h"
+Explanation: The decoded stringis"hahahaha".
+The 5th letter is"h".
+
+
Example 3:
+
Input: s = "a2345678999999999999999", k = 1
+Output:"a"
+Explanation: The decoded stringis"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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/degree-of-an-array.html b/docs/problem/degree-of-an-array.html
new file mode 100644
index 0000000..8dab7fa
--- /dev/null
+++ b/docs/problem/degree-of-an-array.html
@@ -0,0 +1,63 @@
+Degree of an Array - LeetCode javascript solutions
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 is3 because the element 2is repeated 3times.
+So [2,2,3,1,4,2] isthe shortest subarray, therefore returning6.
+
+
+Constraints:
+
+
nums.length will be between 1 and 50,000.
+
nums[i] will be an integer between 0 and 49,999.
+
+
Solution
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/delete-duplicate-emails.html b/docs/problem/delete-duplicate-emails.html
new file mode 100644
index 0000000..2510a2c
--- /dev/null
+++ b/docs/problem/delete-duplicate-emails.html
@@ -0,0 +1,48 @@
+Delete Duplicate Emails - LeetCode javascript solutions
+-------------+---------+
+| 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
+
# 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).
+
\ No newline at end of file
diff --git a/docs/problem/design-a-food-rating-system.html b/docs/problem/design-a-food-rating-system.html
new file mode 100644
index 0000000..8ede4bc
--- /dev/null
+++ b/docs/problem/design-a-food-rating-system.html
@@ -0,0 +1,119 @@
+Design a Food Rating System - LeetCode javascript solutions
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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/design-graph-with-shortest-path-calculator.html b/docs/problem/design-graph-with-shortest-path-calculator.html
new file mode 100644
index 0000000..0be637c
--- /dev/null
+++ b/docs/problem/design-graph-with-shortest-path-calculator.html
@@ -0,0 +1,92 @@
+Design Graph With Shortest Path Calculator - LeetCode javascript solutions
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:
+
+
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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/design-hashmap.html b/docs/problem/design-hashmap.html
new file mode 100644
index 0000000..84d9db3
--- /dev/null
+++ b/docs/problem/design-hashmap.html
@@ -0,0 +1,80 @@
+Design HashMap - LeetCode javascript solutions
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); // return1, 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); // return1, The map is now [[1,1], [2,1]]
+myHashMap.remove(2); // remove the mapping for2, 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.
\ No newline at end of file
diff --git a/docs/problem/destination-city.html b/docs/problem/destination-city.html
new file mode 100644
index 0000000..c7234e6
--- /dev/null
+++ b/docs/problem/destination-city.html
@@ -0,0 +1,57 @@
+Destination City - LeetCode javascript solutions
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.
\ No newline at end of file
diff --git a/docs/problem/determine-if-a-cell-is-reachable-at-a-given-time.html b/docs/problem/determine-if-a-cell-is-reachable-at-a-given-time.html
new file mode 100644
index 0000000..a949d11
--- /dev/null
+++ b/docs/problem/determine-if-a-cell-is-reachable-at-a-given-time.html
@@ -0,0 +1,49 @@
+Determine if a Cell Is Reachable at a Given Time - LeetCode javascript solutions
2849. Determine if a Cell Is Reachable at a Given Time
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* falseotherwise.
+
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:
+
+
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 6secondsby going through the cells depicted inthe picture above.
+
+
Example 2:
+
+
Input: sx = 3, sy = 1, fx = 7, fy = 3, t = 3
+Output: false
+Explanation: Starting at cell (3, 1), it takes at least 4secondsto reach cell (7, 3) by going through the cells depicted inthe picture above. Hence, we cannot reach cell (7, 3) atthethirdsecond.
+
+
+Constraints:
+
+
1 <= sx, sy, fx, fy <= 109
+
0 <= t <= 109
+
+
Solution
+
/**
+ * @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) {
+ returnfalse;
+ }
+ returnMath.max(x, y) <= t;
+};
+
+
Explain:
+
nope.
+
Complexity:
+
+
Time complexity : O(1).
+
Space complexity : O(1).
+
\ No newline at end of file
diff --git a/docs/problem/determine-if-string-halves-are-alike.html b/docs/problem/determine-if-string-halves-are-alike.html
new file mode 100644
index 0000000..004ff1b
--- /dev/null
+++ b/docs/problem/determine-if-string-halves-are-alike.html
@@ -0,0 +1,57 @@
+Determine if String Halves Are Alike - LeetCode javascript solutions
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.
+
\ No newline at end of file
diff --git a/docs/problem/diagonal-traverse-ii.html b/docs/problem/diagonal-traverse-ii.html
new file mode 100644
index 0000000..90968a3
--- /dev/null
+++ b/docs/problem/diagonal-traverse-ii.html
@@ -0,0 +1,44 @@
+Diagonal Traverse II - LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/problem/diameter-of-binary-tree.html b/docs/problem/diameter-of-binary-tree.html
new file mode 100644
index 0000000..b3b5936
--- /dev/null
+++ b/docs/problem/diameter-of-binary-tree.html
@@ -0,0 +1,65 @@
+Diameter of Binary Tree - LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/problem/difference-between-ones-and-zeros-in-row-and-column.html b/docs/problem/difference-between-ones-and-zeros-in-row-and-column.html
new file mode 100644
index 0000000..d13981c
--- /dev/null
+++ b/docs/problem/difference-between-ones-and-zeros-in-row-and-column.html
@@ -0,0 +1,88 @@
+Difference Between Ones and Zeros in Row and Column - LeetCode javascript solutions
2482. Difference Between Ones and Zeros in Row and Column
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
+ ^^^
+
\ No newline at end of file
diff --git a/docs/problem/divide-array-into-arrays-with-max-difference.html b/docs/problem/divide-array-into-arrays-with-max-difference.html
new file mode 100644
index 0000000..987c59e
--- /dev/null
+++ b/docs/problem/divide-array-into-arrays-with-max-difference.html
@@ -0,0 +1,56 @@
+Divide Array Into Arrays With Max Difference - LeetCode javascript solutions
2966. Divide Array Into Arrays With Max Difference
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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/divide-two-integers.html b/docs/problem/divide-two-integers.html
new file mode 100644
index 0000000..0c26a90
--- /dev/null
+++ b/docs/problem/divide-two-integers.html
@@ -0,0 +1,58 @@
+Divide Two Integers - LeetCode javascript solutions
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) return0;
+ if (divisor === -1 && dividend === -2147483648) return2147483647;
+ 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:
+
+
要注意 -2147483648 / -1 越界的情况
+
核心就是 dividend -= divisor << i; result += 2 << (i - 1);
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 inround1.
+And thesecond senator can't exercise any rights anymore since his right has been banned.
+And thethird senator comes from Dire and he can ban thefirst senator's right inround1.
+And inround2, thethird senator can just announce the victory since he isthe only guy inthe senate who can vote.
+
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).
+
\ No newline at end of file
diff --git a/docs/problem/dungeon-game.html b/docs/problem/dungeon-game.html
new file mode 100644
index 0000000..2784581
--- /dev/null
+++ b/docs/problem/dungeon-game.html
@@ -0,0 +1,69 @@
+Dungeon Game - LeetCode javascript solutions
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)
+
-3
+
3
+
+
+
-5
+
-10
+
1
+
+
+
10
+
30
+
-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).
+
\ No newline at end of file
diff --git a/docs/problem/duplicate-emails.html b/docs/problem/duplicate-emails.html
new file mode 100644
index 0000000..d06d5bf
--- /dev/null
+++ b/docs/problem/duplicate-emails.html
@@ -0,0 +1,47 @@
+Duplicate Emails - LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/problem/egg-drop-with-2-eggs-and-n-floors.html b/docs/problem/egg-drop-with-2-eggs-and-n-floors.html
new file mode 100644
index 0000000..482a92f
--- /dev/null
+++ b/docs/problem/egg-drop-with-2-eggs-and-n-floors.html
@@ -0,0 +1,47 @@
+Egg Drop With 2 Eggs and N Floors - LeetCode javascript solutions
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 thefirst egg from floor 1andthesecond egg from floor 2.
+If thefirst egg breaks, we know that f = 0.
+If thesecond egg breaks butthefirst 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 atfloor9.If it breaks, we know f isbetween0and8.Drop the 2nd egg startingfromfloor1and going up one at a timeto find f within8 more drops. Total drops is1 + 8 = 9.
+- If the 1st egg does not break, drop the 1st egg again atfloor22.If it breaks, we know f isbetween9and21.Drop the 2nd egg startingfromfloor10and going up one at a timeto find f within12 more drops. Total drops is2 + 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, and100.
+Regardless of the outcome, it takes at most 14 drops to determine f.
+
+
+Constraints:
+
+
1 <= n <= 1000
+
+
Solution
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/element-appearing-more-than-25-in-sorted-array.html b/docs/problem/element-appearing-more-than-25-in-sorted-array.html
new file mode 100644
index 0000000..6f70abf
--- /dev/null
+++ b/docs/problem/element-appearing-more-than-25-in-sorted-array.html
@@ -0,0 +1,43 @@
+Element Appearing More Than 25% In Sorted Array - LeetCode javascript solutions
1287. Element Appearing More Than 25% In Sorted Array
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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/eliminate-maximum-number-of-monsters.html b/docs/problem/eliminate-maximum-number-of-monsters.html
new file mode 100644
index 0000000..bf33164
--- /dev/null
+++ b/docs/problem/eliminate-maximum-number-of-monsters.html
@@ -0,0 +1,60 @@
+Eliminate Maximum Number of Monsters - LeetCode javascript solutions
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 ofthe monsters are [1,3,4]. You eliminate thefirst monster.
+After a minute, the distances ofthe monsters are [X,2,3]. You eliminate thesecond monster.
+After a minute, the distances ofthe 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 ofthe monsters are [1,1,2,3]. You eliminate thefirst monster.
+After a minute, the distances ofthe 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 ofthe monsters are [3,2,4]. You eliminate thefirst monster.
+After a minute, the distances ofthe 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
+
/**
+ * @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).
+
\ 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
new file mode 100644
index 0000000..f7a9e75
--- /dev/null
+++ b/docs/problem/employees-earning-more-than-their-managers.html
@@ -0,0 +1,49 @@
+Employees Earning More Than Their Managers - LeetCode javascript solutions
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 :
+
\ No newline at end of file
diff --git a/docs/problem/evaluate-reverse-polish-notation.html b/docs/problem/evaluate-reverse-polish-notation.html
new file mode 100644
index 0000000..7d85abe
--- /dev/null
+++ b/docs/problem/evaluate-reverse-polish-notation.html
@@ -0,0 +1,76 @@
+Evaluate Reverse Polish Notation - LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/problem/even-odd-tree.html b/docs/problem/even-odd-tree.html
new file mode 100644
index 0000000..1123d78
--- /dev/null
+++ b/docs/problem/even-odd-tree.html
@@ -0,0 +1,84 @@
+Even Odd Tree - LeetCode javascript solutions
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:
+
+
Input: root = [1,10,4,3,null,7,9,12,8,6,null,null,2]
+Output: true
+Explanation: The node valuesoneach level are:
+Level 0: [1]
+Level 1: [10,4]
+Level 2: [3,7,9]
+Level 3: [12,8,6,2]
+Since levels 0and2 are all odd and increasing and levels 1and3 are all even and decreasing, the tree is Even-Odd.
+
+
Example 2:
+
+
Input: root = [5,4,2,3,3,7]
+Output: false
+Explanation: The nodevalues on each level are:
+Level 0: [5]
+Level 1: [4,2]
+Level 2: [3,3,7]
+Nodevaluesin level 2 must be in strictly increasing order, so the tree is not Even-Odd.
+
+
Example 3:
+
+
Input: root = [5,9,1,3,5,7]
+Output: false
+Explanation: Nodevaluesin 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
+
/**
+ * 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) returnfalse;
+ if (i > 0 && nodesOfLevel[i].val >= nodesOfLevel[i - 1].val) returnfalse;
+ } else {
+ if (nodesOfLevel[i].val % 2 === 0) returnfalse;
+ if (i > 0 && nodesOfLevel[i].val <= nodesOfLevel[i - 1].val) returnfalse;
+ }
+ nodesOfLevel[i].left && newNodesOfLevel.push(nodesOfLevel[i].left);
+ nodesOfLevel[i].right && newNodesOfLevel.push(nodesOfLevel[i].right);
+ }
+ nodesOfLevel = newNodesOfLevel;
+ level += 1;
+ }
+ returntrue;
+};
+
+
Explain:
+
nope.
+
Complexity:
+
+
Time complexity : O(n).
+
Space complexity : O(n).
+
\ No newline at end of file
diff --git a/docs/problem/excel-sheet-column-number.html b/docs/problem/excel-sheet-column-number.html
new file mode 100644
index 0000000..7772f85
--- /dev/null
+++ b/docs/problem/excel-sheet-column-number.html
@@ -0,0 +1,52 @@
+Excel Sheet Column Number - LeetCode javascript solutions
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).
+
\ No newline at end of file
diff --git a/docs/problem/excel-sheet-column-title.html b/docs/problem/excel-sheet-column-title.html
new file mode 100644
index 0000000..b92b548
--- /dev/null
+++ b/docs/problem/excel-sheet-column-title.html
@@ -0,0 +1,54 @@
+Excel Sheet Column Title - LeetCode javascript solutions
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);
+ returnString.fromCharCode(start + num - 1);
+};
+
+
Explain:
+
nope.
+
Complexity:
+
+
Time complexity : O(log(n)).
+
Space complexity : O(1).
+
\ No newline at end of file
diff --git a/docs/problem/extra-characters-in-a-string.html b/docs/problem/extra-characters-in-a-string.html
new file mode 100644
index 0000000..eab3842
--- /dev/null
+++ b/docs/problem/extra-characters-in-a-string.html
@@ -0,0 +1,56 @@
+Extra Characters in a String - LeetCode javascript solutions
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 index0to3and"code" from index5to8. There isonly1 unused character (at index4), so we return1.
+
+
+
Example 2:
+
Input: s = "sayhelloworld", dictionary = ["hello","world"]
+Output: 3
+Explanation: We can break s intwo substrings: "hello"from index 3to7and"world"from index 8to12. The charactersat indices 0, 1, 2 are not used inany substring and thus are considered as extra characters. Hence, we return3.
+
+
+Constraints:
+
+
1 <= s.length <= 50
+
1 <= dictionary.length <= 50
+
1 <= dictionary[i].length <= 50
+
dictionary[i] and s consists of only lowercase English letters
\ No newline at end of file
diff --git a/docs/problem/fair-distribution-of-cookies.html b/docs/problem/fair-distribution-of-cookies.html
new file mode 100644
index 0000000..b6fbb7e
--- /dev/null
+++ b/docs/problem/fair-distribution-of-cookies.html
@@ -0,0 +1,64 @@
+Fair Distribution of Cookies - LeetCode javascript solutions
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 maximumtotal 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 hasa total of 8 + 15 + 8 = 31 cookies.
+- The 2nd child receives [10,20] which hasa total of 10 + 20 = 30 cookies.
+The unfairness of the distribution ismax(31,30) = 31.
+It can be shown that there isno 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
+
/**
+ * @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) returnMath.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).
+
\ No newline at end of file
diff --git a/docs/problem/final-prices-with-a-special-discount-in-a-shop.html b/docs/problem/final-prices-with-a-special-discount-in-a-shop.html
new file mode 100644
index 0000000..2c2ebde
--- /dev/null
+++ b/docs/problem/final-prices-with-a-special-discount-in-a-shop.html
@@ -0,0 +1,54 @@
+Final Prices With a Special Discount in a Shop - LeetCode javascript solutions
1475. Final Prices With a Special Discount in a Shop
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 item0with 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 item1with 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 item2with 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 items3and4 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, forall items, you will not receive any discount atall.
+
+
Example 3:
+
Input: prices = [10,1,1,6]
+Output: [9,0,1,6]
+
+
+Constraints:
+
+
1 <= prices.length <= 500
+
1 <= prices[i] <= 1000
+
+
Solution
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/find-all-people-with-secret.html b/docs/problem/find-all-people-with-secret.html
new file mode 100644
index 0000000..b22f163
--- /dev/null
+++ b/docs/problem/find-all-people-with-secret.html
@@ -0,0 +1,101 @@
+Find All People With Secret - LeetCode javascript solutions
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
+
/**
+ * @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).
+
\ 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
new file mode 100644
index 0000000..3dbc720
--- /dev/null
+++ b/docs/problem/find-and-replace-in-string.html
@@ -0,0 +1,105 @@
+Find And Replace in String - LeetCode javascript solutions
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 originalstringS, 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 0in S, so it's replaced by"eee".
+"cd" starts at index 2in 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 0in S, so it's replaced by "eee".
+"ec" doesn't starts at index 2in the original S, so we do nothing.
+
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). n 为 S.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)). n 为 indexes.length。
+
Space complexity : O(n).
+
\ No newline at end of file
diff --git a/docs/problem/find-bottom-left-tree-value.html b/docs/problem/find-bottom-left-tree-value.html
new file mode 100644
index 0000000..6f1082f
--- /dev/null
+++ b/docs/problem/find-bottom-left-tree-value.html
@@ -0,0 +1,49 @@
+Find Bottom Left Tree Value - LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/problem/find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree.html b/docs/problem/find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree.html
new file mode 100644
index 0000000..a5c1c72
--- /dev/null
+++ b/docs/problem/find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree.html
@@ -0,0 +1,102 @@
+Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree - LeetCode javascript solutions
1489. Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree
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:
+
+
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 thetwo edges 0and1 appear in all MSTs, therefore they are critical edges, so we return them inthefirst list ofthe output.
+The edges 2, 3, 4, and5 are only part of some MSTs, therefore they are considered pseudo-critical edges. We add them tothesecond list ofthe output.
+
+
Example 2:
+
+
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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/find-eventual-safe-states.html b/docs/problem/find-eventual-safe-states.html
new file mode 100644
index 0000000..5f6178a
--- /dev/null
+++ b/docs/problem/find-eventual-safe-states.html
@@ -0,0 +1,72 @@
+Find Eventual Safe States - LeetCode javascript solutions
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:
+
+
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 node4 is a terminal node, and every path starting at node4 leads to node4.
+
+
+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].
\ No newline at end of file
diff --git a/docs/problem/find-first-and-last-position-of-element-in-sorted-array.html b/docs/problem/find-first-and-last-position-of-element-in-sorted-array.html
new file mode 100644
index 0000000..3414fd2
--- /dev/null
+++ b/docs/problem/find-first-and-last-position-of-element-in-sorted-array.html
@@ -0,0 +1,89 @@
+Find First and Last Position of Element in Sorted Array - LeetCode javascript solutions
34. Find First and Last Position of Element in Sorted Array
/**
+ * @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;
+ } elseif (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).
+
\ No newline at end of file
diff --git a/docs/problem/find-in-mountain-array.html b/docs/problem/find-in-mountain-array.html
new file mode 100644
index 0000000..58fae87
--- /dev/null
+++ b/docs/problem/find-in-mountain-array.html
@@ -0,0 +1,119 @@
+Find in Mountain Array - LeetCode javascript solutions
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 minimumindex 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
+
/**
+ * // 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;
+ } elseif (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;
+ } elseif (midVal < target) {
+ right = mid - 1;
+ } else {
+ left = mid + 1;
+ }
+ }
+ return-1;
+};
+
+
Explain:
+
nope.
+
Complexity:
+
+
Time complexity : O(log(n)).
+
Space complexity : O(1).
+
\ No newline at end of file
diff --git a/docs/problem/find-largest-value-in-each-tree-row.html b/docs/problem/find-largest-value-in-each-tree-row.html
new file mode 100644
index 0000000..ab1114b
--- /dev/null
+++ b/docs/problem/find-largest-value-in-each-tree-row.html
@@ -0,0 +1,54 @@
+Find Largest Value in Each Tree Row - LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/problem/find-median-from-data-stream.html b/docs/problem/find-median-from-data-stream.html
new file mode 100644
index 0000000..bdd478b
--- /dev/null
+++ b/docs/problem/find-median-from-data-stream.html
@@ -0,0 +1,98 @@
+Find Median from Data Stream - LeetCode javascript solutions
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.
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
+
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;
+ } elseif (this.arr[mid] > num) {
+ right = mid;
+ } else {
+ left = mid + 1;
+ }
+ }
+};
+
+/**
+ * @return {number}
+ */
+MedianFinder.prototype.findMedian = function() {
+ returnthis.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).
+
\ 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
new file mode 100644
index 0000000..1abb151
--- /dev/null
+++ b/docs/problem/find-minimum-in-rotated-sorted-array-ii.html
@@ -0,0 +1,47 @@
+Find Minimum in Rotated Sorted Array II - LeetCode javascript solutions
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;
+ } elseif (nums[mid] < nums[right]) {
+ right = mid;
+ } else {
+ right--;
+ }
+ }
+ return nums[left];
+};
+
+
Explain:
+
nope.
+
Complexity:
+
+
Time complexity : O(n).
+
Space complexity : O(n).
+
\ 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
new file mode 100644
index 0000000..a10d419
--- /dev/null
+++ b/docs/problem/find-minimum-in-rotated-sorted-array.html
@@ -0,0 +1,41 @@
+Find Minimum in Rotated Sorted Array - LeetCode javascript solutions
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).
+
\ No newline at end of file
diff --git a/docs/problem/find-mode-in-binary-search-tree.html b/docs/problem/find-mode-in-binary-search-tree.html
new file mode 100644
index 0000000..37999ce
--- /dev/null
+++ b/docs/problem/find-mode-in-binary-search-tree.html
@@ -0,0 +1,80 @@
+Find Mode in Binary Search Tree - LeetCode javascript solutions
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).
+
\ No newline at end of file
diff --git a/docs/problem/find-peak-element.html b/docs/problem/find-peak-element.html
new file mode 100644
index 0000000..d833028
--- /dev/null
+++ b/docs/problem/find-peak-element.html
@@ -0,0 +1,48 @@
+Find Peak Element - LeetCode javascript solutions
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: 3is a peak element and your functionshouldreturnthe index number 2.
+
+
Example 2:
+
Input: nums = [1,2,1,3,5,6,4]
+Output: 1 or 5
+Explanation: Your function can return either indexnumber1where the peak elementis2,
+ or indexnumber5where the peak elementis6.
+
+
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).
+
\ No newline at end of file
diff --git a/docs/problem/find-the-difference-of-two-arrays.html b/docs/problem/find-the-difference-of-two-arrays.html
new file mode 100644
index 0000000..077539c
--- /dev/null
+++ b/docs/problem/find-the-difference-of-two-arrays.html
@@ -0,0 +1,63 @@
+Find the Difference of Two Arrays - LeetCode javascript solutions
Given two 0-indexed integer arrays nums1 and nums2, return a listanswerof size2where:
+
+
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
+
/**
+ * @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 = [newSet(), newSet()];
+ 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).
+
\ No newline at end of file
diff --git a/docs/problem/find-the-difference.html b/docs/problem/find-the-difference.html
new file mode 100644
index 0000000..95c673e
--- /dev/null
+++ b/docs/problem/find-the-difference.html
@@ -0,0 +1,69 @@
+Find the Difference - LeetCode javascript solutions
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
+
/**
+ * @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);
+ }
+ returnString.fromCharCode(num);
+};
+
+
Explain:
+
nope.
+
Complexity:
+
+
Time complexity : O(n).
+
Space complexity : O(1).
+
+
Solution 2
+
/**
+ * @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);
+ }
+ returnString.fromCharCode(num);
+};
+
+
Explain:
+
nope.
+
Complexity:
+
+
Time complexity : O(n).
+
Space complexity : O(1).
+
\ No newline at end of file
diff --git a/docs/problem/find-the-duplicate-number.html b/docs/problem/find-the-duplicate-number.html
new file mode 100644
index 0000000..db84c7d
--- /dev/null
+++ b/docs/problem/find-the-duplicate-number.html
@@ -0,0 +1,62 @@
+Find the Duplicate Number - LeetCode javascript solutions
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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/find-the-highest-altitude.html b/docs/problem/find-the-highest-altitude.html
new file mode 100644
index 0000000..e87333b
--- /dev/null
+++ b/docs/problem/find-the-highest-altitude.html
@@ -0,0 +1,43 @@
+Find the Highest Altitude - LeetCode javascript solutions
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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/find-the-longest-semi-repetitive-substring.html b/docs/problem/find-the-longest-semi-repetitive-substring.html
new file mode 100644
index 0000000..c8fc252
--- /dev/null
+++ b/docs/problem/find-the-longest-semi-repetitive-substring.html
@@ -0,0 +1,55 @@
+Find the Longest Semi-Repetitive Substring - LeetCode javascript solutions
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 insides.
+
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 substringis"5223", which starts at i = 0and ends at j = 3.
+
+
Example 2:
+
Input: s = "5494"
+Output:4
+Explanation: s isa semi-reptitive string, so the answer is4.
+
+
Example 3:
+
Input: s = "1111111"
+Output: 2
+Explanation: The longest semi-repetitive substringis"11", which starts at i = 0and ends at j = 1.
+
+
+Constraints:
+
+
1 <= s.length <= 50
+
'0' <= s[i] <= '9'
+
+
Solution
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/find-the-longest-valid-obstacle-course-at-each-position.html b/docs/problem/find-the-longest-valid-obstacle-course-at-each-position.html
new file mode 100644
index 0000000..e2c88a3
--- /dev/null
+++ b/docs/problem/find-the-longest-valid-obstacle-course-at-each-position.html
@@ -0,0 +1,89 @@
+Find the Longest Valid Obstacle Course at Each Position - LeetCode javascript solutions
1964. Find the Longest Valid Obstacle Course at Each Position
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 iinclusive.
+
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 arrayansof lengthn, whereans[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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/find-the-original-array-of-prefix-xor.html b/docs/problem/find-the-original-array-of-prefix-xor.html
new file mode 100644
index 0000000..4427e77
--- /dev/null
+++ b/docs/problem/find-the-original-array-of-prefix-xor.html
@@ -0,0 +1,49 @@
+Find The Original Array of Prefix Xor - LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/problem/find-the-town-judge.html b/docs/problem/find-the-town-judge.html
new file mode 100644
index 0000000..c6019b9
--- /dev/null
+++ b/docs/problem/find-the-town-judge.html
@@ -0,0 +1,58 @@
+Find the Town Judge - LeetCode javascript solutions
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
+
\ No newline at end of file
diff --git a/docs/problem/find-the-winner-of-an-array-game.html b/docs/problem/find-the-winner-of-an-array-game.html
new file mode 100644
index 0000000..5b1e507
--- /dev/null
+++ b/docs/problem/find-the-winner-of-an-array-game.html
@@ -0,0 +1,52 @@
+Find the Winner of an Array Game - LeetCode javascript solutions
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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/find-unique-binary-string.html b/docs/problem/find-unique-binary-string.html
new file mode 100644
index 0000000..56b7fda
--- /dev/null
+++ b/docs/problem/find-unique-binary-string.html
@@ -0,0 +1,50 @@
+Find Unique Binary String - LeetCode javascript solutions
Given an array of strings nums containing nunique 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.
+
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).
+
\ No newline at end of file
diff --git a/docs/problem/find-words-that-can-be-formed-by-characters.html b/docs/problem/find-words-that-can-be-formed-by-characters.html
new file mode 100644
index 0000000..091955c
--- /dev/null
+++ b/docs/problem/find-words-that-can-be-formed-by-characters.html
@@ -0,0 +1,52 @@
+Find Words That Can Be Formed by Characters - LeetCode javascript solutions
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 is3 + 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 is5 + 5 = 10.
+
+
+Constraints:
+
+
1 <= words.length <= 1000
+
1 <= words[i].length, chars.length <= 100
+
words[i] and chars consist of lowercase English letters.
+
+
Solution
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/first-missing-positive.html b/docs/problem/first-missing-positive.html
new file mode 100644
index 0000000..6af1b43
--- /dev/null
+++ b/docs/problem/first-missing-positive.html
@@ -0,0 +1,50 @@
+First Missing Positive - LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/problem/first-unique-character-in-a-string.html b/docs/problem/first-unique-character-in-a-string.html
new file mode 100644
index 0000000..52c9b78
--- /dev/null
+++ b/docs/problem/first-unique-character-in-a-string.html
@@ -0,0 +1,44 @@
+First Unique Character in a String - LeetCode javascript solutions
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
+
/**
+ * @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).
+
\ 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
new file mode 100644
index 0000000..a0835a2
--- /dev/null
+++ b/docs/problem/flatten-binary-tree-to-linked-list.html
@@ -0,0 +1,61 @@
+Flatten Binary Tree to Linked List - LeetCode javascript solutions
Given a binary tree, flatten it to a linked list in-place.
+
For example, given the following tree:
+
1
+ / \
+ 25
+ / \ \
+346
+
+
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) returnnull;
+
+ 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).
+
\ No newline at end of file
diff --git a/docs/problem/flatten-nested-list-iterator.html b/docs/problem/flatten-nested-list-iterator.html
new file mode 100644
index 0000000..3e2b78e
--- /dev/null
+++ b/docs/problem/flatten-nested-list-iterator.html
@@ -0,0 +1,109 @@
+Flatten Nested List Iterator - LeetCode javascript solutions
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<NestedInteger> 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 iteratorwith nestedList
+res = []
+whileiterator.hasNext()
+ append iterator.next() to the endof 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 orderof elements returned bynext 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
+
/**
+ * // 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() {
+ returnthis.index < this.list.length;
+};
+
+/**
+ * @this NestedIterator
+ * @returns {integer}
+ */
+NestedIterator.prototype.next = function() {
+ returnthis.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).
+
\ No newline at end of file
diff --git a/docs/problem/flipping-an-image.html b/docs/problem/flipping-an-image.html
new file mode 100644
index 0000000..c51ea77
--- /dev/null
+++ b/docs/problem/flipping-an-image.html
@@ -0,0 +1,58 @@
+Flipping an Image - LeetCode javascript solutions
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). n 为 A.length。
+
Space complexity : O(1).
+
\ No newline at end of file
diff --git a/docs/problem/flower-planting-with-no-adjacent.html b/docs/problem/flower-planting-with-no-adjacent.html
new file mode 100644
index 0000000..648ed9e
--- /dev/null
+++ b/docs/problem/flower-planting-with-no-adjacent.html
@@ -0,0 +1,68 @@
+Flower Planting With No Adjacent - LeetCode javascript solutions
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:
+Gardens1 and 2 have different types.
+Gardens2 and 3 have different types.
+Gardens3 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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/fraction-to-recurring-decimal.html b/docs/problem/fraction-to-recurring-decimal.html
new file mode 100644
index 0000000..e5bef7f
--- /dev/null
+++ b/docs/problem/fraction-to-recurring-decimal.html
@@ -0,0 +1,61 @@
+Fraction to Recurring Decimal - LeetCode javascript solutions
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/frequency-of-the-most-frequent-element.html b/docs/problem/frequency-of-the-most-frequent-element.html
new file mode 100644
index 0000000..ef6e7f9
--- /dev/null
+++ b/docs/problem/frequency-of-the-most-frequent-element.html
@@ -0,0 +1,84 @@
+Frequency of the Most Frequent Element - LeetCode javascript solutions
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 mostk operations**.
+
+Example 1:
+
Input: nums = [1,2,4], k = 5
+Output: 3
+Explanation: Increment thefirstelementthree times andthesecondelementtwo times to make nums = [4,4,4].
+4 has a frequency of3.
+
+
Example 2:
+
Input: nums = [1,4,8,13], k = 5
+Output: 2
+Explanation: There are multiple optimal solutions:
+- Increment thefirstelementthree times to make nums = [4,4,8,13]. 4 has a frequency of2.
+- Increment thesecondelementfour times to make nums = [1,8,8,13]. 8 has a frequency of2.
+- Increment thethirdelementfive times to make nums = [1,4,13,13]. 13 has a frequency of2.
+
+
Example 3:
+
Input: nums = [3,9,6], k = 2
+Output:1
+
+
+Constraints:
+
+
1 <= nums.length <= 105
+
1 <= nums[i] <= 105
+
1 <= k <= 105
+
+
Solution
+
/**
+ * @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;
+ } elseif (midValue > k) {
+ left = mid + 1;
+ } else {
+ if (mid === left) return mid;
+ right = mid;
+ }
+ }
+ return i;
+};
+
+
Explain:
+
+
sort the array of nums by ascending order
+
calculate prefix sum array
+
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).
+
\ No newline at end of file
diff --git a/docs/problem/friend-circles.html b/docs/problem/friend-circles.html
new file mode 100644
index 0000000..58ec5c4
--- /dev/null
+++ b/docs/problem/friend-circles.html
@@ -0,0 +1,62 @@
+Friend Circles - LeetCode javascript solutions
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 and1st students are direct friends, so they are in a friend circle. The 2nd student himself is in a friend circle. So return2.
+
+
Example 2:
+
Input:
+[[1,1,0],
+ [1,1,1],
+ [0,1,1]]
+Output:1
+Explanation:The 0thand1st students are direct friends, the 1stand2nd students are direct friends, so the 0thand2nd students are indirect friends. All of them are in the same friend circle, soreturn1.
+
+
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).
+
\ No newline at end of file
diff --git a/docs/problem/frog-jump.html b/docs/problem/frog-jump.html
new file mode 100644
index 0000000..660b592
--- /dev/null
+++ b/docs/problem/frog-jump.html
@@ -0,0 +1,53 @@
+Frog Jump - LeetCode javascript solutions
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 tothelast stone by jumping 1 unit tothe2nd stone, then2 units tothe3rd stone, then2 units tothe4th stone, then3 units tothe6th stone, 4 units tothe7th stone, and5 units tothe8th stone.
+
+
Example 2:
+
Input: stones = [0,1,2,3,4,8,9,11]
+Output: false
+Explanation: There isno way to jump to the last stone as the gap between the 5thand6th 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
+
/**
+ * @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]) returnfalse;
+ 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)) returntrue;
+ }
+ dp[i][k] = true;
+ return i === stones.length - 1;
+};
+
+
Explain:
+
nope.
+
Complexity:
+
+
Time complexity : O(n ^ 2).
+
Space complexity : O(n ^ 2).
+
\ No newline at end of file
diff --git a/docs/problem/furthest-building-you-can-reach.html b/docs/problem/furthest-building-you-can-reach.html
new file mode 100644
index 0000000..6654f1e
--- /dev/null
+++ b/docs/problem/furthest-building-you-can-reach.html
@@ -0,0 +1,65 @@
+Furthest Building You Can Reach - LeetCode javascript solutions
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:
+
+
Input: heights = [4,2,7,6,9,14,12], bricks = 5, ladders = 1
+Output:4
+Explanation: Starting atbuilding 0, you can follow these steps:
+- Go to building 1 without using ladders nor bricks since 4 >= 2.
+- Go to building 2 using 5bricks. 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 4because you do not have any more bricks or ladders.
+
\ No newline at end of file
diff --git a/docs/problem/gas-station.html b/docs/problem/gas-station.html
new file mode 100644
index 0000000..832da70
--- /dev/null
+++ b/docs/problem/gas-station.html
@@ -0,0 +1,73 @@
+Gas Station - LeetCode javascript solutions
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:
+Startat station 3 (index3) and fill up with4 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 costis5. Your gas is just enough to travel back to station 3.
+Therefore, return3as the starting index.
+
+
Example 2:
+
Input:
+gas = [2,3,4]
+cost = [3,4,3]
+
+Output: -1
+
+Explanation:
+You can't start at station 0or1, as there isnot enough gas to travel tothe next station.
+Let's start at station 2and fill up with4 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 backto station 2, asit requires 4 unit of gas but you only have 3.
+Therefore, you can't travel aroundthe 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:
+
+
n 点到不了 m 点,则其间所有点都到不了 m 点
+
总和大于等于 0 说明有解
+
+
Complexity:
+
+
Time complexity : O(n).
+
Space complexity : O(1).
+
\ No newline at end of file
diff --git a/docs/problem/generate-parentheses.html b/docs/problem/generate-parentheses.html
new file mode 100644
index 0000000..98d4b22
--- /dev/null
+++ b/docs/problem/generate-parentheses.html
@@ -0,0 +1,43 @@
+Generate Parentheses - LeetCode javascript solutions
/**
+ * @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:
+
每一层最多两种情况:
+
+
右括号比左括号多,加右括号
+
还有左括号,加左括号
+
+
Complexity:
+
+
Time complexity : O((4^n)/(n^(-1))).
+
Space complexity : O((4^n)/(n^(-1))).
+
\ No newline at end of file
diff --git a/docs/problem/generate-random-point-in-a-circle.html b/docs/problem/generate-random-point-in-a-circle.html
new file mode 100644
index 0000000..6e03245
--- /dev/null
+++ b/docs/problem/generate-random-point-in-a-circle.html
@@ -0,0 +1,68 @@
+Generate Random Point in a Circle - LeetCode javascript solutions
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].
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).
+
\ No newline at end of file
diff --git a/docs/problem/group-anagrams.html b/docs/problem/group-anagrams.html
new file mode 100644
index 0000000..afe255b
--- /dev/null
+++ b/docs/problem/group-anagrams.html
@@ -0,0 +1,40 @@
+Group Anagrams - LeetCode javascript solutions
/**
+ * @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]);
+ }
+ returnObject.values(res);
+};
+
+
Explain:
+
把每个字符串排序一下,用哈希表存起来
+
Complexity:
+
+
Time complexity : O(m * nlog(n)). m 为数组长度, n 为字符长度。
+
Space complexity : O(m).
+
\ No newline at end of file
diff --git a/docs/problem/group-the-people-given-the-group-size-they-belong-to.html b/docs/problem/group-the-people-given-the-group-size-they-belong-to.html
new file mode 100644
index 0000000..0e3d5a9
--- /dev/null
+++ b/docs/problem/group-the-people-given-the-group-size-they-belong-to.html
@@ -0,0 +1,52 @@
+Group the People Given the Group Size They Belong To - LeetCode javascript solutions
1282. Group the People Given the Group Size They Belong To
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]].
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/happy-number.html b/docs/problem/happy-number.html
new file mode 100644
index 0000000..fd3b413
--- /dev/null
+++ b/docs/problem/happy-number.html
@@ -0,0 +1,86 @@
+Happy Number - LeetCode javascript solutions
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.
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, and5 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.
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/house-robber-ii.html b/docs/problem/house-robber-ii.html
new file mode 100644
index 0000000..826023c
--- /dev/null
+++ b/docs/problem/house-robber-ii.html
@@ -0,0 +1,47 @@
+House Robber II - LeetCode javascript solutions
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) andthen 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) andthen 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
+
/**
+ * @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);
+ }
+ returnMath.max(nums[0] + (arr2[2] || 0), arr1[1] || 0);
+};
+
+
Explain:
+
nope.
+
Complexity:
+
+
Time complexity : O(n).
+
Space complexity : O(n).
+
\ No newline at end of file
diff --git a/docs/problem/house-robber.html b/docs/problem/house-robber.html
new file mode 100644
index 0000000..4274ba9
--- /dev/null
+++ b/docs/problem/house-robber.html
@@ -0,0 +1,87 @@
+House Robber - LeetCode javascript solutions
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) return0;
+ 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).
+
\ No newline at end of file
diff --git a/docs/problem/image-overlap.html b/docs/problem/image-overlap.html
new file mode 100644
index 0000000..061c301
--- /dev/null
+++ b/docs/problem/image-overlap.html
@@ -0,0 +1,94 @@
+Image Overlap - LeetCode javascript solutions
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.
+
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).
+
+
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.
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/implement-queue-using-stacks.html b/docs/problem/implement-queue-using-stacks.html
new file mode 100644
index 0000000..a97cec2
--- /dev/null
+++ b/docs/problem/implement-queue-using-stacks.html
@@ -0,0 +1,97 @@
+Implement Queue using Stacks - LeetCode javascript solutions
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 amortizedO(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
+
+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());
+ }
+ returnthis.stack2.pop();
+};
+
+/**
+ * @return {number}
+ */
+MyQueue.prototype.peek = function() {
+ if (this.stack2.length === 0) {
+ while (this.stack1.length) this.stack2.push(this.stack1.pop());
+ }
+ returnthis.stack2[this.stack2.length - 1];
+};
+
+/**
+ * @return {boolean}
+ */
+MyQueue.prototype.empty = function() {
+ returnthis.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).
+
\ No newline at end of file
diff --git a/docs/problem/implement-strstr.html b/docs/problem/implement-strstr.html
new file mode 100644
index 0000000..0ab110c
--- /dev/null
+++ b/docs/problem/implement-strstr.html
@@ -0,0 +1,41 @@
+Implement strStr() - LeetCode javascript solutions
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]) returnfalse;
+ 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]) returnfalse;
+ node = node[char];
+ }
+ returntrue;
+};
+
+/**
+ * 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).
+
\ No newline at end of file
diff --git a/docs/problem/insert-delete-getrandom-o1-duplicates-allowed.html b/docs/problem/insert-delete-getrandom-o1-duplicates-allowed.html
new file mode 100644
index 0000000..1253b50
--- /dev/null
+++ b/docs/problem/insert-delete-getrandom-o1-duplicates-allowed.html
@@ -0,0 +1,109 @@
+Insert Delete GetRandom O(1) - Duplicates allowed - LeetCode javascript solutions
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 averageO(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 = newRandomizedCollection();
+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
+
+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) returnfalse;
+ var valIndexs = this.map[val].arr;
+ var delIndex = valIndexs[valIndexs.length - 1];
+ var lastValue = this.arr.pop();
+ if (valIndexs.length === 1) {
+ deletethis.map[val];
+ } else {
+ valIndexs.pop();
+ deletethis.map[val].map[delIndex];
+ }
+ if (lastValue !== val) {
+ var lastValueIndex = this.map[lastValue].map[this.arr.length];
+ this.map[lastValue].arr[lastValueIndex] = delIndex;
+ deletethis.map[lastValue].map[this.arr.length];
+ this.map[lastValue].map[delIndex] = lastValueIndex;
+ this.arr[delIndex] = lastValue;
+ }
+ returntrue;
+};
+
+/**
+ * @return {number}
+ */
+RandomizedCollection.prototype.getRandom = function() {
+ var num = Math.floor(Math.random() * this.arr.length);
+ returnthis.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).
+
\ No newline at end of file
diff --git a/docs/problem/insert-delete-getrandom-o1.html b/docs/problem/insert-delete-getrandom-o1.html
new file mode 100644
index 0000000..20fee60
--- /dev/null
+++ b/docs/problem/insert-delete-getrandom-o1.html
@@ -0,0 +1,95 @@
+Insert Delete GetRandom O(1) - LeetCode javascript solutions
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 averageO(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 = newRandomizedSet();
+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
+
+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);
+ returntrue;
+ }
+ returnfalse;
+};
+
+/**
+ * @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;
+ }
+ deletethis.map[val];
+ returntrue;
+ }
+ returnfalse;
+};
+
+/**
+ * @return {number}
+ */
+RandomizedSet.prototype.getRandom = function() {
+ const num = Math.floor(Math.random() * this.arr.length);
+ returnthis.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).
+
\ No newline at end of file
diff --git a/docs/problem/insert-interval.html b/docs/problem/insert-interval.html
new file mode 100644
index 0000000..52164c1
--- /dev/null
+++ b/docs/problem/insert-interval.html
@@ -0,0 +1,53 @@
+Insert Interval - LeetCode javascript solutions
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).
+
\ No newline at end of file
diff --git a/docs/problem/insertion-sort-list.html b/docs/problem/insertion-sort-list.html
new file mode 100644
index 0000000..a668836
--- /dev/null
+++ b/docs/problem/insertion-sort-list.html
@@ -0,0 +1,56 @@
+Insertion Sort List - LeetCode javascript solutions
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).
+
\ No newline at end of file
diff --git a/docs/problem/integer-break.html b/docs/problem/integer-break.html
new file mode 100644
index 0000000..bc4b3a6
--- /dev/null
+++ b/docs/problem/integer-break.html
@@ -0,0 +1,48 @@
+Integer Break - LeetCode javascript solutions
/**
+ * @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;
+ } elseif (n <= 4 && n >= 2) {
+ res *= n;
+ n = 0;
+ } elseif (n === 1) {
+ n = 0;
+ }
+ }
+ return res;
+};
+
+
Explain:
+
nope.
+
Complexity:
+
+
Time complexity : O(n).
+
Space complexity : O(1).
+
\ No newline at end of file
diff --git a/docs/problem/integer-to-roman.html b/docs/problem/integer-to-roman.html
new file mode 100644
index 0000000..206f4f8
--- /dev/null
+++ b/docs/problem/integer-to-roman.html
@@ -0,0 +1,142 @@
+Integer to Roman - LeetCode javascript solutions
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 = 30andIII = 3.
+
+
Example 5:
+
Input: 1994
+Output: "MCMXCIV"
+Explanation: M = 1000, CM = 900, XC = 90andIV = 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;
+ } elseif (tmp >= 5) {
+ res = str[i][1] + str[i][0].repeat(tmp - 5) + res;
+ } elseif (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;
+};
+
/**
+ * @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) returnfalse;
+ 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) returntrue;
+ 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);
+ } elseif (s3[k] === s1[i]) {
+ res = helper(s1, s2, s3, i + 1, j, k + 1, dp);
+ } elseif (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). n 为 s3.length。
+
Space complexity : O(n^2).
+
\ 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
new file mode 100644
index 0000000..7d41cbb
--- /dev/null
+++ b/docs/problem/intersection-of-two-linked-lists.html
@@ -0,0 +1,102 @@
+Intersection of Two Linked Lists - LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/problem/invert-binary-tree.html b/docs/problem/invert-binary-tree.html
new file mode 100644
index 0000000..f42fa27
--- /dev/null
+++ b/docs/problem/invert-binary-tree.html
@@ -0,0 +1,54 @@
+Invert Binary Tree - LeetCode javascript solutions
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
+
/**
+ * @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]) returnfalse;
+ j++;
+ }
+ returntrue;
+};
+
+
Explain:
+
nope.
+
Complexity:
+
+
Time complexity : O(n).
+
Space complexity : O(1).
+
\ No newline at end of file
diff --git a/docs/problem/jump-game-ii.html b/docs/problem/jump-game-ii.html
new file mode 100644
index 0000000..04db7b6
--- /dev/null
+++ b/docs/problem/jump-game-ii.html
@@ -0,0 +1,44 @@
+Jump Game II - LeetCode javascript solutions
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 jumpsto reach the lastindexis2.
+ Jump 1 step from index0to1, then 3 steps to the lastindex.
+
+
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).
+
\ No newline at end of file
diff --git a/docs/problem/jump-game.html b/docs/problem/jump-game.html
new file mode 100644
index 0000000..454f6f9
--- /dev/null
+++ b/docs/problem/jump-game.html
@@ -0,0 +1,37 @@
+Jump Game - LeetCode javascript solutions
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 1stepfromindex0to1, then3 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 lengthis0, which makes it impossible to reach thelast 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) returnfalse;
+ max = Math.max(max, i + nums[i]);
+ }
+ returntrue;
+};
+
+
Explain:
+
nope.
+
Complexity:
+
+
Time complexity : O(n).
+
Space complexity : O(1).
+
\ No newline at end of file
diff --git a/docs/problem/k-th-symbol-in-grammar.html b/docs/problem/k-th-symbol-in-grammar.html
new file mode 100644
index 0000000..ee5f457
--- /dev/null
+++ b/docs/problem/k-th-symbol-in-grammar.html
@@ -0,0 +1,57 @@
+K-th Symbol in Grammar - LeetCode javascript solutions
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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/knight-dialer.html b/docs/problem/knight-dialer.html
new file mode 100644
index 0000000..ed4cadf
--- /dev/null
+++ b/docs/problem/knight-dialer.html
@@ -0,0 +1,79 @@
+Knight Dialer - LeetCode javascript solutions
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:
+
+
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).
+
+
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 modulo109 + 7.
+
+Example 1:
+
Input: n = 1
+Output: 10
+Explanation: We need to dial anumberoflength1, so placing the knight over anynumeric cell ofthe10 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
+
/**
+ * @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) return1;
+ if (i === 5) return0;
+ 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).
+
\ No newline at end of file
diff --git a/docs/problem/knight-probability-in-chessboard.html b/docs/problem/knight-probability-in-chessboard.html
new file mode 100644
index 0000000..24ddb9d
--- /dev/null
+++ b/docs/problem/knight-probability-in-chessboard.html
@@ -0,0 +1,127 @@
+Knight Probability in Chessboard - LeetCode javascript solutions
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.
+
+
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 ontheboard.
+From eachof those positions, there are also two moves that will keep the knight ontheboard.
+The total probability the knight stays ontheboardis0.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
+
/**
+ * @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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/koko-eating-bananas.html b/docs/problem/koko-eating-bananas.html
new file mode 100644
index 0000000..ad9310a
--- /dev/null
+++ b/docs/problem/koko-eating-bananas.html
@@ -0,0 +1,61 @@
+Koko Eating Bananas - LeetCode javascript solutions
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 integerksuch that she can eat all the bananas withinhhours.
+
+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
+
/**
+ * @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).
+
\ 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
new file mode 100644
index 0000000..1e952cf
--- /dev/null
+++ b/docs/problem/kth-largest-element-in-an-array.html
@@ -0,0 +1,49 @@
+Kth Largest Element in an Array - LeetCode javascript solutions
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];
+ elseif (len < k - 1) return quickSelect(nums, left, le - 1, k - len - 1);
+ elsereturn 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).
+
\ No newline at end of file
diff --git a/docs/problem/kth-smallest-element-in-a-bst.html b/docs/problem/kth-smallest-element-in-a-bst.html
new file mode 100644
index 0000000..2c2b1fe
--- /dev/null
+++ b/docs/problem/kth-smallest-element-in-a-bst.html
@@ -0,0 +1,59 @@
+Kth Smallest Element in a BST - LeetCode javascript solutions
Given the root of a binary search tree, and an integer k, return thekthsmallest value (1-indexed) of all the values of the nodes in the tree.
+
+Example 1:
+
+
Input: root = [3,1,4,null,2], k = 1
+Output:1
+
+
Example 2:
+
+
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?
\ No newline at end of file
diff --git a/docs/problem/largest-3-same-digit-number-in-string.html b/docs/problem/largest-3-same-digit-number-in-string.html
new file mode 100644
index 0000000..b4c71cf
--- /dev/null
+++ b/docs/problem/largest-3-same-digit-number-in-string.html
@@ -0,0 +1,63 @@
+Largest 3-Same-Digit Number in String - LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/problem/largest-number.html b/docs/problem/largest-number.html
new file mode 100644
index 0000000..718636b
--- /dev/null
+++ b/docs/problem/largest-number.html
@@ -0,0 +1,33 @@
+Largest Number - LeetCode javascript solutions
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) return0;
+ return str1 > str2 ? -1 : 1;
+ }).join('');
+ return res[0] === '0' ? '0' : res;
+};
+
+
Explain:
+
nope.
+
Complexity:
+
+
Time complexity : O(nlog(n)).
+
Space complexity : O(1).
+
\ No newline at end of file
diff --git a/docs/problem/largest-odd-number-in-string.html b/docs/problem/largest-odd-number-in-string.html
new file mode 100644
index 0000000..43583d0
--- /dev/null
+++ b/docs/problem/largest-odd-number-in-string.html
@@ -0,0 +1,53 @@
+Largest Odd Number in String - LeetCode javascript solutions
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.
\ No newline at end of file
diff --git a/docs/problem/largest-palindromic-number.html b/docs/problem/largest-palindromic-number.html
new file mode 100644
index 0000000..090a41c
--- /dev/null
+++ b/docs/problem/largest-palindromic-number.html
@@ -0,0 +1,64 @@
+Largest Palindromic Number - LeetCode javascript solutions
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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/largest-rectangle-in-histogram.html b/docs/problem/largest-rectangle-in-histogram.html
new file mode 100644
index 0000000..05ff44d
--- /dev/null
+++ b/docs/problem/largest-rectangle-in-histogram.html
@@ -0,0 +1,41 @@
+Largest Rectangle in Histogram - LeetCode javascript solutions
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).
+
\ No newline at end of file
diff --git a/docs/problem/largest-submatrix-with-rearrangements.html b/docs/problem/largest-submatrix-with-rearrangements.html
new file mode 100644
index 0000000..8b7c3b6
--- /dev/null
+++ b/docs/problem/largest-submatrix-with-rearrangements.html
@@ -0,0 +1,108 @@
+Largest Submatrix With Rearrangements - LeetCode javascript solutions
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:
+
+
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:
+
+
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
+
/**
+ * @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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/largest-substring-between-two-equal-characters.html b/docs/problem/largest-substring-between-two-equal-characters.html
new file mode 100644
index 0000000..86425ad
--- /dev/null
+++ b/docs/problem/largest-substring-between-two-equal-characters.html
@@ -0,0 +1,55 @@
+Largest Substring Between Two Equal Characters - LeetCode javascript solutions
1624. Largest Substring Between Two Equal Characters
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 anempty substring between thetwo'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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/last-day-where-you-can-still-cross.html b/docs/problem/last-day-where-you-can-still-cross.html
new file mode 100644
index 0000000..c91b7ca
--- /dev/null
+++ b/docs/problem/last-day-where-you-can-still-cross.html
@@ -0,0 +1,103 @@
+Last Day Where You Can Still Cross - LeetCode javascript solutions
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:
+
+
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 onday2.
+
+
Example 2:
+
+
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 onday1.
+
+
Example 3:
+
+
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
+
/**
+ * @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) returntrue;
+ 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;
+ }
+ }
+ returnfalse;
+};
+
+
Explain:
+
+
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.
+
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).
+
\ No newline at end of file
diff --git a/docs/problem/last-moment-before-all-ants-fall-out-of-a-plank.html b/docs/problem/last-moment-before-all-ants-fall-out-of-a-plank.html
new file mode 100644
index 0000000..4ca65cf
--- /dev/null
+++ b/docs/problem/last-moment-before-all-ants-fall-out-of-a-plank.html
@@ -0,0 +1,66 @@
+Last Moment Before All Ants Fall Out of a Plank - LeetCode javascript solutions
1503. Last Moment Before All Ants Fall Out of a Plank
We have a wooden plank of the length nunits. 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:
+
+
Input: n = 4, left = [4,3], right = [0,1]
+Output: 4
+Explanation: In the image above:
+-The ant at index 0is named A and going tothe right.
+-The ant at index 1is named B and going tothe right.
+-The ant at index 3is named C and going tothe left.
+-The ant at index 4is named D and going tothe left.
+The last moment when an ant was onthe plank is t = 4 seconds. After that, it falls immediately out ofthe plank. (i.e., We can saythatat t = 4.0000000001, there are no ants onthe plank).
+
+
Example 2:
+
+
Input: n = 7, left = [], right = [0,1,2,3,4,5,6,7]
+Output: 7
+Explanation: All ants are going totheright, the ant at index 0 needs 7secondsto fall.
+
+
Example 3:
+
+
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 index7 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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/leaf-similar-trees.html b/docs/problem/leaf-similar-trees.html
new file mode 100644
index 0000000..49237cc
--- /dev/null
+++ b/docs/problem/leaf-similar-trees.html
@@ -0,0 +1,59 @@
+Leaf-Similar Trees - LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/problem/least-number-of-unique-integers-after-k-removals.html b/docs/problem/least-number-of-unique-integers-after-k-removals.html
new file mode 100644
index 0000000..0c59256
--- /dev/null
+++ b/docs/problem/least-number-of-unique-integers-after-k-removals.html
@@ -0,0 +1,83 @@
+Least Number of Unique Integers after K Removals - LeetCode javascript solutions
1481. Least Number of Unique Integers after K Removals
Given an array of integers arr and an integer k. Find the least number of unique integers after removing exactlyk elements.
+
+Example 1:
+
Input: arr = [5,5,4], k = 1
+Output:1
+Explanation: Remove the single 4, only5isleft.
+
+
Example 2:
+
Input: arr = [4,3,1,1,3,3,2], k = 3
+Output: 2
+Explanation: Remove 4, 2and either oneofthetwo1s orthree3s. 1and3 will be left.
+
+
+Constraints:
+
+
1 <= arr.length <= 10^5
+
1 <= arr[i] <= 10^9
+
0 <= k <= arr.length
+
+
Solution 1
+
/**
+ * @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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/length-of-last-word.html b/docs/problem/length-of-last-word.html
new file mode 100644
index 0000000..af4c217
--- /dev/null
+++ b/docs/problem/length-of-last-word.html
@@ -0,0 +1,28 @@
+Length of Last Word - LeetCode javascript solutions
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).
+
\ 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
new file mode 100644
index 0000000..3db8916
--- /dev/null
+++ b/docs/problem/letter-combinations-of-a-phone-number.html
@@ -0,0 +1,39 @@
+Letter Combinations of a Phone Number - LeetCode javascript solutions
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 :
+
\ No newline at end of file
diff --git a/docs/problem/linked-list-cycle-ii.html b/docs/problem/linked-list-cycle-ii.html
new file mode 100644
index 0000000..31da56b
--- /dev/null
+++ b/docs/problem/linked-list-cycle-ii.html
@@ -0,0 +1,57 @@
+Linked List Cycle II - LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/problem/linked-list-cycle.html b/docs/problem/linked-list-cycle.html
new file mode 100644
index 0000000..2691608
--- /dev/null
+++ b/docs/problem/linked-list-cycle.html
@@ -0,0 +1,35 @@
+Linked List Cycle - LeetCode javascript solutions
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) returntrue;
+ }
+ returnfalse;
+};
+
+
Explain:
+
fast 每次走两步,slow 每次走一步,如果链表有环的话,它们最终会相遇。
+
Complexity:
+
+
Time complexity : O(n).
+
Space complexity : O(1).
+
\ No newline at end of file
diff --git a/docs/problem/longest-common-prefix.html b/docs/problem/longest-common-prefix.html
new file mode 100644
index 0000000..ae22b33
--- /dev/null
+++ b/docs/problem/longest-common-prefix.html
@@ -0,0 +1,42 @@
+Longest Common Prefix - LeetCode javascript solutions
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).
+
\ No newline at end of file
diff --git a/docs/problem/longest-common-subsequence.html b/docs/problem/longest-common-subsequence.html
new file mode 100644
index 0000000..9bed69b
--- /dev/null
+++ b/docs/problem/longest-common-subsequence.html
@@ -0,0 +1,62 @@
+Longest Common Subsequence - LeetCode javascript solutions
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"anditslengthis3.
+
+
Example 2:
+
Input: text1 = "abc", text2 = "abc"
+Output: 3
+Explanation: The longest common subsequence is"abc"anditslengthis3.
+
+
Example 3:
+
Input: text1 = "abc", text2 = "def"
+Output:0
+Explanation: There isno such common subsequence, so the result is0.
+
+
+Constraints:
+
+
1 <= text1.length, text2.length <= 1000
+
text1 and text2 consist of only lowercase English characters.
Given a string s, find **the longest palindromic **subsequence's length ins.
+
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".
+
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).
+
+
/**
+ * @param {string} s
+ * @return {string}
+ */
+var longestPalindrome = function(s) {
+ let startIndex = 0;
+ let maxLength = 1;
+
+ functionexpandAroundCenter(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).
+
\ No newline at end of file
diff --git a/docs/problem/longest-string-chain.html b/docs/problem/longest-string-chain.html
new file mode 100644
index 0000000..137d1f2
--- /dev/null
+++ b/docs/problem/longest-string-chain.html
@@ -0,0 +1,85 @@
+Longest String Chain - LeetCode javascript solutions
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 wordAwithout 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 ofthe longest word chains is ["a","ba","bda","bdca"].
+
+
Example 2:
+
Input: words = ["xbc","pcxbcf","xb","cxbc","pcxbc"]
+Output: 5
+Explanation: All thewords can be putinaword chain ["xb", "xbc", "cxbc", "pcxbc", "pcxbcf"].
+
+
Example 3:
+
Input: words = ["abcd","dbqca"]
+Output: 1
+Explanation: The trivial word chain ["abcd"] is one ofthe longest word chains.
+["abcd","dbqca"] isnot a valid word chain because the ordering ofthe letters is changed.
+
+
+Constraints:
+
+
1 <= words.length <= 1000
+
1 <= words[i].length <= 16
+
words[i] only consists of lowercase English letters.
+
+
Solution
+
/**
+ * @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 {
+ returnfalse;
+ }
+ }
+ i++;
+ }
+ returntrue;
+};
+
+
Explain:
+
DFS and DP.
+
Complexity:
+
+
Time complexity : O(n ^ 2).
+
Space complexity : O(n).
+
\ No newline at end of file
diff --git a/docs/problem/longest-subarray-of-1s-after-deleting-one-element.html b/docs/problem/longest-subarray-of-1s-after-deleting-one-element.html
new file mode 100644
index 0000000..3d0b7b9
--- /dev/null
+++ b/docs/problem/longest-subarray-of-1s-after-deleting-one-element.html
@@ -0,0 +1,55 @@
+Longest Subarray of 1's After Deleting One Element - LeetCode javascript solutions
1493. Longest Subarray of 1's After Deleting One Element
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 thenumberin position 2, [1,1,1] contains3 numbers withvalueof1's.
+
+
Example 2:
+
Input: nums = [0,1,1,1,0,1,1,0,1]
+Output: 5
+Explanation: After deleting thenumberin position 4, [0,1,1,1,1,1,0,1] longest subarray withvalueof1'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
+
/**
+ * @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).
+
\ 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
new file mode 100644
index 0000000..c891009
--- /dev/null
+++ b/docs/problem/longest-substring-without-repeating-characters.html
@@ -0,0 +1,33 @@
+Longest Substring Without Repeating Characters - LeetCode javascript solutions
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?
\ No newline at end of file
diff --git a/docs/problem/majority-element-ii.html b/docs/problem/majority-element-ii.html
new file mode 100644
index 0000000..c6e76dc
--- /dev/null
+++ b/docs/problem/majority-element-ii.html
@@ -0,0 +1,67 @@
+Majority Element II - LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/problem/majority-element.html b/docs/problem/majority-element.html
new file mode 100644
index 0000000..89ef3eb
--- /dev/null
+++ b/docs/problem/majority-element.html
@@ -0,0 +1,66 @@
+Majority Element - LeetCode javascript solutions
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).
+
\ No newline at end of file
diff --git a/docs/problem/matrix-diagonal-sum.html b/docs/problem/matrix-diagonal-sum.html
new file mode 100644
index 0000000..1147bae
--- /dev/null
+++ b/docs/problem/matrix-diagonal-sum.html
@@ -0,0 +1,55 @@
+Matrix Diagonal Sum - LeetCode javascript solutions
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:
+
+
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.
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/max-dot-product-of-two-subsequences.html b/docs/problem/max-dot-product-of-two-subsequences.html
new file mode 100644
index 0000000..051071e
--- /dev/null
+++ b/docs/problem/max-dot-product-of-two-subsequences.html
@@ -0,0 +1,64 @@
+Max Dot Product of Two Subsequences - LeetCode javascript solutions
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
+
/**
+ * @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) returnNumber.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).
+
\ 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
new file mode 100644
index 0000000..40b9052
--- /dev/null
+++ b/docs/problem/max-points-on-a-line.html
@@ -0,0 +1,74 @@
+Max Points on a Line - LeetCode javascript solutions
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:
+
+
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:
+
+
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 donot 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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/maximal-rectangle.html b/docs/problem/maximal-rectangle.html
new file mode 100644
index 0000000..8082469
--- /dev/null
+++ b/docs/problem/maximal-rectangle.html
@@ -0,0 +1,62 @@
+Maximal Rectangle - LeetCode javascript solutions
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/maximize-the-confusion-of-an-exam.html b/docs/problem/maximize-the-confusion-of-an-exam.html
new file mode 100644
index 0000000..79bda39
--- /dev/null
+++ b/docs/problem/maximize-the-confusion-of-an-exam.html
@@ -0,0 +1,71 @@
+Maximize the Confusion of an Exam - LeetCode javascript solutions
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 mostktimes.
+
+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 replacethefirst'T'withan'F'to make answerKey = "FFFT".
+Alternatively, we can replacethesecond'T'withan'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 replacethefirst'F'to make answerKey = "TTTTTFTT"
+Alternatively, we can replacethesecond'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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/maximum-ascending-subarray-sum.html b/docs/problem/maximum-ascending-subarray-sum.html
new file mode 100644
index 0000000..fe5de7f
--- /dev/null
+++ b/docs/problem/maximum-ascending-subarray-sum.html
@@ -0,0 +1,52 @@
+Maximum Ascending Subarray Sum - LeetCode javascript solutions
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 theascending subarray withthe maximum sumof65.
+
+
Example 2:
+
Input: nums = [10,20,30,40,50]
+Output: 150
+Explanation: [10,20,30,40,50] is theascending subarray withthe maximum sumof150.
+
+
Example 3:
+
Input: nums = [12,17,15,13,10,11,12]
+Output: 33
+Explanation: [10,11,12] is theascending subarray withthe maximum sumof33.
+
\ No newline at end of file
diff --git a/docs/problem/maximum-binary-tree-ii.html b/docs/problem/maximum-binary-tree-ii.html
new file mode 100644
index 0000000..c2e6497
--- /dev/null
+++ b/docs/problem/maximum-binary-tree-ii.html
@@ -0,0 +1,77 @@
+Maximum Binary Tree II - LeetCode javascript solutions
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:
+
+
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:
+
+
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:
+
+
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
+
/**
+ * 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;
+ }
+ returnnew TreeNode(val, root);
+};
+
+
Explain:
+
nope.
+
Complexity:
+
+
Time complexity : O(n).
+
Space complexity : O(n).
+
\ No newline at end of file
diff --git a/docs/problem/maximum-binary-tree.html b/docs/problem/maximum-binary-tree.html
new file mode 100644
index 0000000..985fbd1
--- /dev/null
+++ b/docs/problem/maximum-binary-tree.html
@@ -0,0 +1,74 @@
+Maximum Binary Tree - LeetCode javascript solutions
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:
+
+
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.
+
\ 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
new file mode 100644
index 0000000..22cd921
--- /dev/null
+++ b/docs/problem/maximum-depth-of-binary-tree.html
@@ -0,0 +1,41 @@
+Maximum Depth of Binary Tree - LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/problem/maximum-difference-between-node-and-ancestor.html b/docs/problem/maximum-difference-between-node-and-ancestor.html
new file mode 100644
index 0000000..2613726
--- /dev/null
+++ b/docs/problem/maximum-difference-between-node-and-ancestor.html
@@ -0,0 +1,62 @@
+Maximum Difference Between Node and Ancestor - LeetCode javascript solutions
1026. Maximum Difference Between Node and Ancestor
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:
+
+
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:
+
+
Input: root = [1,null,2,null,0,3]
+Output:3
+
+
+Constraints:
+
+
The number of nodes in the tree is in the range [2, 5000].
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).
+
\ No newline at end of file
diff --git a/docs/problem/maximum-element-after-decreasing-and-rearranging.html b/docs/problem/maximum-element-after-decreasing-and-rearranging.html
new file mode 100644
index 0000000..ecb71d8
--- /dev/null
+++ b/docs/problem/maximum-element-after-decreasing-and-rearranging.html
@@ -0,0 +1,64 @@
+Maximum Element After Decreasing and Rearranging - LeetCode javascript solutions
1846. Maximum Element After Decreasing and Rearranging
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 elementin 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 thevalueofthesecondelementto2.
+3. Decrease thevalueofthethirdelementto3.
+Now arr = [1,2,3], which satisfies the conditions.
+The largest elementin 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.
+
\ No newline at end of file
diff --git a/docs/problem/maximum-gap.html b/docs/problem/maximum-gap.html
new file mode 100644
index 0000000..00fd984
--- /dev/null
+++ b/docs/problem/maximum-gap.html
@@ -0,0 +1,62 @@
+Maximum Gap - LeetCode javascript solutions
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) return0;
+
+ var max = Math.max(...nums);
+ var min = Math.min(...nums);
+ if (max === min) return0;
+
+ 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).
+
\ No newline at end of file
diff --git a/docs/problem/maximum-length-of-a-concatenated-string-with-unique-characters.html b/docs/problem/maximum-length-of-a-concatenated-string-with-unique-characters.html
new file mode 100644
index 0000000..8c30564
--- /dev/null
+++ b/docs/problem/maximum-length-of-a-concatenated-string-with-unique-characters.html
@@ -0,0 +1,74 @@
+Maximum Length of a Concatenated String with Unique Characters - LeetCode javascript solutions
1239. Maximum Length of a Concatenated String with Unique Characters
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 onlystring in arr hasall26 characters.
+
+
+Constraints:
+
+
1 <= arr.length <= 16
+
1 <= arr[i].length <= 26
+
arr[i] contains only lowercase English letters.
+
+
Solution
+
/**
+ * @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) return0;
+ 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).
+
\ No newline at end of file
diff --git a/docs/problem/maximum-length-of-pair-chain.html b/docs/problem/maximum-length-of-pair-chain.html
new file mode 100644
index 0000000..1f34737
--- /dev/null
+++ b/docs/problem/maximum-length-of-pair-chain.html
@@ -0,0 +1,74 @@
+Maximum Length of Pair Chain - LeetCode javascript solutions
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/maximum-number-of-achievable-transfer-requests.html b/docs/problem/maximum-number-of-achievable-transfer-requests.html
new file mode 100644
index 0000000..cd65140
--- /dev/null
+++ b/docs/problem/maximum-number-of-achievable-transfer-requests.html
@@ -0,0 +1,76 @@
+Maximum Number of Achievable Transfer Requests - LeetCode javascript solutions
1601. Maximum Number of Achievable Transfer Requests
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:
+
+
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 2and0 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:
+
+
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
+
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).
+
\ No newline at end of file
diff --git a/docs/problem/maximum-number-of-coins-you-can-get.html b/docs/problem/maximum-number-of-coins-you-can-get.html
new file mode 100644
index 0000000..6dbb345
--- /dev/null
+++ b/docs/problem/maximum-number-of-coins-you-can-get.html
@@ -0,0 +1,56 @@
+Maximum Number of Coins You Can Get - LeetCode javascript solutions
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 with8 coins, you the pile with7 coins and Bob thelastone.
+Choose the triplet (1, 2, 4), Alice Pick the pile with4 coins, you the pile with2 coins and Bob thelastone.
+The maximum numberof 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 get2 + 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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/maximum-number-of-events-that-can-be-attended-ii.html b/docs/problem/maximum-number-of-events-that-can-be-attended-ii.html
new file mode 100644
index 0000000..ee7a736
--- /dev/null
+++ b/docs/problem/maximum-number-of-events-that-can-be-attended-ii.html
@@ -0,0 +1,112 @@
+Maximum Number of Events That Can Be Attended II - LeetCode javascript solutions
1751. Maximum Number of Events That Can Be Attended II
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:
+
+
Input: events = [[1,2,4],[3,4,3],[2,3,1]], k = 2
+Output: 7
+Explanation: Choose the green events, 0and1 (0-indexed) for a total value of 4 + 3 = 7.
+
+
Example 2:
+
+
Input: events = [[1,2,4],[3,4,3],[2,3,10]], k = 2
+Output: 10
+Explanation: Choose event 2fora total valueof10.
+Notice that you cannot attend any other event as they overlap, and that you donot have to attend k events.
+
+
Example 3:
+
+
Input: events = [[1,1,1],[2,2,2],[3,3,3],[4,4,4]], k = 3
+Output: 9
+Explanation: Although the events donot 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
+
/**
+ * @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) return0;
+ 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
+
/**
+ * @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) return0;
+ 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).
+
\ No newline at end of file
diff --git a/docs/problem/maximum-number-of-groups-with-increasing-length.html b/docs/problem/maximum-number-of-groups-with-increasing-length.html
new file mode 100644
index 0000000..ab63906
--- /dev/null
+++ b/docs/problem/maximum-number-of-groups-with-increasing-length.html
@@ -0,0 +1,72 @@
+Maximum Number of Groups With Increasing Length - LeetCode javascript solutions
2790. Maximum Number of Groups With Increasing Length
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 useboth0and1at most once.
+One way of creating the maximum numberofgroupswhile satisfying the conditions is:
+Group1 contains the number [0].
+It can be shown that the maximum numberofgroupsis1.
+So, the outputis1.
+
+
+Constraints:
+
+
1 <= usageLimits.length <= 105
+
1 <= usageLimits[i] <= 109
+
+
Solution
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/maximum-number-of-jumps-to-reach-the-last-index.html b/docs/problem/maximum-number-of-jumps-to-reach-the-last-index.html
new file mode 100644
index 0000000..8c87ec4
--- /dev/null
+++ b/docs/problem/maximum-number-of-jumps-to-reach-the-last-index.html
@@ -0,0 +1,68 @@
+Maximum Number of Jumps to Reach the Last Index - LeetCode javascript solutions
2770. Maximum Number of Jumps to Reach the Last Index
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 fromindex0toindex n - 1with the maximum number of jumps, you can perform the following jumping sequence:
+- Jump fromindex0toindex1.
+- Jump fromindex1toindex3.
+- Jump fromindex3toindex5.
+It can be proven that there is no other jumping sequence that goes from0to n - 1with more than 3 jumps. Hence, the answer is3.
+
+
Example 2:
+
Input: nums = [1,3,6,4,1,2], target = 3
+Output: 5
+Explanation: To go fromindex0toindex n - 1with the maximum number of jumps, you can perform the following jumping sequence:
+- Jump fromindex0toindex1.
+- Jump fromindex1toindex2.
+- Jump fromindex2toindex3.
+- Jump fromindex3toindex4.
+- Jump fromindex4toindex5.
+It can be proven that there is no other jumping sequence that goes from0to n - 1with more than 5 jumps. Hence, the answer is5.
+
+
Example 3:
+
Input: nums = [1,3,6,4,1,2], target = 0
+Output: -1
+Explanation: It can be proven that there isno jumping sequence that goes from0to n - 1. Hence, the answer is -1.
+
\ No newline at end of file
diff --git a/docs/problem/maximum-number-of-vowels-in-a-substring-of-given-length.html b/docs/problem/maximum-number-of-vowels-in-a-substring-of-given-length.html
new file mode 100644
index 0000000..f97a607
--- /dev/null
+++ b/docs/problem/maximum-number-of-vowels-in-a-substring-of-given-length.html
@@ -0,0 +1,60 @@
+Maximum Number of Vowels in a Substring of Given Length - LeetCode javascript solutions
1456. Maximum Number of Vowels in a Substring of Given Length
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 oflength2contains2 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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/maximum-odd-binary-number.html b/docs/problem/maximum-odd-binary-number.html
new file mode 100644
index 0000000..718d8c2
--- /dev/null
+++ b/docs/problem/maximum-odd-binary-number.html
@@ -0,0 +1,40 @@
+Maximum Odd Binary Number - LeetCode javascript solutions
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 inthelast position. So the answer is "001".
+
+
Example 2:
+
Input: s = "0101"
+Output: "1001"
+Explanation: One ofthe'1's must be inthelast position. The maximum number that can be made withthe remaining digits is "100". So the answer is "1001".
+
\ No newline at end of file
diff --git a/docs/problem/maximum-product-difference-between-two-pairs.html b/docs/problem/maximum-product-difference-between-two-pairs.html
new file mode 100644
index 0000000..7dc24f3
--- /dev/null
+++ b/docs/problem/maximum-product-difference-between-two-pairs.html
@@ -0,0 +1,61 @@
+Maximum Product Difference Between Two Pairs - LeetCode javascript solutions
1913. Maximum Product Difference Between Two Pairs
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 indices1and3for the first pair (6, 7) andindices2and4for 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 indices3and6for the first pair (9, 8) andindices1and5for the second pair (2, 4).
+The product difference is (9 * 8) - (2 * 4) = 64.
+
\ No newline at end of file
diff --git a/docs/problem/maximum-product-of-two-elements-in-an-array.html b/docs/problem/maximum-product-of-two-elements-in-an-array.html
new file mode 100644
index 0000000..456294d
--- /dev/null
+++ b/docs/problem/maximum-product-of-two-elements-in-an-array.html
@@ -0,0 +1,63 @@
+Maximum Product of Two Elements in an Array - LeetCode javascript solutions
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 andj=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 andj=3 (indexed from 0), you will get the maximum value of (5-1)*(5-1) = 16.
+
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) return0;
+ 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).
+
\ No newline at end of file
diff --git a/docs/problem/maximum-profit-in-job-scheduling.html b/docs/problem/maximum-profit-in-job-scheduling.html
new file mode 100644
index 0000000..ceb1ef0
--- /dev/null
+++ b/docs/problem/maximum-profit-in-job-scheduling.html
@@ -0,0 +1,82 @@
+Maximum Profit in Job Scheduling - LeetCode javascript solutions
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:
+
+
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.
+
/**
+ * @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) return0;
+ 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).
+
\ No newline at end of file
diff --git a/docs/problem/maximum-score-after-splitting-a-string.html b/docs/problem/maximum-score-after-splitting-a-string.html
new file mode 100644
index 0000000..1aa24a1
--- /dev/null
+++ b/docs/problem/maximum-score-after-splitting-a-string.html
@@ -0,0 +1,57 @@
+Maximum Score After Splitting a String - LeetCode javascript solutions
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.
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) return0;
+
+ 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).
+
\ No newline at end of file
diff --git a/docs/problem/maximum-sum-of-distinct-subarrays-with-length-k.html b/docs/problem/maximum-sum-of-distinct-subarrays-with-length-k.html
new file mode 100644
index 0000000..ee4c9ca
--- /dev/null
+++ b/docs/problem/maximum-sum-of-distinct-subarrays-with-length-k.html
@@ -0,0 +1,78 @@
+Maximum Sum of Distinct Subarrays With Length K - LeetCode javascript solutions
2461. Maximum Sum of Distinct Subarrays With Length K
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 withlength3 are:
+- [1,5,4] which meets the requirements and has asumof10.
+- [5,4,2] which meets the requirements and has asumof11.
+- [4,2,9] which meets the requirements and has asumof15.
+- [2,9,9] which does not meet the requirements because theelement9 is repeated.
+- [9,9,9] which does not meet the requirements because theelement9 is repeated.
+We return15 because it is the maximum subarray sumof all the subarrays that meet the conditions
+
+
Example 2:
+
Input: nums = [4,4,4], k = 3
+Output: 0
+Explanation: The subarrays of nums withlength3 are:
+- [4,4,4] which does not meet the requirements because theelement4 is repeated.
+We return0 because no subarrays meet the conditions.
+
+
+Constraints:
+
+
1 <= k <= nums.length <= 105
+
1 <= nums[i] <= 105
+
+
Solution
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/maximum-twin-sum-of-a-linked-list.html b/docs/problem/maximum-twin-sum-of-a-linked-list.html
new file mode 100644
index 0000000..80723e8
--- /dev/null
+++ b/docs/problem/maximum-twin-sum-of-a-linked-list.html
@@ -0,0 +1,83 @@
+Maximum Twin Sum of a Linked List - LeetCode javascript solutions
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:
+
+
Input: head = [5,4,2,1]
+Output: 6
+Explanation:
+Nodes 0and1 are the twins of nodes 3and2, respectively. All have twin sum = 6.
+There are no other nodes with twins inthe linked list.
+Thus, the maximum twin sumofthe linked list is 6.
+
+
Example 2:
+
+
Input: head = [4,2,2,3]
+Output: 7
+Explanation:
+The nodes with twins present in this linked list are:
+- Node0 is the twin of node3 having a twin sum of 4 + 3 = 7.
+- Node1 is the twin of node2 having a twin sum of 2 + 2 = 4.
+Thus, the maximum twin sum of the linked list is max(7, 4) = 7.
+
+
Example 3:
+
+
Input: head = [1,100000]
+Output: 100001
+Explanation:
+There is only one node witha twin inthe linked list having twin sumof1 + 100000 = 100001.
+
+
+Constraints:
+
+
The number of nodes in the list is an even integer in the range [2, 105].
+
1 <= Node.val <= 105
+
+
Solution
+
/**
+ * 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).
+
\ 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
new file mode 100644
index 0000000..b64ca22
--- /dev/null
+++ b/docs/problem/median-of-two-sorted-arrays.html
@@ -0,0 +1,76 @@
+Median of Two Sorted Arrays - LeetCode javascript solutions
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) returnfalse;
+ if (b.start <= a.end && a.end <= b.end) returntrue;
+ if (a.start <= b.end && b.end <= a.end) returntrue;
+ returnfalse;
+};
+
+
Explain:
+
先排序,后操作。也可以边操作边排序。
+
Complexity:
+
+
Time complexity : O(nlog(n)).
+
Space complexity : O(n).
+
\ No newline at end of file
diff --git a/docs/problem/merge-k-sorted-lists.html b/docs/problem/merge-k-sorted-lists.html
new file mode 100644
index 0000000..7679a49
--- /dev/null
+++ b/docs/problem/merge-k-sorted-lists.html
@@ -0,0 +1,197 @@
+Merge k Sorted Lists - LeetCode javascript solutions
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).
+
\ No newline at end of file
diff --git a/docs/problem/merge-two-binary-trees.html b/docs/problem/merge-two-binary-trees.html
new file mode 100644
index 0000000..176f572
--- /dev/null
+++ b/docs/problem/merge-two-binary-trees.html
@@ -0,0 +1,50 @@
+Merge Two Binary Trees - LeetCode javascript solutions
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.
\ No newline at end of file
diff --git a/docs/problem/merge-two-sorted-lists.html b/docs/problem/merge-two-sorted-lists.html
new file mode 100644
index 0000000..bab28c4
--- /dev/null
+++ b/docs/problem/merge-two-sorted-lists.html
@@ -0,0 +1,44 @@
+Merge Two Sorted Lists - LeetCode javascript solutions
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 startatindex1.
+- Pay 15and climb two steps to reach the top.
+The total costis15.
+
+
Example 2:
+
Input: cost = [1,100,1,1,1,100,1,1,100,1]
+Output: 6
+Explanation: You will startatindex0.
+- Pay 1and climb two steps to reach index2.
+- Pay 1and climb two steps to reach index4.
+- Pay 1and climb two steps to reach index6.
+- Pay 1and climb one step to reach index7.
+- Pay 1and climb two steps to reach index9.
+- Pay 1and climb one step to reach the top.
+The total costis6.
+
\ No newline at end of file
diff --git a/docs/problem/min-cost-to-connect-all-points.html b/docs/problem/min-cost-to-connect-all-points.html
new file mode 100644
index 0000000..4b84aba
--- /dev/null
+++ b/docs/problem/min-cost-to-connect-all-points.html
@@ -0,0 +1,82 @@
+Min Cost to Connect All Points - LeetCode javascript solutions
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:
+
+
Input: points = [[0,0],[2,2],[3,10],[5,2],[7,0]]
+Output: 20
+Explanation:
+
+We can connect the points as shown abovetogetthe minimum cost of20.
+Notice that there is a unique path betweenevery pair of points.
+
\ No newline at end of file
diff --git a/docs/problem/minimize-maximum-pair-sum-in-array.html b/docs/problem/minimize-maximum-pair-sum-in-array.html
new file mode 100644
index 0000000..ef60e63
--- /dev/null
+++ b/docs/problem/minimize-maximum-pair-sum-in-array.html
@@ -0,0 +1,53 @@
+Minimize Maximum Pair Sum in Array - LeetCode javascript solutions
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 ismax(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 ismax(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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/minimize-the-maximum-difference-of-pairs.html b/docs/problem/minimize-the-maximum-difference-of-pairs.html
new file mode 100644
index 0000000..79ffffb
--- /dev/null
+++ b/docs/problem/minimize-the-maximum-difference-of-pairs.html
@@ -0,0 +1,62 @@
+Minimize the Maximum Difference of Pairs - LeetCode javascript solutions
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 absolutevalue 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 fromthe indices 1and4, andthesecond pair is formed fromthe indices 2and5.
+The maximum difference is max(|nums[1] - nums[4]|, |nums[2] - nums[5]|) = max(0, 1) = 1. Therefore, we return1.
+
+
Example 2:
+
Input: nums = [4,2,1,2], p = 1
+Output: 0
+Explanation: Let the indices 1and3 form a pair. The difference ofthat pair is |2 - 2| = 0, which isthe minimum we can attain.
+
+
+Constraints:
+
+
1 <= nums.length <= 105
+
0 <= nums[i] <= 109
+
0 <= p <= (nums.length)/2
+
+
Solution
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/minimum-amount-of-time-to-collect-garbage.html b/docs/problem/minimum-amount-of-time-to-collect-garbage.html
new file mode 100644
index 0000000..ef7fb34
--- /dev/null
+++ b/docs/problem/minimum-amount-of-time-to-collect-garbage.html
@@ -0,0 +1,99 @@
+Minimum Amount of Time to Collect Garbage - LeetCode javascript solutions
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 0to house 1
+2. Collects the paper garbage at house 1
+3. Travels from house 1to 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 0to house 1
+3. Travels from house 1to house 2
+4. Collects the glass garbage at house 2
+5. Travels from house 2to 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 donot need to consider the metal garbage truck.
+Therefore, it takes a total of8 + 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 upall the metal garbage.
+The paper garbage truck takes 15 minutes to pick upall the paper garbage.
+The glass garbage truck takes 15 minutes to pick upall 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
+
/**
+ * @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++;
+ } elseif (str[i] === 'P') {
+ res.p++;
+ } else {
+ res.g++;
+ }
+ }
+ return res;
+};
+
+
Explain:
+
nope.
+
Complexity:
+
+
Time complexity : O(n * m).
+
Space complexity : O(1).
+
\ No newline at end of file
diff --git a/docs/problem/minimum-ascii-delete-sum-for-two-strings.html b/docs/problem/minimum-ascii-delete-sum-for-two-strings.html
new file mode 100644
index 0000000..9d3d101
--- /dev/null
+++ b/docs/problem/minimum-ascii-delete-sum-for-two-strings.html
@@ -0,0 +1,57 @@
+Minimum ASCII Delete Sum for Two Strings - LeetCode javascript solutions
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).
+
\ No newline at end of file
diff --git a/docs/problem/minimum-degree-of-a-connected-trio-in-a-graph.html b/docs/problem/minimum-degree-of-a-connected-trio-in-a-graph.html
new file mode 100644
index 0000000..2a7e434
--- /dev/null
+++ b/docs/problem/minimum-degree-of-a-connected-trio-in-a-graph.html
@@ -0,0 +1,80 @@
+Minimum Degree of a Connected Trio in a Graph - LeetCode javascript solutions
1761. Minimum Degree of a Connected Trio in a Graph
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** -1if the graph has no connected trios.
+
+Example 1:
+
+
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:
+
+
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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/minimum-deletions-to-make-character-frequencies-unique.html b/docs/problem/minimum-deletions-to-make-character-frequencies-unique.html
new file mode 100644
index 0000000..b4278a6
--- /dev/null
+++ b/docs/problem/minimum-deletions-to-make-character-frequencies-unique.html
@@ -0,0 +1,65 @@
+Minimum Deletions to Make Character Frequencies Unique - LeetCode javascript solutions
1647. Minimum Deletions to Make Character Frequencies Unique
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 sgood.**
+
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 deletetwo'b's resulting inthe good string"aaabcc".
+Another way ittodeleteone'b'andone'c' resulting inthe good string"aaabbc".
+
+
Example 3:
+
Input: s = "ceabaacb"
+Output: 2
+Explanation: You can deleteboth'c's resulting in the good string"eabaab".
+Note that we only care about characters that are still in the stringat the end (i.e. frequency of0is ignored).
+
+
+Constraints:
+
+
1 <= s.length <= 105
+
s contains only lowercase English letters.
+
+
Solution
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/minimum-deletions-to-make-string-balanced.html b/docs/problem/minimum-deletions-to-make-string-balanced.html
new file mode 100644
index 0000000..afad503
--- /dev/null
+++ b/docs/problem/minimum-deletions-to-make-string-balanced.html
@@ -0,0 +1,58 @@
+Minimum Deletions to Make String Balanced - LeetCode javascript solutions
You are given a string s consisting only of characters 'a' and 'b'.
+
You can delete any number of characters in s to make sbalanced. 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 sbalanced**.
+
+Example 1:
+
Input: s = "aababbab"
+Output: 2
+Explanation: You can either:
+Delete thecharactersat0-indexed positions 2and6 ("aababbab" -> "aaabbb"), or
+Delete thecharactersat0-indexed positions 3and6 ("aababbab" -> "aabbbb").
+
+
Example 2:
+
Input: s = "bbaaaaabb"
+Output:2
+Explanation: The only solution istodelete the first two characters.
+
\ 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
new file mode 100644
index 0000000..bee8dd7
--- /dev/null
+++ b/docs/problem/minimum-depth-of-binary-tree.html
@@ -0,0 +1,76 @@
+Minimum Depth of Binary Tree - LeetCode javascript solutions
/**
+ * 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) return0;
+
+ 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).
+
\ No newline at end of file
diff --git a/docs/problem/minimum-difficulty-of-a-job-schedule.html b/docs/problem/minimum-difficulty-of-a-job-schedule.html
new file mode 100644
index 0000000..103a416
--- /dev/null
+++ b/docs/problem/minimum-difficulty-of-a-job-schedule.html
@@ -0,0 +1,64 @@
+Minimum Difficulty of a Job Schedule - LeetCode javascript solutions
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:
+
+
Input:jobDifficulty = [6,5,4,3,2,1], d = 2
+Output:7
+Explanation: First day you can finish the first 5jobs, 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
+
/**
+ * @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) return0;
+ if (d === 0) returnNumber.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).
+
\ No newline at end of file
diff --git a/docs/problem/minimum-falling-path-sum-ii.html b/docs/problem/minimum-falling-path-sum-ii.html
new file mode 100644
index 0000000..e3fcf9a
--- /dev/null
+++ b/docs/problem/minimum-falling-path-sum-ii.html
@@ -0,0 +1,62 @@
+Minimum Falling Path Sum II - LeetCode javascript solutions
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:
+
+
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.
+
\ No newline at end of file
diff --git a/docs/problem/minimum-falling-path-sum.html b/docs/problem/minimum-falling-path-sum.html
new file mode 100644
index 0000000..f67d4e9
--- /dev/null
+++ b/docs/problem/minimum-falling-path-sum.html
@@ -0,0 +1,48 @@
+Minimum Falling Path Sum - LeetCode javascript solutions
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:
+
+
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:
+
+
Input: matrix = [[-19,57],[-40,-5]]
+Output: -59
+Explanation: The falling path with a minimum sum is shown.
+
\ No newline at end of file
diff --git a/docs/problem/minimum-flips-to-make-a-or-b-equal-to-c.html b/docs/problem/minimum-flips-to-make-a-or-b-equal-to-c.html
new file mode 100644
index 0000000..9df5915
--- /dev/null
+++ b/docs/problem/minimum-flips-to-make-a-or-b-equal-to-c.html
@@ -0,0 +1,53 @@
+Minimum Flips to Make a OR b Equal to c - LeetCode javascript solutions
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:
+
+
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
+
/**
+ * @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;
+ } elseif (!(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).
+
\ No newline at end of file
diff --git a/docs/problem/minimum-interval-to-include-each-query.html b/docs/problem/minimum-interval-to-include-each-query.html
new file mode 100644
index 0000000..9ecf5ed
--- /dev/null
+++ b/docs/problem/minimum-interval-to-include-each-query.html
@@ -0,0 +1,59 @@
+Minimum Interval to Include Each Query - LeetCode javascript solutions
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 intervali 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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/minimum-length-of-string-after-deleting-similar-ends.html b/docs/problem/minimum-length-of-string-after-deleting-similar-ends.html
new file mode 100644
index 0000000..286f62c
--- /dev/null
+++ b/docs/problem/minimum-length-of-string-after-deleting-similar-ends.html
@@ -0,0 +1,62 @@
+Minimum Length of String After Deleting Similar Ends - LeetCode javascript solutions
1750. Minimum Length of String After Deleting Similar Ends
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 thestring stays asis.
+
+
Example 2:
+
Input: s = "cabaabac"
+Output: 0
+Explanation: An optimal sequence of operations is:
+- Take prefix = "c"and suffix = "c"andremove them, s = "abaaba".
+- Take prefix = "a"and suffix = "a"andremove them, s = "baab".
+- Take prefix = "b"and suffix = "b"andremove them, s = "aa".
+- Take prefix = "a"and suffix = "a"andremove them, s = "".
+
+
Example 3:
+
Input: s = "aabccabba"
+Output: 3
+Explanation: An optimal sequence of operations is:
+- Take prefix = "aa"and suffix = "a"andremove them, s = "bccabb".
+- Take prefix = "b"and suffix = "bb"andremove them, s = "cca".
+
+
+Constraints:
+
+
1 <= s.length <= 105
+
s only consists of characters 'a', 'b', and 'c'.
+
+
Solution
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/minimum-number-of-operations-to-make-array-continuous.html b/docs/problem/minimum-number-of-operations-to-make-array-continuous.html
new file mode 100644
index 0000000..4e70ced
--- /dev/null
+++ b/docs/problem/minimum-number-of-operations-to-make-array-continuous.html
@@ -0,0 +1,66 @@
+Minimum Number of Operations to Make Array Continuous - LeetCode javascript solutions
2009. Minimum Number of Operations to Make Array Continuous
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 secondelementto2.
+- Change the third elementto3.
+- Change the fourth elementto4.
+The resulting arrayis [1,2,3,4], which is continuous.
+
+
+Constraints:
+
+
1 <= nums.length <= 105
+
1 <= nums[i] <= 109
+
+
Solution
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/minimum-number-of-operations-to-make-array-empty.html b/docs/problem/minimum-number-of-operations-to-make-array-empty.html
new file mode 100644
index 0000000..61f6c10
--- /dev/null
+++ b/docs/problem/minimum-number-of-operations-to-make-array-empty.html
@@ -0,0 +1,59 @@
+Minimum Number of Operations to Make Array Empty - LeetCode javascript solutions
2870. Minimum Number of Operations to Make Array Empty
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 toempty the array.
+
+
+Constraints:
+
+
2 <= nums.length <= 105
+
1 <= nums[i] <= 106
+
+
Solution
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/minimum-number-of-steps-to-make-two-strings-anagram.html b/docs/problem/minimum-number-of-steps-to-make-two-strings-anagram.html
new file mode 100644
index 0000000..b2824f6
--- /dev/null
+++ b/docs/problem/minimum-number-of-steps-to-make-two-strings-anagram.html
@@ -0,0 +1,56 @@
+Minimum Number of Steps to Make Two Strings Anagram - LeetCode javascript solutions
1347. Minimum Number of Steps to Make Two Strings Anagram
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 thefirst'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 charactersto 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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/minimum-number-of-vertices-to-reach-all-nodes.html b/docs/problem/minimum-number-of-vertices-to-reach-all-nodes.html
new file mode 100644
index 0000000..4885aa6
--- /dev/null
+++ b/docs/problem/minimum-number-of-vertices-to-reach-all-nodes.html
@@ -0,0 +1,53 @@
+Minimum Number of Vertices to Reach All Nodes - LeetCode javascript solutions
1557. Minimum Number of Vertices to Reach All Nodes
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:
+
+
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:
+
+
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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/minimum-operations-to-make-a-special-number.html b/docs/problem/minimum-operations-to-make-a-special-number.html
new file mode 100644
index 0000000..29e2057
--- /dev/null
+++ b/docs/problem/minimum-operations-to-make-a-special-number.html
@@ -0,0 +1,65 @@
+Minimum Operations to Make a Special Number - LeetCode javascript solutions
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** numspecial.
+
An integer x is considered special if it is divisible by 25.
+
+Example 1:
+
Input: num = "2245047"
+Output: 2
+Explanation: Delete digits num[5] andnum[6]. The resulting numberis"22450" which is special since it is divisible by25.
+It can be shown that 2is the minimumnumberofoperationsrequiredtoget a special number.
+
+
Example 2:
+
Input: num = "2908305"
+Output: 3
+Explanation: Delete digits num[3], num[4], andnum[6]. The resulting numberis"2900" which is special since it is divisible by25.
+It can be shown that 3is the minimumnumberofoperationsrequiredtoget a special number.
+
+
Example 3:
+
Input: num = "10"
+Output: 1
+Explanation: Delete digit num[0]. The resulting numberis"0" which is special sinceitis divisible by25.
+It can be shown that1isthe minimum numberof operations required toget a special number.
+
+
+
+Constraints:
+
+
1 <= num.length <= 100
+
num only consists of digits '0' through '9'.
+
num does not contain any leading zeros.
+
+
Solution
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/minimum-operations-to-reduce-x-to-zero.html b/docs/problem/minimum-operations-to-reduce-x-to-zero.html
new file mode 100644
index 0000000..2d18d9d
--- /dev/null
+++ b/docs/problem/minimum-operations-to-reduce-x-to-zero.html
@@ -0,0 +1,59 @@
+Minimum Operations to Reduce X to Zero - LeetCode javascript solutions
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 *exactly0 *if it is possible, otherwise, return **-1.
+
+Example 1:
+
Input: nums = [1,1,4,2,3], x = 5
+Output:2
+Explanation: The optimal solution istoremove the last two elements to reduce xto 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 thelastthree elements andthefirsttwo elements (5 operations in total) to reduce x tozero.
+
+
+Constraints:
+
+
1 <= nums.length <= 105
+
1 <= nums[i] <= 104
+
1 <= x <= 109
+
+
Solution
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/minimum-path-sum.html b/docs/problem/minimum-path-sum.html
new file mode 100644
index 0000000..05552da
--- /dev/null
+++ b/docs/problem/minimum-path-sum.html
@@ -0,0 +1,47 @@
+Minimum Path Sum - LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/problem/minimum-rounds-to-complete-all-tasks.html b/docs/problem/minimum-rounds-to-complete-all-tasks.html
new file mode 100644
index 0000000..538856e
--- /dev/null
+++ b/docs/problem/minimum-rounds-to-complete-all-tasks.html
@@ -0,0 +1,52 @@
+Minimum Rounds to Complete All Tasks - LeetCode javascript solutions
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 thefirstround, you complete 3 tasks of difficulty level 2.
+- In thesecondround, you complete 2 tasks of difficulty level 3.
+- In thethirdround, you complete 3 tasks of difficulty level 4.
+- In thefourthround, 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 isonly1 task of difficulty level 2, but in each round, you can onlycomplete either 2or3 tasks of the same difficulty level. Hence, you cannot completeall the tasks, and the answer is -1.
+
+
+Constraints:
+
+
1 <= tasks.length <= 105
+
1 <= tasks[i] <= 109
+
+
Solution
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/minimum-sideway-jumps.html b/docs/problem/minimum-sideway-jumps.html
new file mode 100644
index 0000000..ae1fcbd
--- /dev/null
+++ b/docs/problem/minimum-sideway-jumps.html
@@ -0,0 +1,70 @@
+Minimum Sideway Jumps - LeetCode javascript solutions
There is a 3 lane road of length n that consists of n + 1points 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:
+
+
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).
+
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
+
/**
+ * @param {number[]} obstacles
+ * @return {number}
+ */
+var minSideJumps = function(obstacles) {
+ return helper(obstacles, 0, 2);
+};
+
+var helper = function(obstacles, i, lane) {
+ if (i === obstacles.length) return0;
+ 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) return1;
+ return1 + helper(obstacles, nextIndex, 6 - lane - obstacles[nextIndex]);
+};
+
+
Explain:
+
Greedy.
+
Complexity:
+
+
Time complexity : O(n).
+
Space complexity : O(1).
+
\ No newline at end of file
diff --git a/docs/problem/minimum-size-subarray-sum.html b/docs/problem/minimum-size-subarray-sum.html
new file mode 100644
index 0000000..23d17d5
--- /dev/null
+++ b/docs/problem/minimum-size-subarray-sum.html
@@ -0,0 +1,56 @@
+Minimum Size Subarray Sum - LeetCode javascript solutions
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.
+
+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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/minimum-speed-to-arrive-on-time.html b/docs/problem/minimum-speed-to-arrive-on-time.html
new file mode 100644
index 0000000..fe77344
--- /dev/null
+++ b/docs/problem/minimum-speed-to-arrive-on-time.html
@@ -0,0 +1,81 @@
+Minimum Speed to Arrive on Time - LeetCode javascript solutions
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 ataninteger hour, we depart immediately atthe1 hour mark. The second train takes 3/1 = 3 hours.
+- Since we are already ataninteger hour, we depart immediately atthe4 hour mark. The third train takes 2/1 = 2 hours.
+- You will arrive at exactly the6 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 notataninteger hour, we waituntilthe1 hour mark to depart. The second train ride takes 3/3 = 1 hour.
+- Since we are already ataninteger hour, we depart immediately atthe2 hour mark. The third train takes 2/3 = 0.66667 hours.
+- You will arrive atthe2.66667 hour mark.
+
+
Example 3:
+
Input: dist = [1,3,2], hour = 1.9
+Output: -1
+Explanation: It is impossible because the earliest thethird train can depart is atthe2 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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/minimum-time-to-collect-all-apples-in-a-tree.html b/docs/problem/minimum-time-to-collect-all-apples-in-a-tree.html
new file mode 100644
index 0000000..232d64c
--- /dev/null
+++ b/docs/problem/minimum-time-to-collect-all-apples-in-a-tree.html
@@ -0,0 +1,67 @@
+Minimum Time to Collect All Apples in a Tree - LeetCode javascript solutions
1443. Minimum Time to Collect All Apples in a Tree
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:
+
+
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:
+
+
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.
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/minimum-time-to-make-rope-colorful.html b/docs/problem/minimum-time-to-make-rope-colorful.html
new file mode 100644
index 0000000..1ed6755
--- /dev/null
+++ b/docs/problem/minimum-time-to-make-rope-colorful.html
@@ -0,0 +1,67 @@
+Minimum Time to Make Rope Colorful - LeetCode javascript solutions
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:
+
+
Input: colors = "abaac", neededTime = [1,2,3,4,5]
+Output:3
+Explanation: In the above image, 'a'is blue, 'b'isred, and'c'is green.
+Bob can remove the blue balloon at index2. This takes 3 seconds.
+There are no longer two consecutive balloons of the same color. Total time = 3.
+
+
Example 2:
+
+
Input: colors = "abc", neededTime = [1,2,3]
+Output: 0
+Explanation: The rope is already colorful. Bob doesnot need to remove any balloons fromthe rope.
+
+
Example 3:
+
+
Input: colors = "aabaa", neededTime = [1,2,3,4,1]
+Output: 2
+Explanation: Bob will remove the ballons at indices 0and4. Each ballon takes 1secondto remove.
+There are no longer two consecutive balloons ofthe 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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/minimum-time-visiting-all-points.html b/docs/problem/minimum-time-visiting-all-points.html
new file mode 100644
index 0000000..3161e91
--- /dev/null
+++ b/docs/problem/minimum-time-visiting-all-points.html
@@ -0,0 +1,57 @@
+Minimum Time Visiting All Points - LeetCode javascript solutions
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:
+
+
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
+
\ No newline at end of file
diff --git a/docs/problem/minimum-xor-sum-of-two-arrays.html b/docs/problem/minimum-xor-sum-of-two-arrays.html
new file mode 100644
index 0000000..175bae0
--- /dev/null
+++ b/docs/problem/minimum-xor-sum-of-two-arrays.html
@@ -0,0 +1,60 @@
+Minimum XOR Sum of Two Arrays - LeetCode javascript solutions
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 (1XOR3) + (2XOR2) = 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 (1XOR5) + (0XOR4) + (3XOR3) = 4 + 4 + 0 = 8.
+
+
+Constraints:
+
+
n == nums1.length
+
n == nums2.length
+
1 <= n <= 14
+
0 <= nums1[i], nums2[i] <= 107
+
+
Solution
+
/**
+ * @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) return0;
+ 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).
+
\ No newline at end of file
diff --git a/docs/problem/missing-number.html b/docs/problem/missing-number.html
new file mode 100644
index 0000000..b02b7ee
--- /dev/null
+++ b/docs/problem/missing-number.html
@@ -0,0 +1,45 @@
+Missing Number - LeetCode javascript solutions
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 = 3since there are 3 numbers, so all numbers are inthe range [0,3]. 2isthe missing numberinthe range sinceitdoesnot appear in nums.
+
+
Example 2:
+
Input: nums = [0,1]
+Output: 2
+Explanation: n = 2since there are 2 numbers, so all numbers are inthe range [0,2]. 2isthe missing numberinthe range sinceitdoesnot appear in nums.
+
+
Example 3:
+
Input: nums = [9,6,4,2,3,5,7,0,1]
+Output: 8
+Explanation: n = 9since there are 9 numbers, so all numbers are inthe range [0,9]. 8isthe missing numberinthe range sinceitdoesnot 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?
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**.
\ No newline at end of file
diff --git a/docs/problem/most-visited-sector-in-a-circular-track.html b/docs/problem/most-visited-sector-in-a-circular-track.html
new file mode 100644
index 0000000..d0785ab
--- /dev/null
+++ b/docs/problem/most-visited-sector-in-a-circular-track.html
@@ -0,0 +1,65 @@
+Most Visited Sector in a Circular Track - LeetCode javascript solutions
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:
+
+
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 3and the marathon)
+We can see that both sectors 1and2 are visited twice and they are the most visited sectors. Sectors 3and4 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]
+
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)).
+
\ No newline at end of file
diff --git a/docs/problem/n-queens-ii.html b/docs/problem/n-queens-ii.html
new file mode 100644
index 0000000..0649234
--- /dev/null
+++ b/docs/problem/n-queens-ii.html
@@ -0,0 +1,61 @@
+N-Queens II - LeetCode javascript solutions
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);
+ return0;
+};
+
+var dfs = function (points, n, index) {
+ var res = 0;
+ if (points.length === n) return1;
+ 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]) returnfalse;
+ if (Math.abs((oldPoints[i][0] - newPoint[0]) / (oldPoints[i][1] - newPoint[1])) === 1) returnfalse;
+ }
+ returntrue;
+};
+
+
Explain:
+
跟之前的题不同的是,退出的时候要返回 count
+
Complexity:
+
+
Time complexity : O(n^2).
+
Space complexity : O(n).
+
\ No newline at end of file
diff --git a/docs/problem/n-queens.html b/docs/problem/n-queens.html
new file mode 100644
index 0000000..e1d1eeb
--- /dev/null
+++ b/docs/problem/n-queens.html
@@ -0,0 +1,73 @@
+N-Queens - LeetCode javascript solutions
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]) returnfalse;
+ if (Math.abs((oldPoints[i][0] - newPoint[0]) / (oldPoints[i][1] - newPoint[1])) === 1) returnfalse;
+ }
+ returntrue;
+};
+
+
Explain:
+
dfs
+
Complexity:
+
+
Time complexity : O(n^2).
+
Space complexity : O(n).
+
\ No newline at end of file
diff --git a/docs/problem/next-greater-element-i.html b/docs/problem/next-greater-element-i.html
new file mode 100644
index 0000000..0b3fbb4
--- /dev/null
+++ b/docs/problem/next-greater-element-i.html
@@ -0,0 +1,55 @@
+Next Greater Element I - LeetCode javascript solutions
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 isas follows:
+- 4is underlined in nums2 = [1,3,4,2]. There isnonext greater element, so the answer is -1.
+- 1is underlined in nums2 = [1,3,4,2]. The next greater element is3.
+- 2is underlined in nums2 = [1,3,4,2]. There isnonext 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 isas follows:
+- 2is underlined in nums2 = [1,2,3,4]. The next greater element is3.
+- 4is underlined in nums2 = [1,2,3,4]. There isnonext 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?
\ No newline at end of file
diff --git a/docs/problem/next-greater-element-ii.html b/docs/problem/next-greater-element-ii.html
new file mode 100644
index 0000000..de8345e
--- /dev/null
+++ b/docs/problem/next-greater-element-ii.html
@@ -0,0 +1,45 @@
+Next Greater Element II - LeetCode javascript solutions
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 first1's next greater numberis2;
+The number2 can't find next greater number.
+The second1'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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/next-greater-element-iii.html b/docs/problem/next-greater-element-iii.html
new file mode 100644
index 0000000..19616e1
--- /dev/null
+++ b/docs/problem/next-greater-element-iii.html
@@ -0,0 +1,48 @@
+Next Greater Element III - LeetCode javascript solutions
Given a positive integer n, find the smallest integer which has exactly the same digits existing in the integernand is greater in value thann. 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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/next-greater-element-iv.html b/docs/problem/next-greater-element-iv.html
new file mode 100644
index 0000000..0f018f7
--- /dev/null
+++ b/docs/problem/next-greater-element-iv.html
@@ -0,0 +1,67 @@
+Next Greater Element IV - LeetCode javascript solutions
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: 4isthefirstintegergreater than2, and9isthesecondintegergreater than2, tothe right of2.
+1st index: 9isthefirst, and6isthesecondintegergreater than4, tothe right of4.
+2nd index: 9isthefirst, and6isthesecondintegergreater than0, tothe right of0.
+3rd index: There is no integergreater than9toits right, so thesecond greater integeris considered to be -1.
+4th index: There is no integergreater than6toits right, so thesecond greater integeris 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 integergreater thanit.
+
+
+Constraints:
+
+
1 <= nums.length <= 105
+
0 <= nums[i] <= 109
+
+
Solution
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/next-permutation.html b/docs/problem/next-permutation.html
new file mode 100644
index 0000000..5f6a129
--- /dev/null
+++ b/docs/problem/next-permutation.html
@@ -0,0 +1,54 @@
+Next Permutation - LeetCode javascript solutions
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,3 → 1,3,2
+
3,2,1 → 1,2,3
+
1,1,5 → 1,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:
+
+
从后往前找,直到 nums[i] < nums[i + 1]
+
找到 i 后,从后往前找,直到 nums[j] > nums[i],交换 nums[i]、nums[j],然后把 i 后的倒置一下
+
没找到 i 的话,直接倒置一下
+
+
Complexity:
+
+
Time complexity : O(n).
+
Space complexity : O(1).
+
\ No newline at end of file
diff --git a/docs/problem/nim-game.html b/docs/problem/nim-game.html
new file mode 100644
index 0000000..83672fb
--- /dev/null
+++ b/docs/problem/nim-game.html
@@ -0,0 +1,26 @@
+Nim Game - LeetCode javascript solutions
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.
+
\ No newline at end of file
diff --git a/docs/problem/node-with-highest-edge-score.html b/docs/problem/node-with-highest-edge-score.html
new file mode 100644
index 0000000..24291a2
--- /dev/null
+++ b/docs/problem/node-with-highest-edge-score.html
@@ -0,0 +1,59 @@
+Node With Highest Edge Score - LeetCode javascript solutions
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:
+
+
Input: edges = [1,0,0,0,0,7,7,5]
+Output: 7
+Explanation:
+- The nodes 1, 2, 3and4 have an edge pointing to node0. The edge score of node0 is 1 + 2 + 3 + 4 = 10.
+- The node0 has an edge pointing to node1. The edge score of node1 is 0.
+- The node7 has an edge pointing to node5. The edge score of node5 is 7.
+- The nodes 5and6 have an edge pointing to node7. The edge score of node7 is 5 + 6 = 11.
+Node7 has the highest edge score so return 7.
+
+
Example 2:
+
+
Input: edges = [2,0,0,2]
+Output: 0
+Explanation:
+- The nodes 1and2 have an edge pointing to node0. The edge score of node0 is 1 + 2 = 3.
+- The nodes 0and3 have an edge pointing to node2. The edge score of node2 is 0 + 3 = 3.
+Nodes 0and2 both have an edge score of 3. Since node0 has a smaller index, we return 0.
+
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.
CREATEFUNCTION getNthHighestSalary(N INT) RETURNSINT
+BEGIN
+ RETURN (
+ # Write your MySQL querystatement below.
+ SELECTDISTINCT Salary FROM Employee ORDERBY Salary DESCLIMIT N, 1
+ );
+END
+
+
Explain:
+
nope.
+
Complexity:
+
+
Time complexity :
+
Space complexity :
+
\ No newline at end of file
diff --git a/docs/problem/number-of-1-bits.html b/docs/problem/number-of-1-bits.html
new file mode 100644
index 0000000..f00164f
--- /dev/null
+++ b/docs/problem/number-of-1-bits.html
@@ -0,0 +1,51 @@
+Number of 1 Bits - LeetCode javascript solutions
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 string00000000000000000000000000001011hasa total of three '1' bits.
+
+
Example 2:
+
Input: n = 00000000000000000000000010000000
+Output:1
+Explanation: The input binary string00000000000000000000000010000000hasa total of one '1' bit.
+
+
Example 3:
+
Input: n = 11111111111111111111111111111101
+Output:31
+Explanation: The input binary string11111111111111111111111111111101hasa 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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/number-of-dice-rolls-with-target-sum.html b/docs/problem/number-of-dice-rolls-with-target-sum.html
new file mode 100644
index 0000000..50044b3
--- /dev/null
+++ b/docs/problem/number-of-dice-rolls-with-target-sum.html
@@ -0,0 +1,61 @@
+Number of Dice Rolls With Target Sum - LeetCode javascript solutions
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 modulo109 + 7.
+
+Example 1:
+
Input: n = 1, k = 6, target = 3
+Output: 1
+Explanation: You throw one die with6 faces.
+There is only one way togetasumof3.
+
+
Example 2:
+
Input: n = 2, k = 6, target = 7
+Output: 6
+Explanation: You throw two dice, eachwith6 faces.
+There are 6 ways togetasumof7: 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
+
/**
+ * @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) return1;
+ if (n <= 0 || target <= 0) return0;
+ 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).
+
\ No newline at end of file
diff --git a/docs/problem/number-of-flowers-in-full-bloom.html b/docs/problem/number-of-flowers-in-full-bloom.html
new file mode 100644
index 0000000..2b2f5f2
--- /dev/null
+++ b/docs/problem/number-of-flowers-in-full-bloom.html
@@ -0,0 +1,73 @@
+Number of Flowers in Full Bloom - LeetCode javascript solutions
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:
+
+
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 returnthenumberof flowers in full bloom during their arrival.
+
+
Example 2:
+
+
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 returnthenumberof 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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/number-of-good-pairs.html b/docs/problem/number-of-good-pairs.html
new file mode 100644
index 0000000..47daf34
--- /dev/null
+++ b/docs/problem/number-of-good-pairs.html
@@ -0,0 +1,52 @@
+Number of Good Pairs - LeetCode javascript solutions
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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/number-of-islands.html b/docs/problem/number-of-islands.html
new file mode 100644
index 0000000..9822206
--- /dev/null
+++ b/docs/problem/number-of-islands.html
@@ -0,0 +1,58 @@
+Number of Islands - LeetCode javascript solutions
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.
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/number-of-laser-beams-in-a-bank.html b/docs/problem/number-of-laser-beams-in-a-bank.html
new file mode 100644
index 0000000..0f6b66b
--- /dev/null
+++ b/docs/problem/number-of-laser-beams-in-a-bank.html
@@ -0,0 +1,67 @@
+Number of Laser Beams in a Bank - LeetCode javascript solutions
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:
+
+
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:
+
+
Input: bank = ["000","111","000"]
+Output: 0
+Explanation: There doesnot 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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/number-of-music-playlists.html b/docs/problem/number-of-music-playlists.html
new file mode 100644
index 0000000..1d0c68e
--- /dev/null
+++ b/docs/problem/number-of-music-playlists.html
@@ -0,0 +1,59 @@
+Number of Music Playlists - LeetCode javascript solutions
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 modulo109 + 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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/number-of-submatrices-that-sum-to-target.html b/docs/problem/number-of-submatrices-that-sum-to-target.html
new file mode 100644
index 0000000..9480b45
--- /dev/null
+++ b/docs/problem/number-of-submatrices-that-sum-to-target.html
@@ -0,0 +1,65 @@
+Number of Submatrices That Sum to Target - LeetCode javascript solutions
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:
+
+
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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/number-of-subsequences-that-satisfy-the-given-sum-condition.html b/docs/problem/number-of-subsequences-that-satisfy-the-given-sum-condition.html
new file mode 100644
index 0000000..efdf616
--- /dev/null
+++ b/docs/problem/number-of-subsequences-that-satisfy-the-given-sum-condition.html
@@ -0,0 +1,72 @@
+Number of Subsequences That Satisfy the Given Sum Condition - LeetCode javascript solutions
1498. Number of Subsequences That Satisfy the Given Sum Condition
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, twoof them donot 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
+
/**
+ * @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:
+
+
sort the array won't change the result, so we sort it first
+
then use two pointer to find out answers
+
keep it in mind: do not let numbers overflow
+
+
Complexity:
+
+
Time complexity : O(nlog(n)).
+
Space complexity : O(n).
+
\ No newline at end of file
diff --git a/docs/problem/number-of-ways-to-divide-a-long-corridor.html b/docs/problem/number-of-ways-to-divide-a-long-corridor.html
new file mode 100644
index 0000000..c28dd5e
--- /dev/null
+++ b/docs/problem/number-of-ways-to-divide-a-long-corridor.html
@@ -0,0 +1,70 @@
+Number of Ways to Divide a Long Corridor - LeetCode javascript solutions
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 modulo109 + 7. If there is no way, return 0.
+
+Example 1:
+
+
Input: corridor = "SSPPSPS"
+Output: 3
+Explanation: There are 3 different ways todividethe corridor.
+The black bars inthe above image indicate thetwo room dividers already installed.
+Note that ineachofthe ways, each section has exactly two seats.
+
+
Example 2:
+
+
Input: corridor = "PPSPSP"
+Output: 1
+Explanation: There is only 1 way todividethe corridor, bynot installing any additional dividers.
+Installing any would create some section that does not have exactly two seats.
+
+
Example 3:
+
+
Input: corridor = "S"
+Output: 0
+Explanation: There is no way todividethe 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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/number-of-ways-to-reach-a-position-after-exactly-k-steps.html b/docs/problem/number-of-ways-to-reach-a-position-after-exactly-k-steps.html
new file mode 100644
index 0000000..5992198
--- /dev/null
+++ b/docs/problem/number-of-ways-to-reach-a-position-after-exactly-k-steps.html
@@ -0,0 +1,53 @@
+Number of Ways to Reach a Position After Exactly k Steps - LeetCode javascript solutions
2400. Number of Ways to Reach a Position After Exactly k Steps
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 exactlyk 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 2from1in exactly 3 steps in three ways:
+- 1 ->2 ->3 ->2.
+- 1 ->2 ->1 ->2.
+- 1 ->0 ->1 ->2.
+It can be proven thatno other way is possible, so we return3.
+
+
Example 2:
+
Input: startPos = 2, endPos = 5, k = 10
+Output: 0
+Explanation: It is impossible to reach position5fromposition2in exactly 10 steps.
+
\ No newline at end of file
diff --git a/docs/problem/number-of-ways-to-reconstruct-a-tree.html b/docs/problem/number-of-ways-to-reconstruct-a-tree.html
new file mode 100644
index 0000000..1710c62
--- /dev/null
+++ b/docs/problem/number-of-ways-to-reconstruct-a-tree.html
@@ -0,0 +1,98 @@
+Number Of Ways To Reconstruct A Tree - LeetCode javascript solutions
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 pairsif and only ifxi 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:
+
+
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:
+
+
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
+
/**
+ * @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;
+ return0;
+ }
+ for (var j = 0; j < map[num].length; j++) {
+ if (map[num][j] !== parent && !map[parent].includes(map[num][j])) {
+ return0;
+ }
+ }
+ 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).
+
\ No newline at end of file
diff --git a/docs/problem/number-of-ways-to-stay-in-the-same-place-after-some-steps.html b/docs/problem/number-of-ways-to-stay-in-the-same-place-after-some-steps.html
new file mode 100644
index 0000000..9b4d88e
--- /dev/null
+++ b/docs/problem/number-of-ways-to-stay-in-the-same-place-after-some-steps.html
@@ -0,0 +1,60 @@
+Number of Ways to Stay in the Same Place After Some Steps - LeetCode javascript solutions
1269. Number of Ways to Stay in the Same Place After Some Steps
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 exactlysteps steps. Since the answer may be too large, return it modulo109 + 7.
+
+Example 1:
+
Input: steps = 3, arrLen = 2
+Output: 4
+Explanation: There are 4 differents ways to stay at index 0after3 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 0after2 steps
+Right, Left
+Stay, Stay
+
\ No newline at end of file
diff --git a/docs/problem/numbers-with-same-consecutive-differences.html b/docs/problem/numbers-with-same-consecutive-differences.html
new file mode 100644
index 0000000..28a0d5c
--- /dev/null
+++ b/docs/problem/numbers-with-same-consecutive-differences.html
@@ -0,0 +1,61 @@
+Numbers With Same Consecutive Differences - LeetCode javascript solutions
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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/out-of-boundary-paths.html b/docs/problem/out-of-boundary-paths.html
new file mode 100644
index 0000000..a72947c
--- /dev/null
+++ b/docs/problem/out-of-boundary-paths.html
@@ -0,0 +1,65 @@
+Out of Boundary Paths - LeetCode javascript solutions
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 mostmaxMove 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 modulo109 + 7.
+
+Example 1:
+
+
Input: m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0
+Output: 6
+
+
Example 2:
+
+
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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/painting-the-walls.html b/docs/problem/painting-the-walls.html
new file mode 100644
index 0000000..45f537d
--- /dev/null
+++ b/docs/problem/painting-the-walls.html
@@ -0,0 +1,54 @@
+Painting the Walls - LeetCode javascript solutions
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 0and1 will be painted bythe paid painter, andit will take 3 units oftime; meanwhile, the free painter will paint the walls at index 2and3, free of cost in2 units oftime. 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 0and3 will be painted bythe paid painter, andit will take 2 units oftime; meanwhile, the free painter will paint the walls at index 1and2, free of cost in2 units oftime. 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
+
/**
+ * @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) return0;
+ if (i === cost.length) returnNumber.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).
+
\ No newline at end of file
diff --git a/docs/problem/palindrome-linked-list.html b/docs/problem/palindrome-linked-list.html
new file mode 100644
index 0000000..af96660
--- /dev/null
+++ b/docs/problem/palindrome-linked-list.html
@@ -0,0 +1,56 @@
+Palindrome Linked List - LeetCode javascript solutions
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) returnfalse;
+ left = left.next;
+ right = right.next;
+ }
+
+ returntrue;
+};
+
+
Explain:
+
nope.
+
Complexity:
+
+
Time complexity : O(n).
+
Space complexity : O(1).
+
\ No newline at end of file
diff --git a/docs/problem/palindrome-number.html b/docs/problem/palindrome-number.html
new file mode 100644
index 0000000..133645f
--- /dev/null
+++ b/docs/problem/palindrome-number.html
@@ -0,0 +1,65 @@
+Palindrome Number - LeetCode javascript solutions
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 toright, it reads -121. From rightto left, it becomes 121-. Therefore it is nota palindrome.
+
+
Example 3:
+
Input: 10
+Output: false
+Explanation: Reads 01fromrightto left. Therefore it is nota 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]) returnfalse;
+ l++;
+ r--;
+ }
+ returntrue;
+};
+
+
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) returnfalse;
+ 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).
+
\ No newline at end of file
diff --git a/docs/problem/palindrome-partitioning-ii.html b/docs/problem/palindrome-partitioning-ii.html
new file mode 100644
index 0000000..f011ed7
--- /dev/null
+++ b/docs/problem/palindrome-partitioning-ii.html
@@ -0,0 +1,41 @@
+Palindrome Partitioning II - LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/problem/parallel-courses-iii.html b/docs/problem/parallel-courses-iii.html
new file mode 100644
index 0000000..71b2c80
--- /dev/null
+++ b/docs/problem/parallel-courses-iii.html
@@ -0,0 +1,82 @@
+Parallel Courses III - LeetCode javascript solutions
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:
+
+
Input: n = 3, relations = [[1,3],[2,3]], time = [3,2,5]
+Output: 8
+Explanation: The figure above represents the given graph andthetime required to complete each course.
+We start course 1and 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, andthe total time required is 3 + 5 = 8 months.
+
+
Example 2:
+
+
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, and3atmonth0.
+You can complete them after1, 2, and3months respectively.
+Course 4 can be taken onlyafter course 3is completed, i.e., after3 months. It is completed after3 + 4 = 7 months.
+Course 5 can be taken onlyafter courses 1, 2, 3, and4 have been completed, i.e., aftermax(1,2,3,7) = 7 months.
+Thus, the minimumtime needed tocomplete all the courses is7 + 5 = 12 months.
+
All the pairs [prevCoursej, nextCoursej] are unique.
+
time.length == n
+
1 <= time[i] <= 104
+
The given graph is a directed acyclic graph.
+
+
Solution
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/partition-array-for-maximum-sum.html b/docs/problem/partition-array-for-maximum-sum.html
new file mode 100644
index 0000000..0219dcd
--- /dev/null
+++ b/docs/problem/partition-array-for-maximum-sum.html
@@ -0,0 +1,57 @@
+Partition Array for Maximum Sum - LeetCode javascript solutions
Given an integer array arr, partition the array into (contiguous) subarrays of length at mostk. 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.**
dp[arr.length - 1] would be the answer in the end of the iteration.
+
Complexity:
+
+
Time complexity : O(n).
+
Space complexity : O(n).
+
\ No newline at end of file
diff --git a/docs/problem/partition-list.html b/docs/problem/partition-list.html
new file mode 100644
index 0000000..aad5035
--- /dev/null
+++ b/docs/problem/partition-list.html
@@ -0,0 +1,51 @@
+Partition List - LeetCode javascript solutions
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).
+
\ No newline at end of file
diff --git a/docs/problem/pascals-triangle-ii.html b/docs/problem/pascals-triangle-ii.html
new file mode 100644
index 0000000..f8f1a22
--- /dev/null
+++ b/docs/problem/pascals-triangle-ii.html
@@ -0,0 +1,82 @@
+Pascal's Triangle II - LeetCode javascript solutions
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 trueif 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:
+
+
Input: path = "NES"
+Output:false
+Explanation: Notice that the path doesn't cross any point more than once.
+
+
Example 2:
+
+
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
+
/**
+ * @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]) returntrue;
+ visited[num] = true;
+ }
+ returnfalse;
+};
+
+
Explain:
+
nope.
+
Complexity:
+
+
Time complexity : O(n).
+
Space complexity : O(n).
+
\ No newline at end of file
diff --git a/docs/problem/path-sum-ii.html b/docs/problem/path-sum-ii.html
new file mode 100644
index 0000000..07edf66
--- /dev/null
+++ b/docs/problem/path-sum-ii.html
@@ -0,0 +1,56 @@
+Path Sum II - LeetCode javascript solutions
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
+ / \
+ 48
+ / / \
+ 11134
+ / \ / \
+7251
+
+
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 :
+
\ No newline at end of file
diff --git a/docs/problem/path-sum.html b/docs/problem/path-sum.html
new file mode 100644
index 0000000..b79a180
--- /dev/null
+++ b/docs/problem/path-sum.html
@@ -0,0 +1,40 @@
+Path Sum - LeetCode javascript solutions
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
+ / \
+ 48
+ / / \
+ 11134
+ / \ \
+721
+
+
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) returnfalse;
+ if (root.val === sum && !root.left && !root.right) returntrue;
+ return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val)
+};
+
+
Explain:
+
nope.
+
Complexity:
+
+
Time complexity : O(n).
+
Space complexity : O(1).
+
\ No newline at end of file
diff --git a/docs/problem/peak-index-in-a-mountain-array.html b/docs/problem/peak-index-in-a-mountain-array.html
new file mode 100644
index 0000000..e55d3a3
--- /dev/null
+++ b/docs/problem/peak-index-in-a-mountain-array.html
@@ -0,0 +1,56 @@
+Peak Index in a Mountain Array - LeetCode javascript solutions
k-- 这里比较难理解,是用来纠正 k 正好整除于某个阶乘数的特殊情况,即 k % factorial[i] === 0 时。
+
Complexity:
+
+
Time complexity : O(n).
+
Space complexity : O(1).
+
\ No newline at end of file
diff --git a/docs/problem/permutations-ii.html b/docs/problem/permutations-ii.html
new file mode 100644
index 0000000..68f6501
--- /dev/null
+++ b/docs/problem/permutations-ii.html
@@ -0,0 +1,52 @@
+Permutations II - LeetCode javascript solutions
/**
+ * @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 :
+
\ No newline at end of file
diff --git a/docs/problem/permutations.html b/docs/problem/permutations.html
new file mode 100644
index 0000000..b9d10d6
--- /dev/null
+++ b/docs/problem/permutations.html
@@ -0,0 +1,52 @@
+Permutations - LeetCode javascript solutions
/**
+ * @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 :
+
\ No newline at end of file
diff --git a/docs/problem/plus-one.html b/docs/problem/plus-one.html
new file mode 100644
index 0000000..49f551c
--- /dev/null
+++ b/docs/problem/plus-one.html
@@ -0,0 +1,40 @@
+Plus One - LeetCode javascript solutions
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 1and 2, and feed the second pig buckets 2and 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 time0, feed thefirst pig bucket 1, and feed thesecond pig bucket 2.
+At time15, there are 2 possible outcomes:
+- If either pig dies, thenthe poisonous bucket is theoneit was fed.
+- If neither pig dies, then feed thefirst pig bucket 3, and feed thesecond pig bucket 4.
+At time30, oneofthetwo pigs must die, andthe poisonous bucket is theoneit was fed.
+
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).
+
\ 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
new file mode 100644
index 0000000..a088a7b
--- /dev/null
+++ b/docs/problem/populating-next-right-pointers-in-each-node-ii.html
@@ -0,0 +1,111 @@
+Populating Next Right Pointers in Each Node II - LeetCode javascript solutions
117. Populating Next Right Pointers in Each Node II
/**
+ * 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).
+
\ 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
new file mode 100644
index 0000000..df3eccb
--- /dev/null
+++ b/docs/problem/populating-next-right-pointers-in-each-node.html
@@ -0,0 +1,109 @@
+Populating Next Right Pointers in Each Node - LeetCode javascript solutions
/**
+ * 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).
+
\ No newline at end of file
diff --git a/docs/problem/power-of-four.html b/docs/problem/power-of-four.html
new file mode 100644
index 0000000..bba2ab3
--- /dev/null
+++ b/docs/problem/power-of-four.html
@@ -0,0 +1,40 @@
+Power of Four - LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/problem/power-of-two.html b/docs/problem/power-of-two.html
new file mode 100644
index 0000000..6cbf657
--- /dev/null
+++ b/docs/problem/power-of-two.html
@@ -0,0 +1,44 @@
+Power of Two - LeetCode javascript solutions
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) return1;
+ if (n > 0) return pow(x, n);
+ if (n < 0) return1 / 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)).
+
\ No newline at end of file
diff --git a/docs/problem/predict-the-winner.html b/docs/problem/predict-the-winner.html
new file mode 100644
index 0000000..ebe9d70
--- /dev/null
+++ b/docs/problem/predict-the-winner.html
@@ -0,0 +1,49 @@
+Predict the Winner - LeetCode javascript solutions
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, player1 can choose between 1and2.
+If he chooses 2 (or1), thenplayer2 can choose from1 (or2) and5. Ifplayer2 chooses 5, thenplayer1 will be left with1 (or2).
+So, final score of player1 is 1 + 2 = 3, andplayer2 is 5.
+Hence, player1 will never be the winner and you need to return false.
+
+
Example 2:
+
Input: nums = [1,5,233,7]
+Output: true
+Explanation: Player1 first chooses 1. Thenplayer2 has to choose between 5and7. No matter which number player2 choose, player1 can choose 233.
+Finally, player1 has more score (234) than player2 (12), so you need to return True representing player1 can win.
+
\ No newline at end of file
diff --git a/docs/problem/previous-permutation-with-one-swap.html b/docs/problem/previous-permutation-with-one-swap.html
new file mode 100644
index 0000000..977a37e
--- /dev/null
+++ b/docs/problem/previous-permutation-with-one-swap.html
@@ -0,0 +1,95 @@
+Previous Permutation With One Swap - LeetCode javascript solutions
Given an array of positive integers arr (not necessarily distinct), return the lexicographically largest permutation that is smaller thanarr, 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]
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).
+
\ 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
new file mode 100644
index 0000000..e06ea96
--- /dev/null
+++ b/docs/problem/product-of-array-except-self.html
@@ -0,0 +1,76 @@
+Product of Array Except Self - LeetCode javascript solutions
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).
+
\ No newline at end of file
diff --git a/docs/problem/pseudo-palindromic-paths-in-a-binary-tree.html b/docs/problem/pseudo-palindromic-paths-in-a-binary-tree.html
new file mode 100644
index 0000000..4845bc9
--- /dev/null
+++ b/docs/problem/pseudo-palindromic-paths-in-a-binary-tree.html
@@ -0,0 +1,67 @@
+Pseudo-Palindromic Paths in a Binary Tree - LeetCode javascript solutions
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:
+
+
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 fromthe root node to leaf nodes: the red path [2,3,3], the green path [2,1,1], andthe 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) andthe green path [2,1,1] can be rearranged in [1,2,1] (palindrome).
+
+
Example 2:
+
+
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 fromthe root node to leaf nodes: the green path [2,1,1], the path [2,1,3,1], andthe 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].
\ No newline at end of file
diff --git a/docs/problem/put-marbles-in-bags.html b/docs/problem/put-marbles-in-bags.html
new file mode 100644
index 0000000..1baa4c6
--- /dev/null
+++ b/docs/problem/put-marbles-in-bags.html
@@ -0,0 +1,55 @@
+Put Marbles in Bags - LeetCode javascript solutions
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 return0.
+
+
+Constraints:
+
+
1 <= k <= weights.length <= 105
+
1 <= weights[i] <= 109
+
+
Solution
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/range-sum-of-bst.html b/docs/problem/range-sum-of-bst.html
new file mode 100644
index 0000000..d1c4a8d
--- /dev/null
+++ b/docs/problem/range-sum-of-bst.html
@@ -0,0 +1,58 @@
+Range Sum of BST - LeetCode javascript solutions
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:
+
+
Input: root = [10,5,15,3,7,null,18], low = 7, high = 15
+Output: 32
+Explanation: Nodes 7, 10, and15 are in the range [7, 15]. 7 + 10 + 15 = 32.
+
+
Example 2:
+
+
Input: root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10
+Output: 23
+Explanation: Nodes 6, 7, and10 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].
\ No newline at end of file
diff --git a/docs/problem/range-sum-query-2d-immutable.html b/docs/problem/range-sum-query-2d-immutable.html
new file mode 100644
index 0000000..949c5f6
--- /dev/null
+++ b/docs/problem/range-sum-query-2d-immutable.html
@@ -0,0 +1,77 @@
+Range Sum Query 2D - Immutable - LeetCode javascript solutions
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:
+
+
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
+
/**
+ * @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) {
+ returnthis.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).
+
\ No newline at end of file
diff --git a/docs/problem/range-sum-query-immutable.html b/docs/problem/range-sum-query-immutable.html
new file mode 100644
index 0000000..c455e20
--- /dev/null
+++ b/docs/problem/range-sum-query-immutable.html
@@ -0,0 +1,65 @@
+Range Sum Query - Immutable - LeetCode javascript solutions
Given an integer array nums, handle multiple queries of the following type:
+
+
Calculate the sum of the elements of nums between indices left and rightinclusive 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 rightinclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right]).
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.
# 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 :
+
\ No newline at end of file
diff --git a/docs/problem/reconstruct-itinerary.html b/docs/problem/reconstruct-itinerary.html
new file mode 100644
index 0000000..733bd69
--- /dev/null
+++ b/docs/problem/reconstruct-itinerary.html
@@ -0,0 +1,62 @@
+Reconstruct Itinerary - LeetCode javascript solutions
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.
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.
\ No newline at end of file
diff --git a/docs/problem/recover-binary-search-tree.html b/docs/problem/recover-binary-search-tree.html
new file mode 100644
index 0000000..d2ab58e
--- /dev/null
+++ b/docs/problem/recover-binary-search-tree.html
@@ -0,0 +1,140 @@
+Recover Binary Search Tree - LeetCode javascript solutions
/**
+ * 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).
+
\ No newline at end of file
diff --git a/docs/problem/redistribute-characters-to-make-all-strings-equal.html b/docs/problem/redistribute-characters-to-make-all-strings-equal.html
new file mode 100644
index 0000000..9033d90
--- /dev/null
+++ b/docs/problem/redistribute-characters-to-make-all-strings-equal.html
@@ -0,0 +1,47 @@
+Redistribute Characters to Make All Strings Equal - LeetCode javascript solutions
1897. Redistribute Characters to Make All Strings Equal
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 trueif 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 thefirst'a'inwords[1] tothe front ofwords[2],
+to make words[1] = "abc"andwords[2] = "abc".
+All the strings are now equal to"abc", so returntrue.
+
+
Example 2:
+
Input: words = ["ab","a"]
+Output: false
+Explanation: It is impossible to make all the strings equal usingthe operation.
+
+
+Constraints:
+
+
1 <= words.length <= 100
+
1 <= words[i].length <= 100
+
words[i] consists of lowercase English letters.
+
+
Solution
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/reduction-operations-to-make-the-array-elements-equal.html b/docs/problem/reduction-operations-to-make-the-array-elements-equal.html
new file mode 100644
index 0000000..c11fa5d
--- /dev/null
+++ b/docs/problem/reduction-operations-to-make-the-array-elements-equal.html
@@ -0,0 +1,68 @@
+Reduction Operations to Make the Array Elements Equal - LeetCode javascript solutions
1887. Reduction Operations to Make the Array Elements Equal
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 numsstrictly 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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/regular-expression-matching.html b/docs/problem/regular-expression-matching.html
new file mode 100644
index 0000000..eb2bdbe
--- /dev/null
+++ b/docs/problem/regular-expression-matching.html
@@ -0,0 +1,85 @@
+Regular Expression Matching - LeetCode javascript solutions
Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'.
+
'.' Matches any single character.
+'*' Matches zeroor more ofthe 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".
+
/**
+ * @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);
+ } elseif (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).
+
\ No newline at end of file
diff --git a/docs/problem/remove-all-adjacent-duplicates-in-string.html b/docs/problem/remove-all-adjacent-duplicates-in-string.html
new file mode 100644
index 0000000..73ba141
--- /dev/null
+++ b/docs/problem/remove-all-adjacent-duplicates-in-string.html
@@ -0,0 +1,45 @@
+Remove All Adjacent Duplicates In String - LeetCode javascript solutions
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 moveis that the stringis"aaca", of which only"aa"is possible, so the final stringis"ca".
+
+
Example 2:
+
Input: s = "azxxzy"
+Output:"ay"
+
+
+Constraints:
+
+
1 <= s.length <= 105
+
s consists of lowercase English letters.
+
+
Solution
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/remove-colored-pieces-if-both-neighbors-are-the-same-color.html b/docs/problem/remove-colored-pieces-if-both-neighbors-are-the-same-color.html
new file mode 100644
index 0000000..2453504
--- /dev/null
+++ b/docs/problem/remove-colored-pieces-if-both-neighbors-are-the-same-color.html
@@ -0,0 +1,83 @@
+Remove Colored Pieces if Both Neighbors are the Same Color - LeetCode javascript solutions
2038. Remove Colored Pieces if Both Neighbors are the Same Color
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 thesecond'A'fromthe left since that is the only 'A' whose neighbors are both 'A'.
+
+Now it's Bob's turn.
+Bob cannot make a move onhisturnsincethereareno'B'swhoseneighborsareboth'B'.
+Thus, Alice wins, so returntrue.
+
+
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 moveon her turn.
+Thus, Bob wins, soreturn false.
+
+
Example 3:
+
Input: colors = "ABBBBBBBAAA"
+Output: false
+Explanation:
+ABBBBBBBAAA -> ABBBBBBBAA
+Alice moves first.
+Her only optionisto remove the second to last 'A' from the right.
+
+ABBBBBBBAA -> ABBBBBBAA
+Nextis 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 returnfalse.
+
+
+Constraints:
+
+
1 <= colors.length <= 105
+
colors consists of only the letters 'A' and 'B'
+
+
Solution
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/remove-duplicate-letters.html b/docs/problem/remove-duplicate-letters.html
new file mode 100644
index 0000000..d9227b5
--- /dev/null
+++ b/docs/problem/remove-duplicate-letters.html
@@ -0,0 +1,47 @@
+Remove Duplicate Letters - LeetCode javascript solutions
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(newRegExp(firstChar, 'g'), '');
+
+ return firstChar + removeDuplicateLetters(restString);
+};
+
+
Explain:
+
贪心,每次找到排第一的字符,再递归。
+
Complexity:
+
+
Time complexity : O(n).
+
Space complexity : O(n).
+
\ 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
new file mode 100644
index 0000000..fa85ee8
--- /dev/null
+++ b/docs/problem/remove-duplicates-from-sorted-array-ii.html
@@ -0,0 +1,61 @@
+Remove Duplicates from Sorted Array II - LeetCode javascript solutions
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)
+intlen = 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++;
+ elsecontinue;
+ } else {
+ times = 1;
+ }
+ last = nums[i];
+ nums[index] = nums[i];
+ index++;
+ }
+ return index;
+};
+
+
Explain:
+
nope.
+
Complexity:
+
+
Time complexity : O(n).
+
Space complexity : O(1).
+
\ 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
new file mode 100644
index 0000000..6cd0d5b
--- /dev/null
+++ b/docs/problem/remove-duplicates-from-sorted-array.html
@@ -0,0 +1,56 @@
+Remove Duplicates from Sorted Array - LeetCode javascript solutions
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 functionshouldreturnlength = 2, with the first two elements of nums being 1and2 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)
+intlen = 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).
+
\ 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
new file mode 100644
index 0000000..e3ec3aa
--- /dev/null
+++ b/docs/problem/remove-duplicates-from-sorted-list-ii.html
@@ -0,0 +1,51 @@
+Remove Duplicates from Sorted List II - LeetCode javascript solutions
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).
+
\ 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
new file mode 100644
index 0000000..95b7c3b
--- /dev/null
+++ b/docs/problem/remove-duplicates-from-sorted-list.html
@@ -0,0 +1,41 @@
+Remove Duplicates from Sorted List - LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/problem/remove-element.html b/docs/problem/remove-element.html
new file mode 100644
index 0000000..09676a2
--- /dev/null
+++ b/docs/problem/remove-element.html
@@ -0,0 +1,55 @@
+Remove Element - LeetCode javascript solutions
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 functionshouldreturnlength = 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)
+intlen = 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).
+
\ 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
new file mode 100644
index 0000000..0cb32a9
--- /dev/null
+++ b/docs/problem/remove-nth-node-from-end-of-list.html
@@ -0,0 +1,58 @@
+Remove Nth Node From End of List - LeetCode javascript solutions
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:
+
+
两个指针 a, b,初始都指向开头
+
把 b 指针往后移动,直到两指针的位置相差 n
+
同时移动两指针,直到 b 指针到了最后。这时候因为两指针的位置相差 n,a 指针的位置就是从后面数第 n+1 个
+
在 a 指针那里删掉后面一个,即第 n 个
+
+
要注意可能会出现删掉 head 的情况。
+
Complexity:
+
+
Time complexity : O(n).
+
Space complexity : O(1).
+
\ No newline at end of file
diff --git a/docs/problem/removing-stars-from-a-string.html b/docs/problem/removing-stars-from-a-string.html
new file mode 100644
index 0000000..46193a5
--- /dev/null
+++ b/docs/problem/removing-stars-from-a-string.html
@@ -0,0 +1,59 @@
+Removing Stars From a String - LeetCode javascript solutions
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 leftto right:
+- The closest character to the 1ststaris't' in "leet**cod*e". s becomes "lee*cod*e".
+- The closest character to the 2nd staris'e' in "lee*cod*e". s becomes "lecod*e".
+- The closest character to the 3rd staris'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 stringis removed, so we returnanemptystring.
+
+
+Constraints:
+
+
1 <= s.length <= 105
+
s consists of lowercase English letters and stars *.
+
The operation above can be performed on s.
+
+
Solution
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/reorder-list.html b/docs/problem/reorder-list.html
new file mode 100644
index 0000000..a89aae7
--- /dev/null
+++ b/docs/problem/reorder-list.html
@@ -0,0 +1,74 @@
+Reorder List - LeetCode javascript solutions
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
+reorder it to: L0→Ln→L1→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 ,分三步
+
+
找到 mid = 3
+
翻转后半部分,变成 1->2->3->6->5->4
+
后半部分依次插入到前半部分
+
+
Complexity:
+
+
Time complexity : O(n).
+
Space complexity : O(1).
+
\ No newline at end of file
diff --git a/docs/problem/repeated-dna-sequences.html b/docs/problem/repeated-dna-sequences.html
new file mode 100644
index 0000000..c444997
--- /dev/null
+++ b/docs/problem/repeated-dna-sequences.html
@@ -0,0 +1,51 @@
+Repeated DNA Sequences - LeetCode javascript solutions
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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/repeated-substring-pattern.html b/docs/problem/repeated-substring-pattern.html
new file mode 100644
index 0000000..984c273
--- /dev/null
+++ b/docs/problem/repeated-substring-pattern.html
@@ -0,0 +1,39 @@
+Repeated Substring Pattern - LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/problem/reshape-the-matrix.html b/docs/problem/reshape-the-matrix.html
new file mode 100644
index 0000000..1c05d12
--- /dev/null
+++ b/docs/problem/reshape-the-matrix.html
@@ -0,0 +1,61 @@
+Reshape the Matrix - LeetCode javascript solutions
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).
+
\ No newline at end of file
diff --git a/docs/problem/restore-ip-addresses.html b/docs/problem/restore-ip-addresses.html
new file mode 100644
index 0000000..0b023e7
--- /dev/null
+++ b/docs/problem/restore-ip-addresses.html
@@ -0,0 +1,95 @@
+Restore IP Addresses - LeetCode javascript solutions
/**
+ * @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') returnfalse;
+ if (Number(str) > 255) returnfalse;
+ returntrue;
+};
+
+
Explain:
+
nope.
+
Complexity:
+
+
Time complexity : O(1).
+
Space complexity : O(1).
+
\ No newline at end of file
diff --git a/docs/problem/restore-the-array-from-adjacent-pairs.html b/docs/problem/restore-the-array-from-adjacent-pairs.html
new file mode 100644
index 0000000..f3514ad
--- /dev/null
+++ b/docs/problem/restore-the-array-from-adjacent-pairs.html
@@ -0,0 +1,65 @@
+Restore the Array From Adjacent Pairs - LeetCode javascript solutions
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.
+
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) return0;
+ }
+ return res;
+};
+
+
Explain:
+
nope.
+
Complexity:
+
+
Time complexity : O(log(n)).
+
Space complexity : O(n).
+
\ No newline at end of file
diff --git a/docs/problem/reverse-linked-list-ii.html b/docs/problem/reverse-linked-list-ii.html
new file mode 100644
index 0000000..bb2d26a
--- /dev/null
+++ b/docs/problem/reverse-linked-list-ii.html
@@ -0,0 +1,68 @@
+Reverse Linked List II - LeetCode javascript solutions
Reverse a linked list from position m to n. Do it in one-pass.
+
Note: 1 ≤ m ≤ n ≤ 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).
+
\ No newline at end of file
diff --git a/docs/problem/reverse-linked-list.html b/docs/problem/reverse-linked-list.html
new file mode 100644
index 0000000..b905fe5
--- /dev/null
+++ b/docs/problem/reverse-linked-list.html
@@ -0,0 +1,69 @@
+Reverse Linked List - LeetCode javascript solutions
\ 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
new file mode 100644
index 0000000..59120a1
--- /dev/null
+++ b/docs/problem/reverse-nodes-in-k-group.html
@@ -0,0 +1,59 @@
+Reverse Nodes in k-Group - LeetCode javascript solutions
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).
+
\ 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
new file mode 100644
index 0000000..59ab449
--- /dev/null
+++ b/docs/problem/reverse-words-in-a-string-iii.html
@@ -0,0 +1,33 @@
+Reverse Words in a String III - LeetCode javascript solutions
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 :
+
\ 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
new file mode 100644
index 0000000..707a39a
--- /dev/null
+++ b/docs/problem/reverse-words-in-a-string.html
@@ -0,0 +1,29 @@
+Reverse Words in a String - LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/problem/roman-to-integer.html b/docs/problem/roman-to-integer.html
new file mode 100644
index 0000000..aab8ab5
--- /dev/null
+++ b/docs/problem/roman-to-integer.html
@@ -0,0 +1,84 @@
+Roman to Integer - LeetCode javascript solutions
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 = 30andIII = 3.
+
+
Example 5:
+
Input: "MCMXCIV"
+Output: 1994
+Explanation: M = 1000, CM = 900, XC = 90andIV = 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).
+
\ No newline at end of file
diff --git a/docs/problem/rotate-image.html b/docs/problem/rotate-image.html
new file mode 100644
index 0000000..65a7880
--- /dev/null
+++ b/docs/problem/rotate-image.html
@@ -0,0 +1,78 @@
+Rotate Image - LeetCode javascript solutions
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]
+]
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/rotate-list.html b/docs/problem/rotate-list.html
new file mode 100644
index 0000000..ed66fd9
--- /dev/null
+++ b/docs/problem/rotate-list.html
@@ -0,0 +1,71 @@
+Rotate List - LeetCode javascript solutions
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;
+};
+
\ No newline at end of file
diff --git a/docs/problem/same-tree.html b/docs/problem/same-tree.html
new file mode 100644
index 0000000..d189ae1
--- /dev/null
+++ b/docs/problem/same-tree.html
@@ -0,0 +1,99 @@
+Same Tree - LeetCode javascript solutions
\ 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
new file mode 100644
index 0000000..0012902
--- /dev/null
+++ b/docs/problem/search-a-2d-matrix-ii.html
@@ -0,0 +1,55 @@
+Search a 2D Matrix II - LeetCode javascript solutions
/**
+ * @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) {
+ returntrue;
+ } elseif (target > tmp) {
+ y++;
+ } else {
+ x--;
+ }
+ }
+ returnfalse;
+};
+
+
Explain:
+
nope.
+
Complexity:
+
+
Time complexity : O(n + m). n 行 m 列。
+
Space complexity : O(1).
+
\ No newline at end of file
diff --git a/docs/problem/search-a-2d-matrix.html b/docs/problem/search-a-2d-matrix.html
new file mode 100644
index 0000000..2b27485
--- /dev/null
+++ b/docs/problem/search-a-2d-matrix.html
@@ -0,0 +1,104 @@
+Search a 2D Matrix - LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/problem/search-for-a-range.html b/docs/problem/search-for-a-range.html
new file mode 100644
index 0000000..4a80103
--- /dev/null
+++ b/docs/problem/search-for-a-range.html
@@ -0,0 +1,59 @@
+Search for a Range - LeetCode javascript solutions
/**
+ * @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:
+
二分查找:
+
分两次,第一次找左边位置,第二次找右边位置
+
+
中间值小于目标,继续去右半部分找
+
中间值大于目标,继续去左半部分找
+
中间值等于目标,找左位置时,继续去左半部分找;
+ 找右位置时,继续去右半部分找。
+
最终不能找到的话,左位置是会大于右位置的,否则代表找到
+
+
Complexity:
+
+
Time complexity : O(log(n)).
+
Space complexity : O(1).
+
\ 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
new file mode 100644
index 0000000..8bdbfde
--- /dev/null
+++ b/docs/problem/search-in-rotated-sorted-array-ii.html
@@ -0,0 +1,61 @@
+Search in Rotated Sorted Array II - LeetCode javascript solutions
\ 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
new file mode 100644
index 0000000..76dfbd7
--- /dev/null
+++ b/docs/problem/search-in-rotated-sorted-array.html
@@ -0,0 +1,60 @@
+Search in Rotated Sorted Array - LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/problem/search-insert-position.html b/docs/problem/search-insert-position.html
new file mode 100644
index 0000000..82b0474
--- /dev/null
+++ b/docs/problem/search-insert-position.html
@@ -0,0 +1,54 @@
+Search Insert Position - LeetCode javascript solutions
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) return0;
+
+ while (left <= right) {
+ mid = Math.floor((left + right) / 2);
+ if (nums[mid] > target) {
+ right = mid - 1;
+ } elseif (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).
+
\ No newline at end of file
diff --git a/docs/problem/seat-reservation-manager.html b/docs/problem/seat-reservation-manager.html
new file mode 100644
index 0000000..abdb60a
--- /dev/null
+++ b/docs/problem/seat-reservation-manager.html
@@ -0,0 +1,82 @@
+Seat Reservation Manager - LeetCode javascript solutions
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
+
/**
+ * @param {number} n
+ */
+var SeatManager = function(n) {
+ this.queue = new MinPriorityQueue();
+ this.index = 1;
+};
+
+/**
+ * @return {number}
+ */
+SeatManager.prototype.reserve = function() {
+ if (this.queue.size()) {
+ returnthis.queue.dequeue().element;
+ }
+ returnthis.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).
+
\ No newline at end of file
diff --git a/docs/problem/second-highest-salary.html b/docs/problem/second-highest-salary.html
new file mode 100644
index 0000000..a34cfd5
--- /dev/null
+++ b/docs/problem/second-highest-salary.html
@@ -0,0 +1,28 @@
+Second Highest Salary - LeetCode javascript solutions
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.
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);
+ } elseif (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).
+
\ No newline at end of file
diff --git a/docs/problem/set-mismatch.html b/docs/problem/set-mismatch.html
new file mode 100644
index 0000000..6d71960
--- /dev/null
+++ b/docs/problem/set-mismatch.html
@@ -0,0 +1,49 @@
+Set Mismatch - LeetCode javascript solutions
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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/shortest-common-supersequence.html b/docs/problem/shortest-common-supersequence.html
new file mode 100644
index 0000000..fb20567
--- /dev/null
+++ b/docs/problem/shortest-common-supersequence.html
@@ -0,0 +1,55 @@
+Shortest Common Supersequence - LeetCode javascript solutions
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 deletethefirst"c".
+str2 = "cab" is a subsequence of"cabac" because we can deletethelast"ac".
+The answer provided is the shortest such string that satisfies these properties.
+
str1 and str2 consist of lowercase English letters.
+
+
Solution
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/shortest-completing-word.html b/docs/problem/shortest-completing-word.html
new file mode 100644
index 0000000..8af8b9b
--- /dev/null
+++ b/docs/problem/shortest-completing-word.html
@@ -0,0 +1,77 @@
+Shortest Completing Word - LeetCode javascript solutions
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 lengthwords that containsthe letters "s".
+We returntheone 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 :
+
\ No newline at end of file
diff --git a/docs/problem/sign-of-the-product-of-an-array.html b/docs/problem/sign-of-the-product-of-an-array.html
new file mode 100644
index 0000000..bc77301
--- /dev/null
+++ b/docs/problem/sign-of-the-product-of-an-array.html
@@ -0,0 +1,51 @@
+Sign of the Product of an Array - LeetCode javascript solutions
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).
+
\ No newline at end of file
diff --git a/docs/problem/single-number-ii.html b/docs/problem/single-number-ii.html
new file mode 100644
index 0000000..ec72487
--- /dev/null
+++ b/docs/problem/single-number-ii.html
@@ -0,0 +1,37 @@
+Single Number II - LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/problem/single-number-iii.html b/docs/problem/single-number-iii.html
new file mode 100644
index 0000000..3c5fd57
--- /dev/null
+++ b/docs/problem/single-number-iii.html
@@ -0,0 +1,50 @@
+Single Number III - LeetCode javascript solutions
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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/single-number.html b/docs/problem/single-number.html
new file mode 100644
index 0000000..f2b439f
--- /dev/null
+++ b/docs/problem/single-number.html
@@ -0,0 +1,33 @@
+Single Number - LeetCode javascript solutions
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).
+
\ No newline at end of file
diff --git a/docs/problem/single-threaded-cpu.html b/docs/problem/single-threaded-cpu.html
new file mode 100644
index 0000000..0c1b95b
--- /dev/null
+++ b/docs/problem/single-threaded-cpu.html
@@ -0,0 +1,82 @@
+Single-Threaded CPU - LeetCode javascript solutions
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 ith 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, task0is available to process. Available tasks = {0}.
+- Also at time = 1, the idle CPU starts processing task0. Available tasks = {}.
+- At time = 2, task1is available to process. Available tasks = {1}.
+- At time = 3, task2is available to process. Available tasks = {1, 2}.
+- Also at time = 3, the CPU finishes task0and starts processing task2 as it is the shortest. Available tasks = {1}.
+- At time = 4, task3is available to process. Available tasks = {1, 3}.
+- At time = 5, the CPU finishes task2and starts processing task3 as it is the shortest. Available tasks = {1}.
+- At time = 6, the CPU finishes task3and starts processing task1. Available tasks = {}.
+- At time = 10, the CPU finishes task1and 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 task4. Available tasks = {0,1,2,3}.
+- At time = 9, the CPU finishes task4and starts processing task3. Available tasks = {0,1,2}.
+- At time = 13, the CPU finishes task3and starts processing task2. Available tasks = {0,1}.
+- At time = 18, the CPU finishes task2and starts processing task0. Available tasks = {1}.
+- At time = 28, the CPU finishes task0and starts processing task1. Available tasks = {}.
+- At time = 40, the CPU finishes task1and becomes idle.
+
+
+Constraints:
+
+
tasks.length == n
+
1 <= n <= 105
+
1 <= enqueueTimei, processingTimei <= 109
+
+
Solution
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/sliding-window-maximum.html b/docs/problem/sliding-window-maximum.html
new file mode 100644
index 0000000..284c661
--- /dev/null
+++ b/docs/problem/sliding-window-maximum.html
@@ -0,0 +1,53 @@
+Sliding Window Maximum - LeetCode javascript solutions
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.
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/smallest-even-multiple.html b/docs/problem/smallest-even-multiple.html
new file mode 100644
index 0000000..64a1fff
--- /dev/null
+++ b/docs/problem/smallest-even-multiple.html
@@ -0,0 +1,34 @@
+Smallest Even Multiple - LeetCode javascript solutions
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 5and2 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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/smallest-range-ii.html b/docs/problem/smallest-range-ii.html
new file mode 100644
index 0000000..5a3001d
--- /dev/null
+++ b/docs/problem/smallest-range-ii.html
@@ -0,0 +1,53 @@
+Smallest Range II - LeetCode javascript solutions
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/solving-questions-with-brainpower.html b/docs/problem/solving-questions-with-brainpower.html
new file mode 100644
index 0000000..b9f67b8
--- /dev/null
+++ b/docs/problem/solving-questions-with-brainpower.html
@@ -0,0 +1,61 @@
+Solving Questions With Brainpower - LeetCode javascript solutions
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 0and3.
+- Solve question 0: Earn 3 points, will be unable to solve the next2 questions
+- Unable to solve questions 1and2
+- Solve question 3: Earn 2 points
+Total points earned: 3 + 2 = 5. There isno other way to earn 5or 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 1and4.
+- Skip question 0
+- Solve question 1: Earn 2 points, will be unable to solve the next2 questions
+- Unable to solve questions 2and3
+- Solve question 4: Earn 5 points
+Total points earned: 2 + 5 = 7. There isno other way to earn 7or more points.
+
\ No newline at end of file
diff --git a/docs/problem/sort-array-by-parity.html b/docs/problem/sort-array-by-parity.html
new file mode 100644
index 0000000..e55d995
--- /dev/null
+++ b/docs/problem/sort-array-by-parity.html
@@ -0,0 +1,51 @@
+Sort Array By Parity - LeetCode javascript solutions
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;
+ } elseif (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++);
+ } elseif (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).
+
\ No newline at end of file
diff --git a/docs/problem/sort-list.html b/docs/problem/sort-list.html
new file mode 100644
index 0000000..de12d64
--- /dev/null
+++ b/docs/problem/sort-list.html
@@ -0,0 +1,65 @@
+Sort List - LeetCode javascript solutions
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;
+ } elseif (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).
+
\ No newline at end of file
diff --git a/docs/problem/sort-vowels-in-a-string.html b/docs/problem/sort-vowels-in-a-string.html
new file mode 100644
index 0000000..49d9111
--- /dev/null
+++ b/docs/problem/sort-vowels-in-a-string.html
@@ -0,0 +1,58 @@
+Sort Vowels in a String - LeetCode javascript solutions
Given a 0-indexed string s, permutes 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, andthe consonants remain inthe 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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/soup-servings.html b/docs/problem/soup-servings.html
new file mode 100644
index 0000000..658890b
--- /dev/null
+++ b/docs/problem/soup-servings.html
@@ -0,0 +1,66 @@
+Soup Servings - LeetCode javascript solutions
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 thefirsttwo operations, A will become emptyfirst.
+For thethird operation, A and B will become emptyatthe same time.
+For thefourth operation, B will become emptyfirst.
+So the total probability of A becoming emptyfirst plus half the probability that A and B become emptyatthe 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
+
/**
+ * @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))) {
+ return1;
+ }
+ }
+ return solve(m, m, dp);
+};
+
+var solve = function(a, b, dp) {
+ if (a <= 0 && b <= 0) return0.5;
+ if (a <= 0) return1;
+ if (b <= 0) return0;
+ 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).
+
\ No newline at end of file
diff --git a/docs/problem/special-positions-in-a-binary-matrix.html b/docs/problem/special-positions-in-a-binary-matrix.html
new file mode 100644
index 0000000..626bb6b
--- /dev/null
+++ b/docs/problem/special-positions-in-a-binary-matrix.html
@@ -0,0 +1,64 @@
+Special Positions in a Binary Matrix - LeetCode javascript solutions
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:
+
+
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:
+
+
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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/spiral-matrix-ii.html b/docs/problem/spiral-matrix-ii.html
new file mode 100644
index 0000000..e4811df
--- /dev/null
+++ b/docs/problem/spiral-matrix-ii.html
@@ -0,0 +1,47 @@
+Spiral Matrix II - LeetCode javascript solutions
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/split-a-string-in-balanced-strings.html b/docs/problem/split-a-string-in-balanced-strings.html
new file mode 100644
index 0000000..e6e36c8
--- /dev/null
+++ b/docs/problem/split-a-string-in-balanced-strings.html
@@ -0,0 +1,62 @@
+Split a String in Balanced Strings - LeetCode javascript solutions
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 splitinto"RL", "RRLL", "RL", "RL", each substring contains same numberof'L'and'R'.
+
+
Example 2:
+
Input: s = "RLRRRLLRLL"
+Output: 2
+Explanation: s can be splitinto"RL", "RRRLLRLL", each substring contains same numberof'L'and'R'.
+Note that s cannot be splitinto"RL", "RR", "RL", "LR", "LL", because the2nd and5th substrings are not balanced.
+
+
Example 3:
+
Input: s = "LLLLRRRR"
+Output:1
+Explanation: s can besplit into "LLLLRRRR".
+
+
+Constraints:
+
+
2 <= s.length <= 1000
+
s[i] is either 'L' or 'R'.
+
s is a balanced string.
+
+
Solution
+
/**
+ * @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).
+
\ 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
new file mode 100644
index 0000000..6bdb8e1
--- /dev/null
+++ b/docs/problem/split-array-with-same-average.html
@@ -0,0 +1,37 @@
+Split Array With Same Average - LeetCode javascript solutions
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.
+
\ No newline at end of file
diff --git a/docs/problem/split-linked-list-in-parts.html b/docs/problem/split-linked-list-in-parts.html
new file mode 100644
index 0000000..d228d29
--- /dev/null
+++ b/docs/problem/split-linked-list-in-parts.html
@@ -0,0 +1,90 @@
+Split Linked List in Parts - LeetCode javascript solutions
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:
+
+
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:
+
+
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 inputhas been split into consecutive parts with size difference at most 1, andearlier parts are a larger size than the later parts.
+
+
+Constraints:
+
+
The number of nodes in the list is in the range [0, 1000].
\ No newline at end of file
diff --git a/docs/problem/sqrtx.html b/docs/problem/sqrtx.html
new file mode 100644
index 0000000..4b41355
--- /dev/null
+++ b/docs/problem/sqrtx.html
@@ -0,0 +1,43 @@
+Sqrt(x) - LeetCode javascript solutions
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 of8is2.82842..., andsince
+ the decimal part is truncated, 2is 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;
+ } elseif ((mid + 1) > x / (mid + 1)) {
+ return mid;
+ } else {
+ left = mid + 1;
+ }
+ }
+};
+
+
Explain:
+
nope.
+
Complexity:
+
+
Time complexity : O(log(n)).
+
Space complexity : O(1).
+
\ No newline at end of file
diff --git a/docs/problem/steps-to-make-array-non-decreasing.html b/docs/problem/steps-to-make-array-non-decreasing.html
new file mode 100644
index 0000000..4547545
--- /dev/null
+++ b/docs/problem/steps-to-make-array-non-decreasing.html
@@ -0,0 +1,48 @@
+Steps to Make Array Non-decreasing - LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/problem/string-compression-ii.html b/docs/problem/string-compression-ii.html
new file mode 100644
index 0000000..273c6ac
--- /dev/null
+++ b/docs/problem/string-compression-ii.html
@@ -0,0 +1,69 @@
+String Compression II - LeetCode javascript solutions
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 mostk 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"oflength6. Deleting anyofthecharacters'a'or'c' would at most decrease thelengthofthe compressed stringto5, for instance delete2'a'then we will have s = "abcccd" which compressed is abc3d. Therefore, the optimal way is todelete'b'and'd', thenthe compressed versionof s will be "a3c3"oflength4.
+
+
Example 2:
+
Input: s = "aabbaa", k = 2
+Output: 2
+Explanation: If we delete both 'b'characters, the resulting compressed string would be "a4"oflength2.
+
+
Example 3:
+
Input: s = "aaaaaaaaaaa", k = 0
+Output:3
+Explanation: Since kis zero, we cannot delete anything. The compressed stringis"a11" of length 3.
+
+
+Constraints:
+
+
1 <= s.length <= 100
+
0 <= k <= s.length
+
s contains only lowercase English letters.
+
+
Solution
+
/**
+ * @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) returnNumber.MAX_SAFE_INTEGER;
+ if (i === s.length - k) return0;
+
+ 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).
+
\ No newline at end of file
diff --git a/docs/problem/string-to-integer-atoi.html b/docs/problem/string-to-integer-atoi.html
new file mode 100644
index 0000000..707c0ec
--- /dev/null
+++ b/docs/problem/string-to-integer-atoi.html
@@ -0,0 +1,75 @@
+String to Integer (atoi) - LeetCode javascript solutions
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.
+ Thentakeas many numerical digits as possible, which gets 42.
+
+
Example 3:
+
Input: "4193 with words"
+Output: 4193
+Explanation: Conversion stops at digit '3'asthe next character is nota numerical digit.
+
+
Example 4:
+
Input: "words and 987"
+Output: 0
+Explanation: The first non-whitespace characteris 'w', which isnot a numerical
+ digit or a +/- sign. Therefore no valid conversion could be performed.
+
+
Example 5:
+
Input: "-91283472332"
+Output: -2147483648
+Explanation: The number "-91283472332"isoutof the rangeof a 32-bitsignedinteger.
+ 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).
+
\ No newline at end of file
diff --git a/docs/problem/string-without-aaa-or-bbb.html b/docs/problem/string-without-aaa-or-bbb.html
new file mode 100644
index 0000000..14db4d5
--- /dev/null
+++ b/docs/problem/string-without-aaa-or-bbb.html
@@ -0,0 +1,54 @@
+String Without AAA or BBB - LeetCode javascript solutions
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
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/subarray-sum-equals-k.html b/docs/problem/subarray-sum-equals-k.html
new file mode 100644
index 0000000..99c5492
--- /dev/null
+++ b/docs/problem/subarray-sum-equals-k.html
@@ -0,0 +1,42 @@
+Subarray Sum Equals K - LeetCode javascript solutions
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).
+
\ No newline at end of file
diff --git a/docs/problem/subsets-ii.html b/docs/problem/subsets-ii.html
new file mode 100644
index 0000000..56b924c
--- /dev/null
+++ b/docs/problem/subsets-ii.html
@@ -0,0 +1,46 @@
+Subsets II - LeetCode javascript solutions
/**
+ * @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 :
+
\ No newline at end of file
diff --git a/docs/problem/subsets.html b/docs/problem/subsets.html
new file mode 100644
index 0000000..6cdb0d2
--- /dev/null
+++ b/docs/problem/subsets.html
@@ -0,0 +1,49 @@
+Subsets - LeetCode javascript solutions
/**
+ * @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 :
+
\ 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
new file mode 100644
index 0000000..b78ab0e
--- /dev/null
+++ b/docs/problem/substring-with-concatenation-of-all-words.html
@@ -0,0 +1,61 @@
+Substring with Concatenation of All Words - LeetCode javascript solutions
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 0and9 are "barfoor"and"foobar" respectively.
+The output order doesnot 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).
+
\ No newline at end of file
diff --git a/docs/problem/sudoku-solver.html b/docs/problem/sudoku-solver.html
new file mode 100644
index 0000000..9e9ccbc
--- /dev/null
+++ b/docs/problem/sudoku-solver.html
@@ -0,0 +1,65 @@
+Sudoku Solver - LeetCode javascript solutions
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)) {
+ returntrue;
+ } else {
+ board[i][j] = '.';
+ }
+ }
+ }
+ returnfalse;
+ }
+ }
+ returntrue;
+};
+
+var isValid = function (board, i, j, num) {
+ for (var k = 0; k < 9; k++) {
+ if (board[i][k] === num) returnfalse;
+ if (board[k][j] === num) returnfalse;
+ if (board[Math.floor(i / 3) * 3 + Math.floor(k / 3)][Math.floor(j / 3) * 3 + (k % 3)] === num) returnfalse;
+ }
+ returntrue;
+};
+
+
Explain:
+
dfs:
+
遍历每个点,尝试填入 1~9 的数字,判断是否可以,不行就回滚,直到可以。
+
Complexity:
+
+
Time complexity : O(9^n). n 为格子数。
+
Space complexity : O(1).
+
\ No newline at end of file
diff --git a/docs/problem/sum-of-absolute-differences-in-a-sorted-array.html b/docs/problem/sum-of-absolute-differences-in-a-sorted-array.html
new file mode 100644
index 0000000..937ac72
--- /dev/null
+++ b/docs/problem/sum-of-absolute-differences-in-a-sorted-array.html
@@ -0,0 +1,59 @@
+Sum of Absolute Differences in a Sorted Array - LeetCode javascript solutions
1685. Sum of Absolute Differences in a Sorted Array
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).
\ No newline at end of file
diff --git a/docs/problem/sum-of-subarray-minimums.html b/docs/problem/sum-of-subarray-minimums.html
new file mode 100644
index 0000000..43f63d6
--- /dev/null
+++ b/docs/problem/sum-of-subarray-minimums.html
@@ -0,0 +1,61 @@
+Sum of Subarray Minimums - LeetCode javascript solutions
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 modulo109 + 7.
/**
+ * @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).
+
\ 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
new file mode 100644
index 0000000..50c7664
--- /dev/null
+++ b/docs/problem/sum-root-to-leaf-numbers.html
@@ -0,0 +1,61 @@
+Sum Root to Leaf Numbers - LeetCode javascript solutions
Input: [4,9,0,5,1]
+ 4
+ / \
+ 90
+ / \
+51
+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).
+
\ No newline at end of file
diff --git a/docs/problem/surrounded-regions.html b/docs/problem/surrounded-regions.html
new file mode 100644
index 0000000..94caba4
--- /dev/null
+++ b/docs/problem/surrounded-regions.html
@@ -0,0 +1,58 @@
+Surrounded Regions - LeetCode javascript solutions
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:
+
XXXX
+X O O X
+XX O X
+X O XX
+
+
After running your function, the board should be:
+
XXXX
+XXXX
+XXXX
+X O XX
+
+
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';
+ elseif (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).
+
\ No newline at end of file
diff --git a/docs/problem/swap-nodes-in-pairs.html b/docs/problem/swap-nodes-in-pairs.html
new file mode 100644
index 0000000..e5abb3a
--- /dev/null
+++ b/docs/problem/swap-nodes-in-pairs.html
@@ -0,0 +1,49 @@
+Swap Nodes in Pairs - LeetCode javascript solutions
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).
+
\ No newline at end of file
diff --git a/docs/problem/swapping-nodes-in-a-linked-list.html b/docs/problem/swapping-nodes-in-a-linked-list.html
new file mode 100644
index 0000000..8fac388
--- /dev/null
+++ b/docs/problem/swapping-nodes-in-a-linked-list.html
@@ -0,0 +1,59 @@
+Swapping Nodes in a Linked List - LeetCode javascript solutions
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:
+
+
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
+
/**
+ * 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) {
+ returnnull;
+ }
+ 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).
+
\ No newline at end of file
diff --git a/docs/problem/symmetric-tree.html b/docs/problem/symmetric-tree.html
new file mode 100644
index 0000000..00769ef
--- /dev/null
+++ b/docs/problem/symmetric-tree.html
@@ -0,0 +1,92 @@
+Symmetric Tree - LeetCode javascript solutions
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.
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.
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/the-number-of-the-smallest-unoccupied-chair.html b/docs/problem/the-number-of-the-smallest-unoccupied-chair.html
new file mode 100644
index 0000000..46ac9e8
--- /dev/null
+++ b/docs/problem/the-number-of-the-smallest-unoccupied-chair.html
@@ -0,0 +1,101 @@
+The Number of the Smallest Unoccupied Chair - LeetCode javascript solutions
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**.
/**
+ * @param {number[][]} times
+ * @param {number} targetFriend
+ * @return {number}
+ */
+var smallestChair = function(times, targetFriend) {
+ var emptyChairs = newSet();
+ 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) {
+ returnArray.from(list).sort((a, b) => a - b)[0];
+};
+
+
Explain:
+
nope.
+
Complexity:
+
+
Time complexity : O(n^2).
+
Space complexity : O(n).
+
\ No newline at end of file
diff --git a/docs/problem/transpose-matrix.html b/docs/problem/transpose-matrix.html
new file mode 100644
index 0000000..0724b36
--- /dev/null
+++ b/docs/problem/transpose-matrix.html
@@ -0,0 +1,46 @@
+Transpose Matrix - LeetCode javascript solutions
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/trapping-rain-water.html b/docs/problem/trapping-rain-water.html
new file mode 100644
index 0000000..aaf20da
--- /dev/null
+++ b/docs/problem/trapping-rain-water.html
@@ -0,0 +1,44 @@
+Trapping Rain Water - LeetCode javascript solutions
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).
+
\ No newline at end of file
diff --git a/docs/problem/triangle.html b/docs/problem/triangle.html
new file mode 100644
index 0000000..271f930
--- /dev/null
+++ b/docs/problem/triangle.html
@@ -0,0 +1,65 @@
+Triangle - LeetCode javascript solutions
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) return0;
+
+ 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];
+
+ returnMath.min(left, right);
+};
+
+
Explain:
+
动态规划:
+
dp[i][j] 记录到达 i 行 j 列的点的最小和
+
+
每个点可以由上一行的两个点(或只有一个点)到达,它的值只与这两个点有关
+
到达某个点的最小和 = min(上一行左边点最小和, 上一行右边点最小和) + 当前点的数值
+
最后找出最后一行的最小值就好
+
+
优化:其实dp只要保留上一行的值就好,我这里保留了所有行的值,可以用滚动数组
+
Complexity:
+
+
Time complexity : O(m*n).
+
Space complexity : O(m*n).
+
\ 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
new file mode 100644
index 0000000..d579bc1
--- /dev/null
+++ b/docs/problem/trim-a-binary-search-tree.html
@@ -0,0 +1,66 @@
+Trim a Binary Search Tree - LeetCode javascript solutions
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.
\ 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
new file mode 100644
index 0000000..bea1d66
--- /dev/null
+++ b/docs/problem/two-sum-ii-input-array-is-sorted.html
@@ -0,0 +1,42 @@
+Two Sum II - Input array is sorted - LeetCode javascript solutions
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 2and7 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];
+ } elseif (sum > target) {
+ right--;
+ } else {
+ left++;
+ }
+ }
+};
+
+
Explain:
+
nope.
+
Complexity:
+
+
Time complexity : O(n).
+
Space complexity : O(1).
+
\ No newline at end of file
diff --git a/docs/problem/two-sum.html b/docs/problem/two-sum.html
new file mode 100644
index 0000000..bdd3a74
--- /dev/null
+++ b/docs/problem/two-sum.html
@@ -0,0 +1,31 @@
+Two Sum - LeetCode javascript solutions
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/ugly-number-ii.html b/docs/problem/ugly-number-ii.html
new file mode 100644
index 0000000..e67c3d5
--- /dev/null
+++ b/docs/problem/ugly-number-ii.html
@@ -0,0 +1,46 @@
+Ugly Number II - LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/problem/ugly-number.html b/docs/problem/ugly-number.html
new file mode 100644
index 0000000..b940db0
--- /dev/null
+++ b/docs/problem/ugly-number.html
@@ -0,0 +1,50 @@
+Ugly Number - LeetCode javascript solutions
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: 14isnot ugly sinceit 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) returnfalse;
+ if (num === 1) returntrue;
+
+ 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).
+
\ 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
new file mode 100644
index 0000000..8c20f30
--- /dev/null
+++ b/docs/problem/unique-binary-search-trees-ii.html
@@ -0,0 +1,65 @@
+Unique Binary Search Trees II - LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/problem/unique-binary-search-trees.html b/docs/problem/unique-binary-search-trees.html
new file mode 100644
index 0000000..7abd175
--- /dev/null
+++ b/docs/problem/unique-binary-search-trees.html
@@ -0,0 +1,37 @@
+Unique Binary Search Trees - LeetCode javascript solutions
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.
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/unique-number-of-occurrences.html b/docs/problem/unique-number-of-occurrences.html
new file mode 100644
index 0000000..fdbe68f
--- /dev/null
+++ b/docs/problem/unique-number-of-occurrences.html
@@ -0,0 +1,48 @@
+Unique Number of Occurrences - LeetCode javascript solutions
/**
+ * @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]]]) returnfalse;
+ occureMap[numMap[nums[j]]] = true;
+ }
+ returntrue;
+};
+
+
Explain:
+
nope.
+
Complexity:
+
+
Time complexity : O(n).
+
Space complexity : O(n).
+
\ No newline at end of file
diff --git a/docs/problem/unique-paths-ii.html b/docs/problem/unique-paths-ii.html
new file mode 100644
index 0000000..e5e69f5
--- /dev/null
+++ b/docs/problem/unique-paths-ii.html
@@ -0,0 +1,62 @@
+Unique Paths II - LeetCode javascript solutions
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) return0;
+
+ 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];
+};
+
\ No newline at end of file
diff --git a/docs/problem/unique-paths-iii.html b/docs/problem/unique-paths-iii.html
new file mode 100644
index 0000000..dfa8680
--- /dev/null
+++ b/docs/problem/unique-paths-iii.html
@@ -0,0 +1,92 @@
+Unique Paths III - LeetCode javascript solutions
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:
+
+
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:
+
+
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:
+
+
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
+
/**
+ * @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];
+ elseif (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;
+ } elseif (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).
+
\ No newline at end of file
diff --git a/docs/problem/unique-paths.html b/docs/problem/unique-paths.html
new file mode 100644
index 0000000..4e4d58d
--- /dev/null
+++ b/docs/problem/unique-paths.html
@@ -0,0 +1,49 @@
+Unique Paths - LeetCode javascript solutions
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) return0;
+ 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];
+ elseif (j > 0 && i === 0) dp[i][j] = dp[i][j - 1];
+ elseif (j === 0 && i > 0) dp[i][j] = dp[i - 1][j];
+ else dp[i][j] = 1;
+ }
+ }
+ return dp[m - 1][n - 1];
+};
+
/**
+ * @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).
+
\ No newline at end of file
diff --git a/docs/problem/valid-number.html b/docs/problem/valid-number.html
new file mode 100644
index 0000000..0a040ef
--- /dev/null
+++ b/docs/problem/valid-number.html
@@ -0,0 +1,65 @@
+Valid Number - LeetCode javascript solutions
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';
+ } elseif (str === '+' || str === '-') {
+ type = 'sign';
+ } elseif (str === ' ') {
+ type = 'blank';
+ } else {
+ type = str;
+ }
+ if (state[currentState][type] === undefined) {
+ returnfalse;
+ } else {
+ currentState = state[currentState][type];
+ }
+ }
+ if (validState.indexOf(currentState) === -1) {
+ returnfalse;
+ } else {
+ returntrue;
+ }
+};
+
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 Example1, 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 '.'.
\ No newline at end of file
diff --git a/docs/problem/validate-binary-search-tree.html b/docs/problem/validate-binary-search-tree.html
new file mode 100644
index 0000000..156cd7c
--- /dev/null
+++ b/docs/problem/validate-binary-search-tree.html
@@ -0,0 +1,95 @@
+Validate Binary Search Tree - LeetCode javascript solutions
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
+ /\
+ 13
+Output:true
+
+
Example 2:
+
5
+ / \
+ 14
+ / \
+ 36
+Output: false
+Explanation: The input is: [5,1,4,null,null,3,6]. The root node's value
+ is5 but its right child's value is4.
+
/**
+ * 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) returnfalse;
+
+ prev = now;
+ now = now.right;
+ }
+
+ returntrue;
+};
+
+
Explain:
+
nope.
+
Complexity:
+
+
Time complexity : O(n). n 为节点数。
+
Space complexity : O(n).
+
\ No newline at end of file
diff --git a/docs/problem/validate-binary-tree-nodes.html b/docs/problem/validate-binary-tree-nodes.html
new file mode 100644
index 0000000..1cf3881
--- /dev/null
+++ b/docs/problem/validate-binary-tree-nodes.html
@@ -0,0 +1,58 @@
+Validate Binary Tree Nodes - LeetCode javascript solutions
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.
\ No newline at end of file
diff --git a/docs/problem/widest-vertical-area-between-two-points-containing-no-points.html b/docs/problem/widest-vertical-area-between-two-points-containing-no-points.html
new file mode 100644
index 0000000..def631d
--- /dev/null
+++ b/docs/problem/widest-vertical-area-between-two-points-containing-no-points.html
@@ -0,0 +1,45 @@
+Widest Vertical Area Between Two Points Containing No Points - LeetCode javascript solutions
1637. Widest Vertical Area Between Two Points Containing No Points
Given npoints 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:
+
+
+
Input: points = [[8,7],[9,9],[7,4],[9,7]]
+Output: 1
+Explanation: Both the red and the blue area are optimal.
+
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] !== '*') returnfalse;
+ }
+ returntrue;
+ }
+
+ if (sNow === pNow || pNow === '?') {
+ res = test(s, p, sIndex + 1, pIndex + 1, dp);
+ } elseif (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).
+
\ No newline at end of file
diff --git a/docs/problem/word-break-ii.html b/docs/problem/word-break-ii.html
new file mode 100644
index 0000000..7e716d0
--- /dev/null
+++ b/docs/problem/word-break-ii.html
@@ -0,0 +1,86 @@
+Word Break II - LeetCode javascript solutions
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.
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.
+
/**
+ * @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) returntrue;
+
+ 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).
+
\ No newline at end of file
diff --git a/docs/problem/word-ladder-ii.html b/docs/problem/word-ladder-ii.html
new file mode 100644
index 0000000..c9cc896
--- /dev/null
+++ b/docs/problem/word-ladder-ii.html
@@ -0,0 +1,139 @@
+Word Ladder II - LeetCode javascript solutions
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.
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 = newSet(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++;
+ }
+
+ return0;
+};
+
+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).
+
\ No newline at end of file
diff --git a/docs/problem/word-search.html b/docs/problem/word-search.html
new file mode 100644
index 0000000..83e02b8
--- /dev/null
+++ b/docs/problem/word-search.html
@@ -0,0 +1,117 @@
+Word Search - LeetCode javascript solutions
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", returntrue.
+Given word = "SEE", returntrue.
+Given word = "ABCB", returnfalse.
+
+
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) returnfalse;
+
+ 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)) returntrue;
+ }
+ }
+
+ returnfalse;
+};
+
+var helper = function (board, word, m, n, k, visited) {
+ if (k === word.length) returntrue;
+ if (m < 0 || m >= board.length) returnfalse;
+ if (n < 0 || n >= board[m].length) returnfalse;
+ if (visited[m][n]) returnfalse;
+ if (board[m][n] !== word[k]) returnfalse;
+
+ 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). n 为 board 字符总数, k 为 word 长度。
+
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) returnfalse;
+
+ for (var i = 0; i < len1; i++) {
+ for (var j = 0; j < len2; j++) {
+ if (helper(board, word, i, j, 0)) returntrue;
+ }
+ }
+
+ returnfalse;
+};
+
+var helper = function (board, word, m, n, k) {
+ if (k === word.length) returntrue;
+ if (m < 0 || m >= board.length) returnfalse;
+ if (n < 0 || n >= board[m].length) returnfalse;
+ if (board[m][n] !== word[k]) returnfalse;
+
+ 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). n 为 board 字符总数, k 为 word 长度。
+
Space complexity : O(1).
+
\ No newline at end of file
diff --git a/docs/problem/zigzag-conversion.html b/docs/problem/zigzag-conversion.html
new file mode 100644
index 0000000..1d1c074
--- /dev/null
+++ b/docs/problem/zigzag-conversion.html
@@ -0,0 +1,54 @@
+ZigZag Conversion - LeetCode javascript solutions
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 II 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:
+
stringconvert(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('');
+};
+
\ No newline at end of file
diff --git a/docs/tag/array/page/2.html b/docs/tag/array/page/2.html
new file mode 100644
index 0000000..1842d7d
--- /dev/null
+++ b/docs/tag/array/page/2.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/array/page/3.html b/docs/tag/array/page/3.html
new file mode 100644
index 0000000..39bad77
--- /dev/null
+++ b/docs/tag/array/page/3.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/array/page/4.html b/docs/tag/array/page/4.html
new file mode 100644
index 0000000..4c56a33
--- /dev/null
+++ b/docs/tag/array/page/4.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/array/page/5.html b/docs/tag/array/page/5.html
new file mode 100644
index 0000000..195a959
--- /dev/null
+++ b/docs/tag/array/page/5.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/array/page/6.html b/docs/tag/array/page/6.html
new file mode 100644
index 0000000..ad706ff
--- /dev/null
+++ b/docs/tag/array/page/6.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/array/page/7.html b/docs/tag/array/page/7.html
new file mode 100644
index 0000000..80a5315
--- /dev/null
+++ b/docs/tag/array/page/7.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/backtracking/index.html b/docs/tag/backtracking/index.html
new file mode 100644
index 0000000..3d4608a
--- /dev/null
+++ b/docs/tag/backtracking/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/binary-indexed-tree/index.html b/docs/tag/binary-indexed-tree/index.html
new file mode 100644
index 0000000..978ffab
--- /dev/null
+++ b/docs/tag/binary-indexed-tree/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/binary-search-tree/index.html b/docs/tag/binary-search-tree/index.html
new file mode 100644
index 0000000..e0823db
--- /dev/null
+++ b/docs/tag/binary-search-tree/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/binary-search/index.html b/docs/tag/binary-search/index.html
new file mode 100644
index 0000000..10b5989
--- /dev/null
+++ b/docs/tag/binary-search/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/binary-search/page/2.html b/docs/tag/binary-search/page/2.html
new file mode 100644
index 0000000..36fd80e
--- /dev/null
+++ b/docs/tag/binary-search/page/2.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/binary-tree/index.html b/docs/tag/binary-tree/index.html
new file mode 100644
index 0000000..e1e7fd2
--- /dev/null
+++ b/docs/tag/binary-tree/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/bit-manipulation/index.html b/docs/tag/bit-manipulation/index.html
new file mode 100644
index 0000000..b7e70a4
--- /dev/null
+++ b/docs/tag/bit-manipulation/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/bitmask/index.html b/docs/tag/bitmask/index.html
new file mode 100644
index 0000000..f13aa9e
--- /dev/null
+++ b/docs/tag/bitmask/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/brainteaser/index.html b/docs/tag/brainteaser/index.html
new file mode 100644
index 0000000..7d74a84
--- /dev/null
+++ b/docs/tag/brainteaser/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/breadth-first-search/index.html b/docs/tag/breadth-first-search/index.html
new file mode 100644
index 0000000..8fde1ac
--- /dev/null
+++ b/docs/tag/breadth-first-search/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/combinatorics/index.html b/docs/tag/combinatorics/index.html
new file mode 100644
index 0000000..6699f22
--- /dev/null
+++ b/docs/tag/combinatorics/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/counting-sort/index.html b/docs/tag/counting-sort/index.html
new file mode 100644
index 0000000..db93ce6
--- /dev/null
+++ b/docs/tag/counting-sort/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/counting/index.html b/docs/tag/counting/index.html
new file mode 100644
index 0000000..a667cfb
--- /dev/null
+++ b/docs/tag/counting/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/data-stream/index.html b/docs/tag/data-stream/index.html
new file mode 100644
index 0000000..0e63ff6
--- /dev/null
+++ b/docs/tag/data-stream/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/database/index.html b/docs/tag/database/index.html
new file mode 100644
index 0000000..038c012
--- /dev/null
+++ b/docs/tag/database/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/depth-first-search/index.html b/docs/tag/depth-first-search/index.html
new file mode 100644
index 0000000..ee94c3c
--- /dev/null
+++ b/docs/tag/depth-first-search/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/depth-first-search/page/2.html b/docs/tag/depth-first-search/page/2.html
new file mode 100644
index 0000000..79bc260
--- /dev/null
+++ b/docs/tag/depth-first-search/page/2.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/design/index.html b/docs/tag/design/index.html
new file mode 100644
index 0000000..678b428
--- /dev/null
+++ b/docs/tag/design/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/divide-and-conquer/index.html b/docs/tag/divide-and-conquer/index.html
new file mode 100644
index 0000000..6520a1a
--- /dev/null
+++ b/docs/tag/divide-and-conquer/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/dynamic-programming/index.html b/docs/tag/dynamic-programming/index.html
new file mode 100644
index 0000000..d49f9b6
--- /dev/null
+++ b/docs/tag/dynamic-programming/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/dynamic-programming/page/2.html b/docs/tag/dynamic-programming/page/2.html
new file mode 100644
index 0000000..499f2c2
--- /dev/null
+++ b/docs/tag/dynamic-programming/page/2.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/dynamic-programming/page/3.html b/docs/tag/dynamic-programming/page/3.html
new file mode 100644
index 0000000..1a22516
--- /dev/null
+++ b/docs/tag/dynamic-programming/page/3.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/enumeration/index.html b/docs/tag/enumeration/index.html
new file mode 100644
index 0000000..22c44c6
--- /dev/null
+++ b/docs/tag/enumeration/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/eulerian-circuit/index.html b/docs/tag/eulerian-circuit/index.html
new file mode 100644
index 0000000..5531195
--- /dev/null
+++ b/docs/tag/eulerian-circuit/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/game-theory/index.html b/docs/tag/game-theory/index.html
new file mode 100644
index 0000000..fbd67ec
--- /dev/null
+++ b/docs/tag/game-theory/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/geometry/index.html b/docs/tag/geometry/index.html
new file mode 100644
index 0000000..adfddcc
--- /dev/null
+++ b/docs/tag/geometry/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/graph/index.html b/docs/tag/graph/index.html
new file mode 100644
index 0000000..c603bbc
--- /dev/null
+++ b/docs/tag/graph/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/greedy/index.html b/docs/tag/greedy/index.html
new file mode 100644
index 0000000..e5b772e
--- /dev/null
+++ b/docs/tag/greedy/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/greedy/page/2.html b/docs/tag/greedy/page/2.html
new file mode 100644
index 0000000..f928c1a
--- /dev/null
+++ b/docs/tag/greedy/page/2.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/hash-function/index.html b/docs/tag/hash-function/index.html
new file mode 100644
index 0000000..9d39845
--- /dev/null
+++ b/docs/tag/hash-function/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/hash-table/index.html b/docs/tag/hash-table/index.html
new file mode 100644
index 0000000..46c9875
--- /dev/null
+++ b/docs/tag/hash-table/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/hash-table/page/2.html b/docs/tag/hash-table/page/2.html
new file mode 100644
index 0000000..e4c2369
--- /dev/null
+++ b/docs/tag/hash-table/page/2.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/hash-table/page/3.html b/docs/tag/hash-table/page/3.html
new file mode 100644
index 0000000..a33c3e9
--- /dev/null
+++ b/docs/tag/hash-table/page/3.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/heap-priority-queue/index.html b/docs/tag/heap-priority-queue/index.html
new file mode 100644
index 0000000..ab32482
--- /dev/null
+++ b/docs/tag/heap-priority-queue/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/heap/index.html b/docs/tag/heap/index.html
new file mode 100644
index 0000000..4632868
--- /dev/null
+++ b/docs/tag/heap/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/interactive/index.html b/docs/tag/interactive/index.html
new file mode 100644
index 0000000..0bd1ba5
--- /dev/null
+++ b/docs/tag/interactive/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/iterator/index.html b/docs/tag/iterator/index.html
new file mode 100644
index 0000000..b052fcd
--- /dev/null
+++ b/docs/tag/iterator/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/line-sweep/index.html b/docs/tag/line-sweep/index.html
new file mode 100644
index 0000000..8e8758f
--- /dev/null
+++ b/docs/tag/line-sweep/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/linked-list/index.html b/docs/tag/linked-list/index.html
new file mode 100644
index 0000000..3211d67
--- /dev/null
+++ b/docs/tag/linked-list/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/math/index.html b/docs/tag/math/index.html
new file mode 100644
index 0000000..660ef1b
--- /dev/null
+++ b/docs/tag/math/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/math/page/2.html b/docs/tag/math/page/2.html
new file mode 100644
index 0000000..8bafc21
--- /dev/null
+++ b/docs/tag/math/page/2.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/math/page/3.html b/docs/tag/math/page/3.html
new file mode 100644
index 0000000..63e005c
--- /dev/null
+++ b/docs/tag/math/page/3.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/matrix/index.html b/docs/tag/matrix/index.html
new file mode 100644
index 0000000..4a7e5ac
--- /dev/null
+++ b/docs/tag/matrix/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/memoization/index.html b/docs/tag/memoization/index.html
new file mode 100644
index 0000000..03ca252
--- /dev/null
+++ b/docs/tag/memoization/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/merge-sort/index.html b/docs/tag/merge-sort/index.html
new file mode 100644
index 0000000..e8f2965
--- /dev/null
+++ b/docs/tag/merge-sort/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/minimum-spanning-tree/index.html b/docs/tag/minimum-spanning-tree/index.html
new file mode 100644
index 0000000..313c99c
--- /dev/null
+++ b/docs/tag/minimum-spanning-tree/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/monotonic-queue/index.html b/docs/tag/monotonic-queue/index.html
new file mode 100644
index 0000000..c635f3c
--- /dev/null
+++ b/docs/tag/monotonic-queue/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/monotonic-stack/index.html b/docs/tag/monotonic-stack/index.html
new file mode 100644
index 0000000..6fbac74
--- /dev/null
+++ b/docs/tag/monotonic-stack/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/number-theory/index.html b/docs/tag/number-theory/index.html
new file mode 100644
index 0000000..e9de708
--- /dev/null
+++ b/docs/tag/number-theory/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/ordered-set/index.html b/docs/tag/ordered-set/index.html
new file mode 100644
index 0000000..6302564
--- /dev/null
+++ b/docs/tag/ordered-set/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/prefix-sum/index.html b/docs/tag/prefix-sum/index.html
new file mode 100644
index 0000000..6286d47
--- /dev/null
+++ b/docs/tag/prefix-sum/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/probability-and-statistics/index.html b/docs/tag/probability-and-statistics/index.html
new file mode 100644
index 0000000..36bfacb
--- /dev/null
+++ b/docs/tag/probability-and-statistics/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/queue/index.html b/docs/tag/queue/index.html
new file mode 100644
index 0000000..8204826
--- /dev/null
+++ b/docs/tag/queue/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/randomized/index.html b/docs/tag/randomized/index.html
new file mode 100644
index 0000000..38ce776
--- /dev/null
+++ b/docs/tag/randomized/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/recursion/index.html b/docs/tag/recursion/index.html
new file mode 100644
index 0000000..09cb7a4
--- /dev/null
+++ b/docs/tag/recursion/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/rejection-sampling/index.html b/docs/tag/rejection-sampling/index.html
new file mode 100644
index 0000000..2123000
--- /dev/null
+++ b/docs/tag/rejection-sampling/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/rolling-hash/index.html b/docs/tag/rolling-hash/index.html
new file mode 100644
index 0000000..44e6639
--- /dev/null
+++ b/docs/tag/rolling-hash/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/segment-tree/index.html b/docs/tag/segment-tree/index.html
new file mode 100644
index 0000000..735c091
--- /dev/null
+++ b/docs/tag/segment-tree/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/shortest-path/index.html b/docs/tag/shortest-path/index.html
new file mode 100644
index 0000000..c7de70b
--- /dev/null
+++ b/docs/tag/shortest-path/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/simulation/index.html b/docs/tag/simulation/index.html
new file mode 100644
index 0000000..41dc41d
--- /dev/null
+++ b/docs/tag/simulation/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/sliding-window/index.html b/docs/tag/sliding-window/index.html
new file mode 100644
index 0000000..18a08f1
--- /dev/null
+++ b/docs/tag/sliding-window/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/sort/index.html b/docs/tag/sort/index.html
new file mode 100644
index 0000000..ea33f22
--- /dev/null
+++ b/docs/tag/sort/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/sorting/index.html b/docs/tag/sorting/index.html
new file mode 100644
index 0000000..1ccc59f
--- /dev/null
+++ b/docs/tag/sorting/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/sorting/page/2.html b/docs/tag/sorting/page/2.html
new file mode 100644
index 0000000..94079ec
--- /dev/null
+++ b/docs/tag/sorting/page/2.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/stack/index.html b/docs/tag/stack/index.html
new file mode 100644
index 0000000..7cadc8a
--- /dev/null
+++ b/docs/tag/stack/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/stack/page/2.html b/docs/tag/stack/page/2.html
new file mode 100644
index 0000000..655ccfc
--- /dev/null
+++ b/docs/tag/stack/page/2.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/string-matching/index.html b/docs/tag/string-matching/index.html
new file mode 100644
index 0000000..1b4e877
--- /dev/null
+++ b/docs/tag/string-matching/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/string/index.html b/docs/tag/string/index.html
new file mode 100644
index 0000000..e92232e
--- /dev/null
+++ b/docs/tag/string/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/string/page/2.html b/docs/tag/string/page/2.html
new file mode 100644
index 0000000..8459e80
--- /dev/null
+++ b/docs/tag/string/page/2.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/string/page/3.html b/docs/tag/string/page/3.html
new file mode 100644
index 0000000..5a599da
--- /dev/null
+++ b/docs/tag/string/page/3.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/string/page/4.html b/docs/tag/string/page/4.html
new file mode 100644
index 0000000..b07f245
--- /dev/null
+++ b/docs/tag/string/page/4.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/strongly-connected-component/index.html b/docs/tag/strongly-connected-component/index.html
new file mode 100644
index 0000000..f3e4129
--- /dev/null
+++ b/docs/tag/strongly-connected-component/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/topological-sort/index.html b/docs/tag/topological-sort/index.html
new file mode 100644
index 0000000..0e247d4
--- /dev/null
+++ b/docs/tag/topological-sort/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/tree/index.html b/docs/tag/tree/index.html
new file mode 100644
index 0000000..674d2a8
--- /dev/null
+++ b/docs/tag/tree/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/tree/page/2.html b/docs/tag/tree/page/2.html
new file mode 100644
index 0000000..53eef4a
--- /dev/null
+++ b/docs/tag/tree/page/2.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/trie/index.html b/docs/tag/trie/index.html
new file mode 100644
index 0000000..6f3f2af
--- /dev/null
+++ b/docs/tag/trie/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/two-pointers/index.html b/docs/tag/two-pointers/index.html
new file mode 100644
index 0000000..69d308b
--- /dev/null
+++ b/docs/tag/two-pointers/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/two-pointers/page/2.html b/docs/tag/two-pointers/page/2.html
new file mode 100644
index 0000000..47928d8
--- /dev/null
+++ b/docs/tag/two-pointers/page/2.html
@@ -0,0 +1 @@
+LeetCode javascript solutions
\ No newline at end of file
diff --git a/docs/tag/union-find/index.html b/docs/tag/union-find/index.html
new file mode 100644
index 0000000..f2b2687
--- /dev/null
+++ b/docs/tag/union-find/index.html
@@ -0,0 +1 @@
+LeetCode javascript solutions