Dataset Viewer
QID
int64 1
2.85k
| titleSlug
stringlengths 3
77
| Hints
sequence | Code
stringlengths 80
1.34k
| Body
stringlengths 190
4.55k
| Difficulty
stringclasses 3
values | Topics
sequence | Definitions
stringclasses 14
values | Solutions
sequence |
---|---|---|---|---|---|---|---|---|
1 | two-sum | [
"A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations.",
"So, if we fix one of the numbers, say <code>x</code>, we have to scan the entire array to find the next number <code>y</code> which is <code>value - x</code> where value is the input parameter. Can we change our array somehow so that this search becomes faster?",
"The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?"
] | /**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
}; | Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
Constraints:
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
Only one valid answer exists.
Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity? | Easy | [
"array",
"hash-table"
] | [
"const twoSum = function(nums, target) {\n const myObject = {};\n for (let i = 0; i < nums.length; i++) {\n const complement = target - nums[i];\n if (myObject.hasOwnProperty(complement)) {\n return [myObject[complement], i];\n }\n myObject[nums[i]] = i;\n }\n};"
] |
|
2 | add-two-numbers | [] | /**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var addTwoNumbers = function(l1, l2) {
}; | 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 contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example 1:
Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.
Example 2:
Input: l1 = [0], l2 = [0]
Output: [0]
Example 3:
Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]
Constraints:
The number of nodes in each linked list is in the range [1, 100].
0 <= Node.val <= 9
It is guaranteed that the list represents a number that does not have leading zeros.
| Medium | [
"linked-list",
"math",
"recursion"
] | /**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/ | [
"const addTwoNumbers = function(l1, l2) {\n let res = new ListNode(null)\n let inc = false\n let cur = res\n while(l1 || l2 || inc) {\n const tmp = ((l1 && l1.val) || 0) + ((l2 && l2.val) || 0) + (inc ? 1 : 0)\n if(tmp >= 10) inc = true\n else inc = false\n cur.next = new ListNode(tmp % 10)\n cur = cur.next\n if(l1) l1 = l1.next\n if(l2) l2 = l2.next\n }\n \n return res.next\n};",
"const addTwoNumbers = function(l1, l2) {\n const res = new ListNode(null);\n single(l1, l2, res);\n return res.next;\n};\n\nfunction single(l1, l2, res) {\n let cur;\n let addOne = 0;\n let sum = 0;\n let curVal = 0;\n while (l1 || l2 || addOne) {\n sum = ((l1 && l1.val) || 0) + ((l2 && l2.val) || 0) + addOne;\n if (sum / 10 >= 1) {\n curVal = sum % 10;\n addOne = 1;\n } else {\n curVal = sum;\n addOne = 0;\n }\n\n if (cur) {\n cur = cur.next = new ListNode(curVal);\n } else {\n cur = res.next = new ListNode(curVal);\n }\n\n if (l1) {\n l1 = l1.next;\n }\n if (l2) {\n l2 = l2.next;\n }\n }\n}",
"const addTwoNumbers = function(l1, l2) {\n let extra = false\n const dummy = new ListNode()\n let cur = dummy\n while(l1 || l2) {\n let val = 0\n if(l1) val += l1.val\n if(l2) val += l2.val\n if(extra) val += 1\n \n if(val > 9) {\n extra = true\n val = val % 10\n } else {\n extra = false\n }\n cur.next = new ListNode(val)\n cur = cur.next\n if(l1) l1 = l1.next\n if(l2) l2 = l2.next\n }\n\n if(extra) cur.next = new ListNode(1)\n return dummy.next\n};",
"const addTwoNumbers = function(l1, l2) {\n const dummy = new ListNode(null)\n let cur = dummy, carry = 0\n \n while(l1 || l2) {\n let v = 0\n if(l1 && l2) {\n v = l1.val + l2.val + carry\n l1 = l1.next\n l2 = l2.next\n } else {\n const node = l1 || l2\n v = node.val + carry\n if(l1) l1 = l1.next\n if(l2) l2 = l2.next\n }\n \n cur.next = new ListNode(v % 10)\n cur = cur.next\n if(v >= 10) carry = 1\n else carry = 0\n }\n \n if(carry) cur.next = new ListNode(1)\n \n return dummy.next\n};"
] |
3 | longest-substring-without-repeating-characters | [] | /**
* @param {string} s
* @return {number}
*/
var lengthOfLongestSubstring = function(s) {
}; | Given a string s, find the length of the longest substring without repeating characters.
Example 1:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
Constraints:
0 <= s.length <= 5 * 104
s consists of English letters, digits, symbols and spaces.
| Medium | [
"hash-table",
"string",
"sliding-window"
] | [
"const lengthOfLongestSubstring = function(s) {\n if(s.length < 2) return s.length\n const hash = {}\n let max = 0\n for(let i = 0, j = -1, len = s.length; i < len; i++) {\n const cur = s[i]\n if(hash[cur] != null) j = Math.max(j, hash[cur])\n \n hash[cur] = i\n max = Math.max(max, i - j)\n }\n \n return max\n};",
"const lengthOfLongestSubstring = function(s) {\n // var p=0, q=0; //p: start of the sub, q: end of the queue\n\n //hashmap in js????? Array.indexOf\n const sub = [];\n let max = 0;\n\n for (let i = 0; i < s.length; i++) {\n let index = sub.indexOf(s.charAt(i));\n if (index == -1) {\n sub.push(s.charAt(i));\n // q++;\n } else {\n //find repeat, get index of repeat el, remve all el before that index\n sub = sub.slice(index + 1, sub.length);\n sub.push(s.charAt(i));\n }\n max = Math.max(max, sub.length);\n }\n return max;\n};"
] |
|
4 | median-of-two-sorted-arrays | [] | /**
* @param {number[]} nums1
* @param {number[]} nums2
* @return {number}
*/
var findMedianSortedArrays = function(nums1, nums2) {
}; | Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.
The overall run time complexity should be O(log (m+n)).
Example 1:
Input: nums1 = [1,3], nums2 = [2]
Output: 2.00000
Explanation: merged array = [1,2,3] and median is 2.
Example 2:
Input: nums1 = [1,2], nums2 = [3,4]
Output: 2.50000
Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.
Constraints:
nums1.length == m
nums2.length == n
0 <= m <= 1000
0 <= n <= 1000
1 <= m + n <= 2000
-106 <= nums1[i], nums2[i] <= 106
| Hard | [
"array",
"binary-search",
"divide-and-conquer"
] | [
"const findMedianSortedArrays = function(nums1, nums2) {\n if(nums1.length > nums2.length) return findMedianSortedArrays(nums2, nums1)\n const m = nums1.length, n = nums2.length\n let low = 0, high = m\n while(low <= high) {\n \n const px = Math.floor((low + high) / 2)\n const py = Math.floor(( m + n + 1 ) / 2) - px\n \n const maxLeft1 = px === 0 ? -Infinity : nums1[px - 1]\n const minRight1 = px === m ? Infinity : nums1[px]\n \n const maxLeft2 = py === 0 ? -Infinity : nums2[py - 1]\n const minRight2 = py === n ? Infinity : nums2[py]\n \n if(maxLeft1 <= minRight2 && maxLeft2 <= minRight1) {\n if((m + n) % 2 === 0) {\n return (Math.max(maxLeft1, maxLeft2) + Math.min(minRight1, minRight2)) / 2\n } else {\n return Math.max(maxLeft1, maxLeft2)\n }\n } else if(maxLeft1 > minRight2) {\n high = px - 1 \n } else {\n low = px + 1\n }\n \n }\n};",
"const findMedianSortedArrays = function(A, B) {\n let m = A.length,\n n = B.length;\n\n if (m > n) {\n return findMedianSortedArrays(B, A);\n }\n\n let imin = 0,\n imax = m,\n i,\n j;\n while (imin <= imax) {\n i = (imin + imax) >> 1;\n j = ((m + n + 1) >> 1) - i;\n if (j > 0 && i < m && B[j - 1] > A[i]) {\n imin = i + 1;\n } else if (i > 0 && j < n && A[i - 1] > B[j]) {\n imax = i - 1;\n } else {\n if (i === 0) {\n num1 = B[j - 1];\n } else if (j === 0) {\n num1 = A[i - 1];\n } else {\n num1 = Math.max(A[i - 1], B[j - 1]);\n }\n\n if ((m + n) & 1) {\n return num1;\n }\n\n if (i === m) {\n num2 = B[j];\n } else if (j === n) {\n num2 = A[i];\n } else {\n num2 = Math.min(A[i], B[j]);\n }\n return (num1 + num2) / 2.0;\n }\n }\n};",
"const findMedianSortedArrays = function (nums1, nums2) {\n if (nums1.length > nums2.length) {\n return findMedianSortedArrays(nums2, nums1)\n }\n const x = nums1.length\n const y = nums2.length\n\n let low = 0\n let high = x\n\n while (low <= high) {\n const partX = Math.floor((low + high) / 2)\n const partY = Math.floor((x + y + 1) / 2) - partX\n\n const maxX = partX === 0 ? Number.NEGATIVE_INFINITY : nums1[partX - 1]\n const maxY = partY === 0 ? Number.NEGATIVE_INFINITY : nums2[partY - 1]\n\n const minX =\n partX === nums1.length ? Number.POSITIVE_INFINITY : nums1[partX]\n const minY =\n partY === nums2.length ? Number.POSITIVE_INFINITY : nums2[partY]\n\n if (maxX <= minY && maxY <= minX) {\n const lowMax = Math.max(maxX, maxY)\n\n if ((x + y) % 2 == 1) {\n return Math.max(maxX, maxY)\n } else {\n return (Math.max(maxX, maxY) + Math.min(minX, minY)) / 2\n }\n } else if (maxX < minY) {\n low = partX + 1\n } else {\n high = partX - 1\n }\n }\n}"
] |
|
5 | longest-palindromic-substring | [
"How can we reuse a previously computed palindrome to compute a larger palindrome?",
"If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome?",
"Complexity based hint:</br>\r\nIf we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation."
] | /**
* @param {string} s
* @return {string}
*/
var longestPalindrome = function(s) {
}; | Given a string s, return the longest palindromic substring in s.
Example 1:
Input: s = "babad"
Output: "bab"
Explanation: "aba" is also a valid answer.
Example 2:
Input: s = "cbbd"
Output: "bb"
Constraints:
1 <= s.length <= 1000
s consist of only digits and English letters.
| Medium | [
"string",
"dynamic-programming"
] | [
"const longestPalindrome = function(s) {\n let res = ''\n for(let i = 0, len = s.length; i < len; i++) {\n let s1 = chk(s,i,i), s2 = chk(s,i,i+1)\n if(s1.length > res.length) res = s1\n if(s2.length > res.length) res = s2\n }\n return res\n};\n\nfunction chk(s, i, j) {\n for(; i>= 0 && j < s.length; i--, j++) {\n if(s[i] !== s[j]) break\n }\n return s.slice(i+1, j)\n}",
"const longestPalindrome = function(s) {\n let T = preProcess(s);\n let n = T.length;\n let P = [];\n let C = 0,\n R = 0;\n let i_mirror;\n for (let i = 1; i < n - 1; i++) {\n i_mirror = 2 * C - i; // equals to i' = C - (i-C)\n\n P[i] = R > i ? Math.min(R - i, P[i_mirror]) : 0;\n\n // Attempt to expand palindrome centered at i\n while (T[i + 1 + P[i]] == T[i - 1 - P[i]]) P[i]++;\n\n // If palindrome centered at i expand past R,\n // adjust center based on expanded palindrome.\n if (i + P[i] > R) {\n C = i;\n R = i + P[i];\n }\n }\n\n // Find the maximum element in P.\n let maxLen = 0;\n let centerIndex = 0;\n for (let j = 1; j < n - 1; j++) {\n if (P[j] > maxLen) {\n maxLen = P[j];\n centerIndex = j;\n }\n }\n\n return s.substr((centerIndex - 1 - maxLen) / 2, maxLen);\n};\n\nfunction preProcess(s) {\n let n = s.length;\n if (n === 0) return \"^$\";\n let ret = \"^\";\n for (let i = 0; i < n; i++) ret += \"#\" + s.substr(i, 1);\n\n ret += \"#$\";\n return ret;\n}",
"const longestPalindrome = function(s) {\n const n = s.length\n let res = ''\n for(let i = 0; i < n; i++) {\n const first = chk(s, i, i, n)\n if(first.length > res.length) res = first\n const second = chk(s, i, i + 1, n)\n if(second.length > res.length) res = second\n }\n return res\n};\n\nfunction chk(str, i, j, n) {\n if(j >= n) return str[i]\n let l = i, r = j\n while(l >= 0 && r < n) {\n if(str[l] === str[r]) {\n l--\n r++\n } else {\n return str.slice(l + 1, r)\n }\n }\n if(l < 0) {\n return str.slice(0, r)\n } else {\n return str.slice(l + 1, n)\n }\n}"
] |
|
6 | zigzag-conversion | [] | /**
* @param {string} s
* @param {number} numRows
* @return {string}
*/
var convert = function(s, numRows) {
}; | The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string s, int numRows);
Example 1:
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Example 2:
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:
P I N
A L S I G
Y A H R
P I
Example 3:
Input: s = "A", numRows = 1
Output: "A"
Constraints:
1 <= s.length <= 1000
s consists of English letters (lower-case and upper-case), ',' and '.'.
1 <= numRows <= 1000
| Medium | [
"string"
] | [
"const convert = function(s, numRows) {\n if (numRows === 1) {\n return s;\n }\n let output = \"\";\n for (let i = 1; i <= numRows; i++) {\n let j = i - 1;\n let maxIncrement = 2 * numRows - 2;\n let increment = 2 * numRows - 2 - 2 * j;\n if (increment === 0) {\n increment = maxIncrement;\n } else {\n increment = maxIncrement - increment;\n }\n for (j; j < s.length; j += increment) {\n output += s[j];\n if (maxIncrement !== increment) {\n increment = maxIncrement - increment;\n }\n }\n }\n return output;\n};"
] |
|
7 | reverse-integer | [] | /**
* @param {number} x
* @return {number}
*/
var reverse = function(x) {
}; | Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Example 1:
Input: x = 123
Output: 321
Example 2:
Input: x = -123
Output: -321
Example 3:
Input: x = 120
Output: 21
Constraints:
-231 <= x <= 231 - 1
| Medium | [
"math"
] | [
"const reverse = function (x) {\n let res = 0, tail, newResult\n const low = -Math.pow(2, 31), high = Math.pow(2, 31)\n while(x !== 0) {\n tail = x % 10\n newResult = res * 10 + tail\n // if((newResult - tail) / 10 !== res) return 0\n if(newResult < low || newResult >= high) return 0\n res = newResult\n x = ~~(x / 10)\n }\n \n return res\n};",
"const reverse = function(num) {\n let negative = false;\n let result = 0;\n if (num < 0) {\n negative = true;\n num = Math.abs(num);\n }\n while (num > 0) {\n mod = num % 10; // mod = 3 // mod = 2 // mod\n num = Math.floor(num / 10); // num = 12 // num = 1\n result = result * 10 + mod; // 0 = 0 * 10 + 3 = 0 + 3 = 3 // 3 = 3 * 10 + 2 = 30 + 2 = 32\n }\n if (result > 2147483647) return 0;\n if (negative) return result * -1;\n return result;\n};"
] |
|
8 | string-to-integer-atoi | [] | /**
* @param {string} s
* @return {number}
*/
var myAtoi = function(s) {
}; | Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function).
The algorithm for myAtoi(string s) is as follows:
Read in and ignore any leading whitespace.
Check if the next character (if not already at the end of the string) is '-' or '+'. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present.
Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored.
Convert these digits into an integer (i.e. "123" -> 123, "0032" -> 32). If no digits were read, then the integer is 0. Change the sign as necessary (from step 2).
If the integer is out of the 32-bit signed integer range [-231, 231 - 1], then clamp the integer so that it remains in the range. Specifically, integers less than -231 should be clamped to -231, and integers greater than 231 - 1 should be clamped to 231 - 1.
Return the integer as the final result.
Note:
Only the space character ' ' is considered a whitespace character.
Do not ignore any characters other than the leading whitespace or the rest of the string after the digits.
Example 1:
Input: s = "42"
Output: 42
Explanation: The underlined characters are what is read in, the caret is the current reader position.
Step 1: "42" (no characters read because there is no leading whitespace)
^
Step 2: "42" (no characters read because there is neither a '-' nor '+')
^
Step 3: "42" ("42" is read in)
^
The parsed integer is 42.
Since 42 is in the range [-231, 231 - 1], the final result is 42.
Example 2:
Input: s = " -42"
Output: -42
Explanation:
Step 1: " -42" (leading whitespace is read and ignored)
^
Step 2: " -42" ('-' is read, so the result should be negative)
^
Step 3: " -42" ("42" is read in)
^
The parsed integer is -42.
Since -42 is in the range [-231, 231 - 1], the final result is -42.
Example 3:
Input: s = "4193 with words"
Output: 4193
Explanation:
Step 1: "4193 with words" (no characters read because there is no leading whitespace)
^
Step 2: "4193 with words" (no characters read because there is neither a '-' nor '+')
^
Step 3: "4193 with words" ("4193" is read in; reading stops because the next character is a non-digit)
^
The parsed integer is 4193.
Since 4193 is in the range [-231, 231 - 1], the final result is 4193.
Constraints:
0 <= s.length <= 200
s consists of English letters (lower-case and upper-case), digits (0-9), ' ', '+', '-', and '.'.
| Medium | [
"string"
] | [
"const myAtoi = function(str) {\n return Math.max(Math.min(parseInt(str) || 0, 2147483647), -2147483648);\n};\n\n// anotther\n\n\nconst myAtoi = function(s) {\n let n = s.length, i = 0, j = 0, sign = 1;\n if(n === 0) {\n return 0;\n } \n while(i < n && s[i] === ' ') {\n i++;\n }\n if(i < n && (s[i] === '-' || s[i] === '+')) {\n sign = (s[i] === '-') ? -1 : 1;\n i++;\n }\n j = i\n while(i < n) {\n if(Number.isInteger(parseInt(s[i]))) i++;\n else break;\n }\n let result = parseInt(s.slice(j, i))\n if(isNaN(result)) return 0\n if(sign * result < -(2**31)) return -(2**31);\n else if(sign * result > (2**31-1)) return 2**31-1;\n else return sign * result; \n};"
] |
|
9 | palindrome-number | [
"Beware of overflow when you reverse the integer."
] | /**
* @param {number} x
* @return {boolean}
*/
var isPalindrome = function(x) {
}; | Given an integer x, return true if x is a palindrome, and false otherwise.
Example 1:
Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.
Example 2:
Input: x = -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Constraints:
-231 <= x <= 231 - 1
Follow up: Could you solve it without converting the integer to a string? | Easy | [
"math"
] | [
"const isPalindrome = function(x) {\n if (x < 0) return false;\n const rev = reverseNum(x);\n return x === rev;\n};\n\nfunction reverseNum(num) {\n let n = num;\n let rev = 0;\n let dig;\n while (num > 0) {\n dig = num % 10;\n rev = rev * 10 + dig;\n num = Math.floor(num / 10);\n }\n return rev;\n}"
] |
|
10 | regular-expression-matching | [] | /**
* @param {string} s
* @param {string} p
* @return {boolean}
*/
var isMatch = function(s, p) {
}; | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where:
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
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 preceding 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 (.)".
Constraints:
1 <= s.length <= 20
1 <= p.length <= 20
s contains only lowercase English letters.
p contains only lowercase English letters, '.', and '*'.
It is guaranteed for each appearance of the character '*', there will be a previous valid character to match.
| Hard | [
"string",
"dynamic-programming",
"recursion"
] | [
"const isMatch = function(s, p) {\n let memory = new Array(s.length + 1)\n .fill(0)\n .map(e => new Array(p.length + 1).fill(-1));\n return memorySearch(s, 0, p, 0, memory);\n};\n\nconst memorySearch = (s, i, p, k, memory) => {\n if (memory[i][k] != -1) return memory[i][k];\n if (k == p.length) return i == s.length;\n\n let firstMatch = i < s.length && (s[i] == p[k] || p[k] == \".\");\n if (k + 1 < p.length && p[k + 1] == \"*\") {\n memory[i][k] =\n (firstMatch && memorySearch(s, i + 1, p, k, memory)) ||\n memorySearch(s, i, p, k + 2, memory);\n } else {\n memory[i][k] = firstMatch && memorySearch(s, i + 1, p, k + 1, memory);\n }\n return memory[i][k];\n};"
] |
|
11 | container-with-most-water | [
"If you simulate the problem, it will be O(n^2) which is not efficient.",
"Try to use two-pointers. Set one pointer to the left and one to the right of the array. Always move the pointer that points to the lower line.",
"How can you calculate the amount of water at each step?"
] | /**
* @param {number[]} height
* @return {number}
*/
var maxArea = function(height) {
}; | You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).
Find two lines that together with the x-axis form a container, such that the container contains the most water.
Return the maximum amount of water a container can store.
Notice that you may not slant the container.
Example 1:
Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
Example 2:
Input: height = [1,1]
Output: 1
Constraints:
n == height.length
2 <= n <= 105
0 <= height[i] <= 104
| Medium | [
"array",
"two-pointers",
"greedy"
] | [
"const maxArea = function(height) {\n let res = 0, l = 0, r = height.length - 1\n while(l < r) {\n const tmp = (r - l) * Math.min(height[l], height[r])\n if(tmp > res) res = tmp\n if(height[l] < height[r]) l++\n else r--\n }\n return res\n};"
] |
|
12 | integer-to-roman | [] | /**
* @param {number} num
* @return {string}
*/
var intToRoman = function(num) {
}; | 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, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 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.
Example 1:
Input: num = 3
Output: "III"
Explanation: 3 is represented as 3 ones.
Example 2:
Input: num = 58
Output: "LVIII"
Explanation: L = 50, V = 5, III = 3.
Example 3:
Input: num = 1994
Output: "MCMXCIV"
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
Constraints:
1 <= num <= 3999
| Medium | [
"hash-table",
"math",
"string"
] | [
"const map = {\n \"1000\": \"M\",\n \"900\": \"CM\",\n \"500\": \"D\",\n \"400\": \"CD\",\n \"100\": \"C\",\n \"90\": \"XC\",\n \"50\": \"L\",\n \"40\": \"XL\",\n \"10\": \"X\",\n \"9\": \"IX\",\n \"5\": \"V\",\n \"4\": \"IV\",\n \"1\": \"I\"\n};\nconst intToRoman = function(number) {\n const l = fkey(map, number);\n if (number == +l) {\n return map[number];\n }\n return map[l] + intToRoman(number - +l);\n};\n\nfunction fkey(m, num) {\n const keys = Object.keys(m);\n const sArr = keys.filter(el => +el <= num);\n return +Math.max.apply(Math, sArr);\n}"
] |
|
13 | roman-to-integer | [
"Problem is simpler to solve by working the string from back to front and using a map."
] | /**
* @param {string} s
* @return {number}
*/
var romanToInt = function(s) {
}; | 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, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII, which is simply X + II. The number 27 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.
Example 1:
Input: s = "III"
Output: 3
Explanation: III = 3.
Example 2:
Input: s = "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.
Example 3:
Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
Constraints:
1 <= s.length <= 15
s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M').
It is guaranteed that s is a valid roman numeral in the range [1, 3999].
| Easy | [
"hash-table",
"math",
"string"
] | [
"const romanToInt = function(s) {\n let res = 0\n for (let i = s.length - 1; i >= 0; i--) {\n let c = s.charAt(i)\n switch (c) {\n case 'I':\n res += res >= 5 ? -1 : 1\n break\n case 'V':\n res += 5\n break\n case 'X':\n res += 10 * (res >= 50 ? -1 : 1)\n break\n case 'L':\n res += 50\n break\n case 'C':\n res += 100 * (res >= 500 ? -1 : 1)\n break\n case 'D':\n res += 500\n break\n case 'M':\n res += 1000\n break\n }\n }\n return res\n}",
"const romanToInt = function(s) {\n const map = { I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000 }\n let result = 0\n let index = s.length - 1\n let preInt = 0\n while (index >= 0) {\n let ch = s[index]\n let curInt = map[ch]\n if (curInt >= preInt) result += curInt\n else result -= curInt\n preInt = curInt\n index--\n }\n return result\n}"
] |
|
14 | longest-common-prefix | [] | /**
* @param {string[]} strs
* @return {string}
*/
var longestCommonPrefix = function(strs) {
}; | 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: strs = ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Constraints:
1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i] consists of only lowercase English letters.
| Easy | [
"string",
"trie"
] | [
"const longestCommonPrefix = function(strs) {\n const A = strs.concat().sort(),\n a1 = A[0] || \"\",\n a2 = A[A.length - 1] || \"\",\n L = a1.length,\n i = 0;\n while (i < L && a1.charAt(i) === a2.charAt(i)) i++;\n return a1.substring(0, i);\n};"
] |
|
15 | 3sum | [
"So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand!",
"For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y, which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster?",
"The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?"
] | /**
* @param {number[]} nums
* @return {number[][]}
*/
var threeSum = function(nums) {
}; | Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
Notice that the solution set must not contain duplicate triplets.
Example 1:
Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
Explanation:
nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.
nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.
nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.
The distinct triplets are [-1,0,1] and [-1,-1,2].
Notice that the order of the output and the order of the triplets does not matter.
Example 2:
Input: nums = [0,1,1]
Output: []
Explanation: The only possible triplet does not sum up to 0.
Example 3:
Input: nums = [0,0,0]
Output: [[0,0,0]]
Explanation: The only possible triplet sums up to 0.
Constraints:
3 <= nums.length <= 3000
-105 <= nums[i] <= 105
| Medium | [
"array",
"two-pointers",
"sorting"
] | [
"const threeSum = function(nums) {\n const res = [], n = nums.length\n nums.sort((a, b) => a - b)\n \n for(let i = 0; i < n; i++) {\n const target = -nums[i]\n let l = i + 1, r = n - 1\n while(l < r) {\n const sum = nums[l] + nums[r]\n if(sum > target) r--\n else if(sum < target) l++\n else {\n const e = [nums[i], nums[l], nums[r]]\n res.push(e)\n while(l + 1 < r && nums[l + 1] === nums[l]) l++\n while(r - 1 > l && nums[r - 1] === nums[r]) r--\n l++\n r--\n }\n }\n while(i + 1 < n && nums[i] === nums[i + 1]) i++\n }\n \n \n return res\n};",
"const threeSum = function (nums) {\n nums.sort((a, b) => a - b)\n const res = []\n let lo, hi, sum\n for (let i = 0; i < nums.length - 2; i++) {\n if (nums[i] > 0) break\n if (nums[i] === nums[i - 1]) continue\n if (i === 0 || (i > 0 && nums[i] !== nums[i - 1])) {\n lo = i + 1\n hi = nums.length - 1\n sum = 0 - nums[i]\n while (lo < hi) {\n if (nums[lo] + nums[hi] === sum) {\n res.push([nums[i], nums[lo], nums[hi]])\n while (lo < hi && nums[lo] === nums[lo + 1]) lo += 1\n while (lo < hi && nums[hi] === nums[hi - 1]) hi -= 1\n lo += 1\n hi -= 1\n } else if (nums[lo] + nums[hi] < sum) lo++\n else hi--\n }\n }\n }\n return res\n}",
"const threeSum = function(nums) {\n const res = [], n = nums.length\n nums.sort((a, b) => a - b)\n for(let i = 0; i < n - 2; i++) {\n let l = i + 1, r = n - 1, target = -nums[i]\n if(i === 0 || (i > 0 && nums[i] !== nums[i - 1])) {\n while(l < r) {\n if(nums[l] + nums[r] === target) {\n res.push([nums[i], nums[l], nums[r]])\n while(l < n - 1 && nums[l] === nums[l + 1]) l++\n while(r > 0 && nums[r] === nums[r - 1]) r--\n r--\n l++\n } else if(nums[l] + nums[r] > target) {\n r--\n } else l++\n }\n }\n } \n\n return res\n};"
] |
|
16 | 3sum-closest | [] | /**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var threeSumClosest = function(nums, target) {
}; | Given an integer array nums of length n 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 1:
Input: nums = [-1,2,1,-4], target = 1
Output: 2
Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
Example 2:
Input: nums = [0,0,0], target = 1
Output: 0
Explanation: The sum that is closest to the target is 0. (0 + 0 + 0 = 0).
Constraints:
3 <= nums.length <= 500
-1000 <= nums[i] <= 1000
-104 <= target <= 104
| Medium | [
"array",
"two-pointers",
"sorting"
] | [
"const threeSumClosest = function(nums, target) {\n const nums = nums.sort((a, b) => a - b);\n let result;\n let lo;\n let hi;\n let sum;\n result = nums[0] + nums[1] + nums[nums.length - 1];\n for (let i = 0; i < nums.length - 2; i++) {\n lo = i + 1;\n hi = nums.length - 1;\n while (lo < hi) {\n sum = nums[i] + nums[lo] + nums[hi];\n if (sum < target) {\n while (lo < hi && nums[lo] === nums[lo + 1]) {\n lo += 1;\n }\n lo += 1;\n } else if (sum > target) {\n while (lo < hi && nums[hi] === nums[hi - 1]) {\n hi -= 1;\n }\n hi -= 1;\n } else {\n return sum;\n }\n\n if (Math.abs(target - sum) < Math.abs(target - result)) {\n result = sum;\n }\n }\n }\n\n return result;\n};"
] |
|
17 | letter-combinations-of-a-phone-number | [] | /**
* @param {string} digits
* @return {string[]}
*/
var letterCombinations = function(digits) {
}; | Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.
A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
Example 1:
Input: digits = "23"
Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
Example 2:
Input: digits = ""
Output: []
Example 3:
Input: digits = "2"
Output: ["a","b","c"]
Constraints:
0 <= digits.length <= 4
digits[i] is a digit in the range ['2', '9'].
| Medium | [
"hash-table",
"string",
"backtracking"
] | [
"const letterCombinations = function(digits) {\n if (digits === \"\") {\n return [];\n }\n const charMap = {\n 2: [\"a\", \"b\", \"c\"],\n 3: [\"d\", \"e\", \"f\"],\n 4: [\"g\", \"h\", \"i\"],\n 5: [\"j\", \"k\", \"l\"],\n 6: [\"m\", \"n\", \"o\"],\n 7: [\"p\", \"q\", \"r\", \"s\"],\n 8: [\"t\", \"u\", \"v\"],\n 9: [\"w\", \"x\", \"y\", \"z\"]\n };\n const res = [];\n const matrix = [];\n for (let i = 0; i < digits.length; i++) {\n matrix.push(charMap[digits.charAt(i)]);\n }\n let tmp = matrix[0];\n for (let j = 1; j < matrix.length; j++) {\n tmp = helper(matrix, j, tmp);\n }\n return tmp;\n};\nfunction helper(matrix, rowIdx, arr) {\n const res = [];\n for (let i = 0; i < arr.length; i++) {\n const preStr = arr[i];\n for (let j = 0; j < matrix[rowIdx].length; j++) {\n res.push(`${preStr}${matrix[rowIdx][j]}`);\n }\n }\n return res;\n}"
] |
|
18 | 4sum | [] | /**
* @param {number[]} nums
* @param {number} target
* @return {number[][]}
*/
var fourSum = function(nums, target) {
}; | Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that:
0 <= a, b, c, d < n
a, b, c, and d are distinct.
nums[a] + nums[b] + nums[c] + nums[d] == target
You may return the answer in any order.
Example 1:
Input: nums = [1,0,-1,0,-2,2], target = 0
Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
Example 2:
Input: nums = [2,2,2,2,2], target = 8
Output: [[2,2,2,2]]
Constraints:
1 <= nums.length <= 200
-109 <= nums[i] <= 109
-109 <= target <= 109
| Medium | [
"array",
"two-pointers",
"sorting"
] | [
"const fourSum = function (nums, target) {\n nums.sort((a, b) => a - b)\n const results = []\n kSum(nums, target, 4, 0, [], results)\n return results\n}\n\nfunction kSum(nums, target, k, i, acc, results) {\n if (nums[i] * k > target || nums[nums.length - 1] * k < target) return\n if (k > 2) {\n for (let j = i; j <= nums.length - k; j++) {\n if (j == i || nums[j] > nums[j - 1])\n kSum(nums, target - nums[j], k - 1, j + 1, [...acc, nums[j]], results)\n }\n } else {\n twoSum(nums, target, i, acc, results)\n }\n}\n\nfunction twoSum(nums, target, i, acc, results) {\n let lo = i\n let hi = nums.length - 1\n while (lo < hi) {\n const sum = nums[lo] + nums[hi]\n if (sum == target) {\n results.push([...acc, nums[lo], nums[hi]])\n while (nums[lo] == nums[lo + 1]) lo++\n while (nums[hi] == nums[hi - 1]) hi--\n lo++\n hi--\n } else if (sum < target) {\n lo++\n } else {\n hi--\n }\n }\n}",
"const fourSum = function(nums, target) {\n return nSum(nums.sort((a, b) => a - b), target, 4, 0);\n};\n\nfunction nSum(nums, target, k, start) {\n const res = [];\n if (nums.length < k || k < 2 || target < nums[0] * k || target > nums[-1] * k)\n return res;\n if (k == 2) {\n // 2 sum; ( improved to O(n) )\n let r = nums.length - 1;\n let l = start;\n while (l < r) {\n if (nums[l] + nums[r] === target) {\n res.push([nums[l], nums[r]]);\n //skip duplication\n while (l < r && nums[l] === nums[l + 1]) l++;\n while (l < r && nums[r] === nums[r - 1]) r--;\n l++;\n r--;\n } else if (nums[l] + nums[r] < target) {\n l++;\n } else {\n r--;\n }\n }\n } else {\n for (let i = start; i < nums.length - k + 1; i++) {\n if (i === start || (i > start && nums[i] !== nums[i - 1])) {\n let temp = nSum(nums, target - nums[i], k - 1, i + 1);\n temp.forEach(t => {\n t.push(nums[i]);\n res.push(t);\n });\n }\n }\n }\n return res;\n}"
] |
|
19 | remove-nth-node-from-end-of-list | [
"Maintain two pointers and update one with a delay of n steps."
] | /**
* 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} n
* @return {ListNode}
*/
var removeNthFromEnd = function(head, n) {
}; | Given the head of a linked list, remove the nth node from the end of the list and return its head.
Example 1:
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
Example 2:
Input: head = [1], n = 1
Output: []
Example 3:
Input: head = [1,2], n = 1
Output: [1]
Constraints:
The number of nodes in the list is sz.
1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz
Follow up: Could you do this in one pass?
| Medium | [
"linked-list",
"two-pointers"
] | /**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/ | [
"const removeNthFromEnd = (head, n) => {\n if (head.next === null) return null;\n\n let ptrBeforeN = head;\n let count = 1;\n\n // While there are more elements\n let el = head.next;\n while (el !== null) {\n if (count > n) ptrBeforeN = ptrBeforeN.next;\n el = el.next;\n count++;\n }\n\n if (count === n) return head.next;\n\n ptrBeforeN.next = ptrBeforeN.next.next;\n return head;\n};"
] |
20 | valid-parentheses | [
"Use a stack of characters.",
"When you encounter an opening bracket, push it to the top of the stack.",
"When you encounter a closing bracket, check if the top of the stack was the opening for it. If yes, pop it from the stack. Otherwise, return false."
] | /**
* @param {string} s
* @return {boolean}
*/
var isValid = function(s) {
}; | Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Every close bracket has a corresponding open bracket of the same type.
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
Constraints:
1 <= s.length <= 104
s consists of parentheses only '()[]{}'.
| Easy | [
"string",
"stack"
] | [
" const isValid = function(s) {\n const stack = []\n for(let c of s) {\n if(c === '(') stack.push(')')\n else if(c === '{') stack.push('}')\n else if(c === '[') stack.push(']')\n else if(stack.length === 0 || c !== stack.pop()) return false\n }\n return stack.length === 0\n};",
" const isValid = function(s) {\n const stack = []\n const n = s.length\n for(let c of s) {\n if(c === '(' || c === '{' || c === '[') stack.push(c)\n else if(c === ')') {\n if(stack[stack.length - 1] === '(') stack.pop()\n else return false\n }\n else if(c === '}') {\n if(stack[stack.length - 1] === '{') stack.pop()\n else return false\n }\n else if(c === ']') {\n if(stack[stack.length - 1] === '[') stack.pop()\n else return false\n }\n }\n return stack.length === 0\n};",
"const isValid = function(s) {\n const openBrackets = [\"(\", \"{\", \"[\"];\n const closeBrackets = [\")\", \"}\", \"]\"];\n const oArr = [];\n let char = \"\";\n let cidx = 0;\n let oidx = 0;\n for (let i = 0; i < s.length; i++) {\n char = s.charAt(i);\n if (closeBrackets.indexOf(char) !== -1) {\n cidx = closeBrackets.indexOf(char);\n lastOpenBracket = oArr[oArr.length - 1];\n oidx = openBrackets.indexOf(lastOpenBracket);\n if (cidx === oidx) {\n oArr.pop();\n } else {\n return false;\n }\n } else {\n oArr.push(char);\n }\n }\n return oArr.length > 0 ? false : true;\n};"
] |
|
21 | merge-two-sorted-lists | [] | /**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} list1
* @param {ListNode} list2
* @return {ListNode}
*/
var mergeTwoLists = function(list1, list2) {
}; | You are given the heads of two sorted linked lists list1 and list2.
Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists.
Return the head of the merged linked list.
Example 1:
Input: list1 = [1,2,4], list2 = [1,3,4]
Output: [1,1,2,3,4,4]
Example 2:
Input: list1 = [], list2 = []
Output: []
Example 3:
Input: list1 = [], list2 = [0]
Output: [0]
Constraints:
The number of nodes in both lists is in the range [0, 50].
-100 <= Node.val <= 100
Both list1 and list2 are sorted in non-decreasing order.
| Easy | [
"linked-list",
"recursion"
] | /**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/ | [
"const mergeTwoLists = function(l1, l2) {\n if (l1 === null) return l2;\n if (l2 === null) return l1;\n if (l1.val < l2.val) {\n l1.next = mergeTwoLists(l1.next, l2);\n return l1;\n } else {\n l2.next = mergeTwoLists(l1, l2.next);\n return l2;\n }\n};",
"const mergeTwoLists = function(l1, l2) {\n const dummy = new ListNode()\n let cur = dummy\n while(l1 && l2) {\n if(l1.val < l2.val) {\n cur.next = new ListNode(l1.val)\n l1 = l1.next\n } else {\n cur.next = new ListNode(l2.val)\n l2 = l2.next\n }\n \n cur = cur.next\n }\n if(l1) cur.next = l1\n if(l2) cur.next = l2\n \n return dummy.next\n};"
] |
22 | generate-parentheses | [] | /**
* @param {number} n
* @return {string[]}
*/
var generateParenthesis = function(n) {
}; | Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example 1:
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Example 2:
Input: n = 1
Output: ["()"]
Constraints:
1 <= n <= 8
| Medium | [
"string",
"dynamic-programming",
"backtracking"
] | [
"const generateParenthesis = function(n) {\n const res = [];\n backtrack(res, \"\", 0, 0, n);\n return res;\n};\nfunction backtrack(arr, cur, open, close, max) {\n if (cur.length === max * 2) {\n arr.push(cur);\n return;\n }\n if (open < max) backtrack(arr, cur + \"(\", open + 1, close, max);\n if (close < open) backtrack(arr, cur + \")\", open, close + 1, max);\n}"
] |
|
23 | merge-k-sorted-lists | [] | /**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode[]} lists
* @return {ListNode}
*/
var mergeKLists = function(lists) {
}; | You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.
Merge all the linked-lists into one sorted linked-list and return it.
Example 1:
Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Explanation: The linked-lists are:
[
1->4->5,
1->3->4,
2->6
]
merging them into one sorted list:
1->1->2->3->4->4->5->6
Example 2:
Input: lists = []
Output: []
Example 3:
Input: lists = [[]]
Output: []
Constraints:
k == lists.length
0 <= k <= 104
0 <= lists[i].length <= 500
-104 <= lists[i][j] <= 104
lists[i] is sorted in ascending order.
The sum of lists[i].length will not exceed 104.
| Hard | [
"linked-list",
"divide-and-conquer",
"heap-priority-queue",
"merge-sort"
] | /**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/ | [
"const mergeKLists = function(lists) {\n return merge(lists, 0, lists.length - 1)\n}\nfunction merge(lists, l, r) {\n if (l > r) return null\n if (l === r) return lists[l]\n let m = Math.floor((r + l) / 2)\n let left = merge(lists, l, m)\n let right = merge(lists, m + 1, r)\n let head = new ListNode(0)\n let dummy = head\n while (left && right) {\n if (left.val <= right.val) {\n head.next = left\n left = left.next\n } else {\n head.next = right\n right = right.next\n }\n head = head.next\n }\n head.next = left ? left : right\n return dummy.next\n}",
"const mergeKLists = function(lists) {\n if(lists == null || lists.length === 0) return null\n if(lists.length === 1) return lists[0]\n if(lists.length === 2) return mergeTwo(lists[0], lists[1])\n const left = mergeKLists(lists.slice(0, ~~(lists.length / 2)))\n const right = mergeKLists(lists.slice(~~(lists.length / 2)))\n \n return mergeTwo(left, right)\n};\n\nfunction mergeTwo(l1, l2) {\n const dummy = new ListNode()\n let cur = dummy\n while(l1 && l2) {\n if(l1.val < l2.val) {\n cur.next = l1\n l1 = l1.next\n } else {\n cur.next = l2\n l2 = l2.next\n }\n cur = cur.next\n }\n if(l1) cur.next = l1\n if(l2) cur.next = l2\n \n \n return dummy.next\n}",
"const mergeKLists = function(lists) {\n if(lists == null || lists.length === 0) return null\n const dummy = new ListNode()\n let head = dummy\n const pq = new PriorityQueue((a, b) => a.val < b.val)\n for(let list of lists) {\n while(list) {\n pq.push(list)\n list = list.next\n }\n }\n while(!pq.isEmpty()) {\n const pop = pq.pop()\n head.next = new ListNode(pop.val)\n head = head.next\n }\n return dummy.next\n};\n\nclass PriorityQueue {\n constructor(comparator = (a, b) => a > b) {\n this.heap = []\n this.top = 0\n this.comparator = comparator\n }\n size() {\n return this.heap.length\n }\n isEmpty() {\n return this.size() === 0\n }\n peek() {\n return this.heap[this.top]\n }\n push(...values) {\n values.forEach((value) => {\n this.heap.push(value)\n this.siftUp()\n })\n return this.size()\n }\n pop() {\n const poppedValue = this.peek()\n const bottom = this.size() - 1\n if (bottom > this.top) {\n this.swap(this.top, bottom)\n }\n this.heap.pop()\n this.siftDown()\n return poppedValue\n }\n replace(value) {\n const replacedValue = this.peek()\n this.heap[this.top] = value\n this.siftDown()\n return replacedValue\n }\n\n parent = (i) => ((i + 1) >>> 1) - 1\n left = (i) => (i << 1) + 1\n right = (i) => (i + 1) << 1\n greater = (i, j) => this.comparator(this.heap[i], this.heap[j])\n swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])\n siftUp = () => {\n let node = this.size() - 1\n while (node > this.top && this.greater(node, this.parent(node))) {\n this.swap(node, this.parent(node))\n node = this.parent(node)\n }\n }\n siftDown = () => {\n let node = this.top\n while (\n (this.left(node) < this.size() && this.greater(this.left(node), node)) ||\n (this.right(node) < this.size() && this.greater(this.right(node), node))\n ) {\n let maxChild =\n this.right(node) < this.size() &&\n this.greater(this.right(node), this.left(node))\n ? this.right(node)\n : this.left(node)\n this.swap(node, maxChild)\n node = maxChild\n }\n }\n}"
] |
24 | swap-nodes-in-pairs | [] | /**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var swapPairs = function(head) {
}; | Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Example 1:
Input: head = [1,2,3,4]
Output: [2,1,4,3]
Example 2:
Input: head = []
Output: []
Example 3:
Input: head = [1]
Output: [1]
Constraints:
The number of nodes in the list is in the range [0, 100].
0 <= Node.val <= 100
| Medium | [
"linked-list",
"recursion"
] | /**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/ | [
"const swapPairs = function(node) {\n const head = new ListNode(-1);\n let cur = head;\n\n while (node !== null) {\n if (node.next !== null) {\n let one = node;\n let two = node.next;\n let three = node.next.next;\n cur.next = two;\n two.next = one;\n one.next = three;\n cur = cur.next.next;\n node = three;\n } else {\n cur.next = node;\n break;\n }\n }\n\n return head.next;\n};"
] |
25 | reverse-nodes-in-k-group | [] | /**
* 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 reverseKGroup = function(head, k) {
}; | Given the head of a linked list, reverse the nodes of the list k at a time, and return the 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.
You may not alter the values in the list's nodes, only nodes themselves may be changed.
Example 1:
Input: head = [1,2,3,4,5], k = 2
Output: [2,1,4,3,5]
Example 2:
Input: head = [1,2,3,4,5], k = 3
Output: [3,2,1,4,5]
Constraints:
The number of nodes in the list is n.
1 <= k <= n <= 5000
0 <= Node.val <= 1000
Follow-up: Can you solve the problem in O(1) extra memory space?
| Hard | [
"linked-list",
"recursion"
] | /**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/ | [
"const reverseKGroup = function(head, k) {\n let n = 0\n for (let i = head; i != null; n++, i = i.next);\n let dmy = new ListNode(0)\n dmy.next = head\n for (let prev = dmy, tail = head; n >= k; n -= k) {\n for (let i = 1; i < k; i++) {\n let next = tail.next.next\n tail.next.next = prev.next\n prev.next = tail.next\n tail.next = next\n }\n\n prev = tail\n tail = tail.next\n }\n return dmy.next\n}",
"const reverseKGroup = function (head, k) {\n if(head == null) return head\n const dummy = new ListNode()\n dummy.next = head\n let n = 0, cur = head\n while(cur) {\n n++\n cur = cur.next\n }\n if(n < k) return head\n let pre = dummy, tail = head\n\n for(let i = 0; i + k <= n; i += k) {\n for(let j = 1; j < k; j++) {\n const tmp = pre.next\n pre.next = tail.next\n tail.next = tail.next.next\n pre.next.next = tmp\n }\n pre = tail\n tail = tail.next\n } \n \n return dummy.next\n}",
"const reverseKGroup = function (head, k) {\n let ptr = head\n let ktail = null\n\n // Head of the final, moified linked list\n let new_head = null\n\n // Keep going until there are nodes in the list\n while (ptr != null) {\n let count = 0\n\n // Start counting nodes from the head\n ptr = head\n\n // Find the head of the next k nodes\n while (count < k && ptr != null) {\n ptr = ptr.next\n count += 1\n }\n\n // If we counted k nodes, reverse them\n if (count == k) {\n // Reverse k nodes and get the new head\n let revHead = reverseLinkedList(head, k)\n\n // new_head is the head of the final linked list\n if (new_head == null) new_head = revHead\n\n // ktail is the tail of the previous block of\n // reversed k nodes\n if (ktail != null) ktail.next = revHead\n\n ktail = head\n head = ptr\n }\n }\n\n // attach the final, possibly un-reversed portion\n if (ktail != null) ktail.next = head\n\n return new_head == null ? head : new_head\n}\n\nfunction reverseLinkedList(head, k) {\n // Reverse k nodes of the given linked list.\n // This function assumes that the list contains\n // atleast k nodes.\n let new_head = null\n let ptr = head\n\n while (k > 0) {\n // Keep track of the next node to process in the\n // original list\n let next_node = ptr.next\n\n // Insert the node pointed to by \"ptr\"\n // at the beginning of the reversed list\n ptr.next = new_head\n new_head = ptr\n\n // Move on to the next node\n ptr = next_node\n\n // Decrement the count of nodes to be reversed by 1\n k--\n }\n\n // Return the head of the reversed list\n return new_head\n}"
] |
26 | remove-duplicates-from-sorted-array | [
"In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements?\r\n\r\n<br>\r\n<img src=\"https://assets.leetcode.com/uploads/2019/10/20/hint_rem_dup.png\" width=\"500\"/>",
"We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements.",
"Essentially, once an element is encountered, you simply need to <b>bypass</b> its duplicates and move on to the next unique element."
] | /**
* @param {number[]} nums
* @return {number}
*/
var removeDuplicates = function(nums) {
}; | Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements in nums.
Consider the number of unique elements of nums to be k, to get accepted, you need to do the following things:
Change the array nums such that the first k elements of nums contain the unique elements in the order they were present in nums initially. The remaining elements of nums are not important as well as the size of nums.
Return k.
Custom Judge:
The judge will test your solution with the following code:
int[] nums = [...]; // Input array
int[] expectedNums = [...]; // The expected answer with correct length
int k = removeDuplicates(nums); // Calls your implementation
assert k == expectedNums.length;
for (int i = 0; i < k; i++) {
assert nums[i] == expectedNums[i];
}
If all assertions pass, then your solution will be accepted.
Example 1:
Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
Example 2:
Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
Constraints:
1 <= nums.length <= 3 * 104
-100 <= nums[i] <= 100
nums is sorted in non-decreasing order.
| Easy | [
"array",
"two-pointers"
] | [
"const removeDuplicates = function(nums) {\n if (nums.length === 0) return 0;\n if (nums.length === 1) return 1;\n let pre = nums[0];\n for (let i = 1; i < nums.length; ) {\n if (nums[i] !== pre) {\n pre = nums[i];\n i += 1;\n } else {\n nums.splice(i, 1);\n }\n }\n return nums.length;\n};"
] |
|
27 | remove-element | [
"The problem statement clearly asks us to modify the array in-place and it also says that the element beyond the new length of the array can be anything. Given an element, we need to remove all the occurrences of it from the array. We don't technically need to <b>remove</b> that element per-say, right?",
"We can move all the occurrences of this element to the end of the array. Use two pointers!\r\n<br><img src=\"https://assets.leetcode.com/uploads/2019/10/20/hint_remove_element.png\" width=\"500\"/>",
"Yet another direction of thought is to consider the elements to be removed as non-existent. In a single pass, if we keep copying the visible elements in-place, that should also solve this problem for us."
] | /**
* @param {number[]} nums
* @param {number} val
* @return {number}
*/
var removeElement = function(nums, val) {
}; | Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val.
Consider the number of elements in nums which are not equal to val be k, to get accepted, you need to do the following things:
Change the array nums such that the first k elements of nums contain the elements which are not equal to val. The remaining elements of nums are not important as well as the size of nums.
Return k.
Custom Judge:
The judge will test your solution with the following code:
int[] nums = [...]; // Input array
int val = ...; // Value to remove
int[] expectedNums = [...]; // The expected answer with correct length.
// It is sorted with no values equaling val.
int k = removeElement(nums, val); // Calls your implementation
assert k == expectedNums.length;
sort(nums, 0, k); // Sort the first k elements of nums
for (int i = 0; i < actualLength; i++) {
assert nums[i] == expectedNums[i];
}
If all assertions pass, then your solution will be accepted.
Example 1:
Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2,_,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 2.
It does not matter what you leave beyond the returned k (hence they are underscores).
Example 2:
Input: nums = [0,1,2,2,3,0,4,2], val = 2
Output: 5, nums = [0,1,4,0,3,_,_,_]
Explanation: Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4.
Note that the five elements can be returned in any order.
It does not matter what you leave beyond the returned k (hence they are underscores).
Constraints:
0 <= nums.length <= 100
0 <= nums[i] <= 50
0 <= val <= 100
| Easy | [
"array",
"two-pointers"
] | [
"const removeElement = function(nums, val) {\n let j = 0;\n for (let i = 0; i < nums.length; i++) {\n if (nums[i] !== val) {\n nums[j] = nums[i];\n j++;\n }\n }\n return j;\n};"
] |
|
28 | find-the-index-of-the-first-occurrence-in-a-string | [] | /**
* @param {string} haystack
* @param {string} needle
* @return {number}
*/
var strStr = function(haystack, needle) {
}; | Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "sadbutsad", needle = "sad"
Output: 0
Explanation: "sad" occurs at index 0 and 6.
The first occurrence is at index 0, so we return 0.
Example 2:
Input: haystack = "leetcode", needle = "leeto"
Output: -1
Explanation: "leeto" did not occur in "leetcode", so we return -1.
Constraints:
1 <= haystack.length, needle.length <= 104
haystack and needle consist of only lowercase English characters.
| Easy | [
"two-pointers",
"string",
"string-matching"
] | [
"const strStr = function(a, b) {\n if(b === '') return 0\n if(a.length < b.length) return -1\n if(a.length === b.length) return a === b ? 0 : -1\n const m = a.length, n = b.length\n const fail = Array(n).fill(-1)\n // DFA\n for(let i = 1; i < n; i++) {\n let j = fail[i - 1]\n while(j !== -1 && b[j + 1] !== b[i]) {\n j = fail[j] \n }\n if(b[j + 1] === b[i]) fail[i] = j + 1\n }\n let pos = -1\n for(let i = 0; i < m; i++) {\n while(pos !== -1 && a[i] !== b[pos + 1]) pos = fail[pos]\n if(a[i] === b[pos + 1]) {\n pos++\n if(pos === n - 1) return i - n + 1\n }\n }\n return -1\n};",
"const strStr = function(haystack, needle) {\n if (needle === \"\") return 0;\n for (let i = 0; ; i++) {\n for (let j = 0; ; j++) {\n if (j === needle.length) {\n return i;\n }\n if (i + j === haystack.length) return -1;\n if (haystack.charAt(i + j) !== needle.charAt(j)) {\n break;\n }\n }\n }\n};"
] |
|
29 | divide-two-integers | [] | /**
* @param {number} dividend
* @param {number} divisor
* @return {number}
*/
var divide = function(dividend, divisor) {
}; | Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator.
The integer division should truncate toward zero, which means losing its fractional part. For example, 8.345 would be truncated to 8, and -2.7335 would be truncated to -2.
Return the quotient after dividing dividend by divisor.
Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For this problem, if the quotient is strictly greater than 231 - 1, then return 231 - 1, and if the quotient is strictly less than -231, then return -231.
Example 1:
Input: dividend = 10, divisor = 3
Output: 3
Explanation: 10/3 = 3.33333.. which is truncated to 3.
Example 2:
Input: dividend = 7, divisor = -3
Output: -2
Explanation: 7/-3 = -2.33333.. which is truncated to -2.
Constraints:
-231 <= dividend, divisor <= 231 - 1
divisor != 0
| Medium | [
"math",
"bit-manipulation"
] | [
"const divide = function(dividend, divisor) {\n if (!divisor || (dividend === Number.MIN_SAFE_INTEGER && divisor === -1)) {\n return Number.MAX_SAFE_INTEGER;\n }\n const MAX_INT = Math.pow(2, 31) - 1;\n if (dividend === -2147483648 && divisor === -1) return MAX_INT;\n\n const sign = (dividend < 0) ^ (divisor < 0) ? -1 : 1;\n let dvd = Math.abs(dividend);\n let dvs = Math.abs(divisor);\n let res = 0;\n\n while (dvd >= dvs) {\n let tmp = dvs;\n let multiple = 1;\n while (dvd >= tmp << 1 && tmp << 1 > 0) {\n tmp <<= 1;\n multiple <<= 1;\n }\n dvd -= tmp;\n res += multiple;\n }\n return sign === 1 ? res : -res;\n};"
] |
|
30 | substring-with-concatenation-of-all-words | [] | /**
* @param {string} s
* @param {string[]} words
* @return {number[]}
*/
var findSubstring = function(s, words) {
}; | You are given a string s and an array of strings words. All the strings of words are of the same length.
A concatenated substring in s is a substring that contains all the strings of any permutation of words concatenated.
For example, if words = ["ab","cd","ef"], then "abcdef", "abefcd", "cdabef", "cdefab", "efabcd", and "efcdab" are all concatenated strings. "acdbef" is not a concatenated substring because it is not the concatenation of any permutation of words.
Return the starting indices of all the concatenated substrings in s. You can return the answer in any order.
Example 1:
Input: s = "barfoothefoobarman", words = ["foo","bar"]
Output: [0,9]
Explanation: Since words.length == 2 and words[i].length == 3, the concatenated substring has to be of length 6.
The substring starting at 0 is "barfoo". It is the concatenation of ["bar","foo"] which is a permutation of words.
The substring starting at 9 is "foobar". It is the concatenation of ["foo","bar"] which is a permutation of words.
The output order does not matter. Returning [9,0] is fine too.
Example 2:
Input: s = "wordgoodgoodgoodbestword", words = ["word","good","best","word"]
Output: []
Explanation: Since words.length == 4 and words[i].length == 4, the concatenated substring has to be of length 16.
There is no substring of length 16 in s that is equal to the concatenation of any permutation of words.
We return an empty array.
Example 3:
Input: s = "barfoofoobarthefoobarman", words = ["bar","foo","the"]
Output: [6,9,12]
Explanation: Since words.length == 3 and words[i].length == 3, the concatenated substring has to be of length 9.
The substring starting at 6 is "foobarthe". It is the concatenation of ["foo","bar","the"] which is a permutation of words.
The substring starting at 9 is "barthefoo". It is the concatenation of ["bar","the","foo"] which is a permutation of words.
The substring starting at 12 is "thefoobar". It is the concatenation of ["the","foo","bar"] which is a permutation of words.
Constraints:
1 <= s.length <= 104
1 <= words.length <= 5000
1 <= words[i].length <= 30
s and words[i] consist of lowercase English letters.
| Hard | [
"hash-table",
"string",
"sliding-window"
] | [
"const findSubstring = function(s, words) {\n if (words == null || words.length === 0 || !s) return []\n const wh = {}\n const slen = s.length\n const wl = words[0].length\n const len = words[0].length * words.length\n words.forEach(el => {\n if (wh[el]) wh[el]++\n else wh[el] = 1\n })\n const res = []\n for (let i = 0; i < slen - len + 1; i++) {\n if (chk(wh, s.slice(i, i + len), wl, words.length)) res.push(i)\n }\n return res\n}\n\nfunction chk(hash, str, wl, num) {\n const oh = {}\n for (let i = 0; i < num; i++) {\n let tmp = str.slice(i * wl, i * wl + wl)\n if (oh[tmp]) oh[tmp]++\n else oh[tmp] = 1\n }\n const keys = Object.keys(hash)\n for (let i = 0; i < keys.length; i++) {\n if (oh[keys[i]] !== hash[keys[i]]) return false\n }\n return true\n}",
"const findSubstring = function(s, words) {\n if (s === \"\" || words.length === 0) return []\n const wordMap = new Map()\n words.forEach(item => {\n if (wordMap.has(item)) {\n wordMap.set(item, wordMap.get(item) + 1)\n } else {\n wordMap.set(item, 1)\n }\n })\n const w = words[0].length\n const wlen = words.length\n const ans = []\n const n = s.length\n for (let i = 0; i < w; i++) {\n let left = i\n let count = 0\n let sMap = new Map()\n for (let j = i; j <= n - w; j += w) {\n let sub = s.substring(j, j + w)\n if (wordMap.has(sub)) {\n if (sMap.has(sub)) {\n sMap.set(sub, sMap.get(sub) + 1)\n } else {\n sMap.set(sub, 1)\n }\n if (sMap.get(sub) <= wordMap.get(sub)) {\n count++\n } else {\n while (sMap.get(sub) > wordMap.get(sub)) {\n let next = s.substring(left, left + w)\n sMap.set(next, sMap.get(next) - 1)\n if (sMap.get(next) < wordMap.get(next)) {\n count--\n }\n left += w\n }\n }\n if (count === wlen) {\n ans.push(left)\n let first = s.substring(left, left + w)\n sMap.set(first, sMap.get(first) - 1)\n left += w\n count--\n }\n } else {\n sMap.clear()\n count = 0\n left = j + w\n }\n }\n }\n return ans\n}"
] |
|
31 | next-permutation | [] | /**
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var nextPermutation = function(nums) {
}; | A permutation of an array of integers is an arrangement of its members into a sequence or linear order.
For example, for arr = [1,2,3], the following are all the permutations of arr: [1,2,3], [1,3,2], [2, 1, 3], [2, 3, 1], [3,1,2], [3,2,1].
The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order).
For example, the next permutation of arr = [1,2,3] is [1,3,2].
Similarly, the next permutation of arr = [2,3,1] is [3,1,2].
While the next permutation of arr = [3,2,1] is [1,2,3] because [3,2,1] does not have a lexicographical larger rearrangement.
Given an array of integers nums, find the next permutation of nums.
The replacement must be in place and use only constant extra memory.
Example 1:
Input: nums = [1,2,3]
Output: [1,3,2]
Example 2:
Input: nums = [3,2,1]
Output: [1,2,3]
Example 3:
Input: nums = [1,1,5]
Output: [1,5,1]
Constraints:
1 <= nums.length <= 100
0 <= nums[i] <= 100
| Medium | [
"array",
"two-pointers"
] | [
"const nextPermutation = function(nums) {\n const n = nums.length\n let k = null\n for(let i = n - 2; i >= 0; i--) {\n if(nums[i] < nums[i + 1]) {\n k = i\n break\n }\n }\n if(k == null) {\n reverse(nums, 0, n - 1)\n } else {\n let end\n for(let i = n - 1; i >= 0; i--) {\n if(nums[i] > nums[k]) {\n end = i\n break\n }\n }\n swap(nums, k, end)\n reverse(nums, k + 1, n - 1)\n }\n \n function reverse(arr, start, end) {\n while(start < end) {\n swap(arr, start, end)\n start++\n end--\n }\n }\n \n function swap(arr, i, j) {\n ;[arr[i], arr[j]] = [arr[j], arr[i]];\n }\n};",
"const nextPermutation = function(nums) {\n let i = nums.length - 2;\n while (i >= 0 && nums[i + 1] <= nums[i]) {\n i--;\n }\n if (i >= 0) {\n let j = nums.length - 1;\n while (j >= 0 && nums[j] <= nums[i]) {\n j--;\n }\n swap(nums, i, j);\n }\n reverse(nums, i + 1);\n \n};\n\nfunction reverse(nums, start) {\n let i = start, j = nums.length - 1;\n while (i < j) {\n swap(nums, i, j);\n i++;\n j--;\n }\n}\n\nfunction swap(arr, i, j) {\n arr[i] ^= arr[j];\n arr[j] ^= arr[i];\n arr[i] ^= arr[j];\n}",
"const nextPermutation = function(nums) {\n const n = nums.length\n let start, end\n for(let i = n - 2; i >= 0; i--) {\n if(nums[i] < nums[i + 1]) {\n start = i\n break\n }\n }\n if(start == null) {\n reverse(nums, 0, n - 1)\n } else {\n for(let i = n - 1; i >= 0; i--) {\n if(nums[i] > nums[start]) {\n end = i\n break\n }\n }\n swap(nums, start, end)\n reverse(nums, start + 1, n - 1)\n }\n};\nfunction reverse(arr, start, end) {\n while(start < end) {\n swap(arr, start++, end--)\n }\n}\nfunction swap(arr, i, j) {\n const tmp = arr[i]\n arr[i] = arr[j]\n arr[j] = tmp\n}"
] |
|
32 | longest-valid-parentheses | [] | /**
* @param {string} s
* @return {number}
*/
var longestValidParentheses = function(s) {
}; | Given a string containing just the characters '(' and ')', return the length of the longest valid (well-formed) parentheses substring.
Example 1:
Input: s = "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()".
Example 2:
Input: s = ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()".
Example 3:
Input: s = ""
Output: 0
Constraints:
0 <= s.length <= 3 * 104
s[i] is '(', or ')'.
| Hard | [
"string",
"dynamic-programming",
"stack"
] | [
"const longestValidParentheses = function(s) {\n const arr = s.split(\"\")\n const dp = new Array(arr.length).fill(0)\n let open = 0\n let max = 0\n for (let i = 0; i < arr.length; i++) {\n if (arr[i] === \"(\") open++\n if (arr[i] === \")\" && open > 0) {\n dp[i] = 2 + dp[i - 1]\n if (i - dp[i] > 0) dp[i] += dp[i - dp[i]]\n open--\n }\n if (dp[i] > max) max = dp[i]\n }\n return max\n}",
"const longestValidParentheses = function(s) {\n let longest = 0\n let stack = [-1]\n for (let i = 0; i < s.length; i++) {\n if (s[i] === \"(\") {\n stack.push(i)\n } else {\n stack.pop()\n if (!stack.length) stack.push(i)\n else longest = Math.max(longest, i - stack[stack.length - 1])\n }\n }\n\n return longest\n}",
"const longestValidParentheses = function (s) {\n let res = 0,\n stk = [],\n n = s.length,\n idxStk = []\n for (let i = 0; i < n; i++) {\n const ch = s[i]\n if (stk.length && stk[stk.length - 1] === '(' && ch === ')')\n stk.pop(), idxStk.pop()\n else stk.push(ch), idxStk.push(i)\n res = Math.max(res, i - (idxStk.length ? idxStk[idxStk.length - 1] : -1))\n }\n return res\n}\n\nconst longestValidParentheses = function (s) {\n let res = 0,\n stk = [],\n n = s.length,\n idxStk = []\n for (let i = 0; i < n; i++) {\n const ch = s[i]\n if (stk.length && stk[stk.length - 1] === '(' && ch === ')')\n stk.pop(), idxStk.pop()\n else stk.push(ch), idxStk.push(i)\n res = Math.max(res, i - (idxStk.length ? idxStk[idxStk.length - 1] : -1))\n }\n return res\n}"
] |
|
33 | search-in-rotated-sorted-array | [] | /**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var search = function(nums, target) {
}; | There is an integer array nums sorted in ascending order (with distinct values).
Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2].
Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums.
You must write an algorithm with O(log n) runtime complexity.
Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
Example 3:
Input: nums = [1], target = 0
Output: -1
Constraints:
1 <= nums.length <= 5000
-104 <= nums[i] <= 104
All values of nums are unique.
nums is an ascending array that is possibly rotated.
-104 <= target <= 104
| Medium | [
"array",
"binary-search"
] | [
"const search = function(nums, target) {\n const len = nums.length\n let r = false\n let ridx = 0\n if(len === 0) return -1\n if(nums[0] === target) return 0\n for(let i = 1; i < len; i++) {\n if(nums[i] === target) return i\n if(nums[i] < nums[i - 1]) {\n r = true\n ridx = i\n break\n }\n }\n \n if(r === true) {\n for(let i = len - 1; i >= ridx; i--) {\n if(nums[i] === target) return i\n }\n }\n \n return -1\n};",
"const search = function(nums, target) {\n const len = nums.length\n for(let i = 0; nums[i] <= target; i++){\n if(nums[i] === target){\n return i\n }\n }\n for(let j = len - 1; nums[j] >= target; j--){\n if(nums[j] === target){\n return j\n }\n }\n return -1 \n};",
"const search = function(nums, target) {\n let low = 0\n let high = nums.length - 1\n while (low <= high) {\n let mid = low + ((high - low) >> 1)\n if (nums[mid] === target) return mid\n\n if (nums[low] <= nums[mid] ) {\n if (target < nums[mid] && target >= nums[low]) {\n high = mid - 1\n } else {\n low = mid + 1\n }\n } else {\n if (target > nums[mid] && target <= nums[high]) {\n low = mid + 1\n } else {\n high = mid - 1\n }\n }\n\n }\n return -1\n};"
] |
|
34 | find-first-and-last-position-of-element-in-sorted-array | [] | /**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var searchRange = function(nums, target) {
}; | Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.
If target is not found in the array, return [-1, -1].
You must write an algorithm with O(log n) runtime complexity.
Example 1:
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
Example 2:
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]
Example 3:
Input: nums = [], target = 0
Output: [-1,-1]
Constraints:
0 <= nums.length <= 105
-109 <= nums[i] <= 109
nums is a non-decreasing array.
-109 <= target <= 109
| Medium | [
"array",
"binary-search"
] | [
"const searchRange = function(nums, target) {\n let len = nums.length;\n let start = 0;\n let end = len - 1;\n let res = [];\n let idx;\n while (start <= end) {\n let mid = Math.floor((start + end) / 2);\n if (target === nums[mid]) {\n idx = mid;\n break;\n } else if (target < nums[mid]) end = mid - 1;\n else start = mid + 1;\n }\n if (idx == null) return [-1, -1];\n let li = idx;\n let hi = idx;\n while (nums[li - 1] === target) {\n li--;\n }\n while (nums[hi + 1] === target) {\n hi++;\n }\n res = [li, hi];\n return res;\n};"
] |
|
35 | search-insert-position | [] | /**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var searchInsert = function(nums, target) {
}; | Given a sorted array of distinct integers 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 must write an algorithm with O(log n) runtime complexity.
Example 1:
Input: nums = [1,3,5,6], target = 5
Output: 2
Example 2:
Input: nums = [1,3,5,6], target = 2
Output: 1
Example 3:
Input: nums = [1,3,5,6], target = 7
Output: 4
Constraints:
1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums contains distinct values sorted in ascending order.
-104 <= target <= 104
| Easy | [
"array",
"binary-search"
] | [
"const searchInsert = function(nums, target) {\n for (let i = 0; i < nums.length; i++) {\n if (nums[i] >= target) {\n return i;\n } else {\n if (i === nums.length - 1) {\n return i + 1;\n }\n }\n }\n};",
"const searchInsert = function(nums, target) {\n const n = nums.length\n let l = 0, r = n - 1\n while(l <= r) {\n const mid = l + ((r - l) >> 1)\n if(nums[mid] === target) return mid\n if(nums[mid] > target) r = mid - 1\n else l = mid + 1\n }\n return l\n};"
] |
|
36 | valid-sudoku | [] | /**
* @param {character[][]} board
* @return {boolean}
*/
var isValidSudoku = function(board) {
}; | Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
Each row must contain the digits 1-9 without repetition.
Each column must contain the digits 1-9 without repetition.
Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition.
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.
Example 1:
Input: board =
[["5","3",".",".","7",".",".",".","."]
,["6",".",".","1","9","5",".",".","."]
,[".","9","8",".",".",".",".","6","."]
,["8",".",".",".","6",".",".",".","3"]
,["4",".",".","8",".","3",".",".","1"]
,["7",".",".",".","2",".",".",".","6"]
,[".","6",".",".",".",".","2","8","."]
,[".",".",".","4","1","9",".",".","5"]
,[".",".",".",".","8",".",".","7","9"]]
Output: true
Example 2:
Input: board =
[["8","3",".",".","7",".",".",".","."]
,["6",".",".","1","9","5",".",".","."]
,[".","9","8",".",".",".",".","6","."]
,["8",".",".",".","6",".",".",".","3"]
,["4",".",".","8",".","3",".",".","1"]
,["7",".",".",".","2",".",".",".","6"]
,[".","6",".",".",".",".","2","8","."]
,[".",".",".","4","1","9",".",".","5"]
,[".",".",".",".","8",".",".","7","9"]]
Output: false
Explanation: Same as Example 1, except with the 5 in the top left corner being modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is invalid.
Constraints:
board.length == 9
board[i].length == 9
board[i][j] is a digit 1-9 or '.'.
| Medium | [
"array",
"hash-table",
"matrix"
] | [
"const isValidSudoku = function(board) {\n const n = 9\n const m = 3\n const row = [],\n col = [],\n block = []\n for (let i = 0; i < n; i++) {\n row[i] = new Set()\n col[i] = new Set()\n block[i] = new Set()\n }\n for (let r = 0; r < n; r++) {\n for (let c = 0; c < n; c++) {\n const ch = board[r][c]\n if (ch === '.') continue\n const b = Math.floor(r / m) * m + Math.floor(c / m)\n if (row[r].has(ch) || col[c].has(ch) || block[b].has(ch)) return false\n row[r].add(ch)\n col[c].add(ch)\n block[b].add(ch)\n }\n }\n return true\n}",
"const isValidSudoku = function(board) {\n let seen = new Set()\n for (let i = 0; i < 9; ++i) {\n for (let j = 0; j < 9; ++j) {\n let number = board[i][j]\n if (number != '.')\n if (\n !hset(seen, number + ' in row ' + i) ||\n !hset(seen, number + ' in column ' + j) ||\n !hset(seen, number + ' in block ' + ~~(i / 3) + '-' + ~~(j / 3))\n )\n return false\n }\n }\n return true\n}\nfunction hset(s, val) {\n if (s.has(val)) return false\n else {\n s.add(val)\n return true\n }\n}"
] |
|
37 | sudoku-solver | [] | /**
* @param {character[][]} board
* @return {void} Do not return anything, modify board in-place instead.
*/
var solveSudoku = function(board) {
}; | 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 digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.
The '.' character indicates empty cells.
Example 1:
Input: board = [["5","3",".",".","7",".",".",".","."],["6",".",".","1","9","5",".",".","."],[".","9","8",".",".",".",".","6","."],["8",".",".",".","6",".",".",".","3"],["4",".",".","8",".","3",".",".","1"],["7",".",".",".","2",".",".",".","6"],[".","6",".",".",".",".","2","8","."],[".",".",".","4","1","9",".",".","5"],[".",".",".",".","8",".",".","7","9"]]
Output: [["5","3","4","6","7","8","9","1","2"],["6","7","2","1","9","5","3","4","8"],["1","9","8","3","4","2","5","6","7"],["8","5","9","7","6","1","4","2","3"],["4","2","6","8","5","3","7","9","1"],["7","1","3","9","2","4","8","5","6"],["9","6","1","5","3","7","2","8","4"],["2","8","7","4","1","9","6","3","5"],["3","4","5","2","8","6","1","7","9"]]
Explanation: The input board is shown above and the only valid solution is shown below:
Constraints:
board.length == 9
board[i].length == 9
board[i][j] is a digit or '.'.
It is guaranteed that the input board has only one solution.
| Hard | [
"array",
"hash-table",
"backtracking",
"matrix"
] | [
"const solveSudoku = function(board) {\n dfs(0, 0)\n function dfs(row, col) {\n if (row === 9) return true\n if (col === 9) return dfs(row + 1, 0)\n if (board[row][col] === \".\") {\n for (let num = 1; num <= 9; num++) {\n if (isValid(row, col, `${num}`)) {\n board[row][col] = `${num}`\n if (dfs(row, col + 1)) return true\n board[row][col] = \".\"\n }\n }\n } else {\n return dfs(row, col + 1)\n }\n return false\n }\n function isValid(row, col, num) {\n for (let rowIdx = 0; rowIdx < 9; rowIdx++) if (board[rowIdx][col] === num) return false\n for (let colIdx = 0; colIdx < 9; colIdx++) if (board[row][colIdx] === num) return false\n\n let squareRowStart = row - (row % 3)\n let squareColStart = col - (col % 3)\n for (let rIdx = 0; rIdx < 3; rIdx++) {\n for (let cIdx = 0; cIdx < 3; cIdx++) {\n if (board[squareRowStart + rIdx][squareColStart + cIdx] === num) return false\n }\n }\n return true\n }\n}",
"const solveSudoku = function(board) {\n helper(board, 0 , 0)\n};\n\nfunction helper(board, row, col) {\n if(row >= 9) return true\n if(col >= 9) return helper(board, row + 1, 0)\n if(board[row][col] !== '.') return helper(board, row, col + 1)\n for(let i = 1; i <= 9; i++) {\n const ch = `${i}`\n if(valid(board, row, col, ch)) {\n board[row][col] = ch\n if(helper(board, row, col + 1)) return true\n board[row][col] = '.'\n }\n }\n return false\n}\n\nfunction valid(board, row, col, ch) {\n const blkRow = ~~(row / 3), blkCol = ~~(col / 3)\n for(let i = 0; i < 9; i++) {\n if(board[row][i] === ch) return false\n if(board[i][col] === ch) return false\n if(board[blkRow * 3 + Math.floor(i / 3)][blkCol * 3 + (i % 3)] === ch) return false\n }\n return true\n}"
] |
|
38 | count-and-say | [
"Create a helper function that maps an integer to pairs of its digits and their frequencies. For example, if you call this function with \"223314444411\", then it maps it to an array of pairs [[2,2], [3,2], [1,1], [4,5], [1, 2]].",
"Create another helper function that takes the array of pairs and creates a new integer. For example, if you call this function with [[2,2], [3,2], [1,1], [4,5], [1, 2]], it should create \"22\"+\"23\"+\"11\"+\"54\"+\"21\" = \"2223115421\".",
"Now, with the two helper functions, you can start with \"1\" and call the two functions alternatively n-1 times. The answer is the last integer you will obtain."
] | /**
* @param {number} n
* @return {string}
*/
var countAndSay = function(n) {
}; | The count-and-say sequence is a sequence of digit strings defined by the recursive formula:
countAndSay(1) = "1"
countAndSay(n) is the way you would "say" the digit string from countAndSay(n-1), which is then converted into a different digit string.
To determine how you "say" a digit string, split it into the minimal number of substrings such that each substring contains exactly one unique digit. Then for each substring, say the number of digits, then say the digit. Finally, concatenate every said digit.
For example, the saying and conversion for digit string "3322251":
Given a positive integer n, return the nth term of the count-and-say sequence.
Example 1:
Input: n = 1
Output: "1"
Explanation: This is the base case.
Example 2:
Input: n = 4
Output: "1211"
Explanation:
countAndSay(1) = "1"
countAndSay(2) = say "1" = one 1 = "11"
countAndSay(3) = say "11" = two 1's = "21"
countAndSay(4) = say "21" = one 2 + one 1 = "12" + "11" = "1211"
Constraints:
1 <= n <= 30
| Medium | [
"string"
] | [
"const countAndSay = function(n) {\n let str = '1'\n for (let i = 2; i <= n; i++) {\n let tempStr = ''\n let count = 0\n for (let j = 0, m = str.length; j < m; j++) {\n const char = str.charAt(j)\n count += 1\n if (char !== str.charAt(j + 1)) {\n tempStr += count + char\n count = 0\n }\n }\n str = tempStr\n }\n return str\n}"
] |
|
39 | combination-sum | [] | /**
* @param {number[]} candidates
* @param {number} target
* @return {number[][]}
*/
var combinationSum = function(candidates, target) {
}; | Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.
The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.
The test cases are generated such that the number of unique combinations that sum up to target is less than 150 combinations for the given input.
Example 1:
Input: candidates = [2,3,6,7], target = 7
Output: [[2,2,3],[7]]
Explanation:
2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
7 is a candidate, and 7 = 7.
These are the only two combinations.
Example 2:
Input: candidates = [2,3,5], target = 8
Output: [[2,2,2,2],[2,3,3],[3,5]]
Example 3:
Input: candidates = [2], target = 1
Output: []
Constraints:
1 <= candidates.length <= 30
2 <= candidates[i] <= 40
All elements of candidates are distinct.
1 <= target <= 40
| Medium | [
"array",
"backtracking"
] | [
"const combinationSum = function(candidates, target) {\n candidates.sort((a, b) => a - b);\n const res = [];\n bt(candidates, target, res, [], 0);\n return res;\n};\n\nfunction bt(candidates, target, res, combination, start) {\n if (target === 0) {\n res.push(combination.slice(0));\n return;\n }\n for (let i = start; i < candidates.length && target >= candidates[i]; i++) {\n combination.push(candidates[i]);\n bt(candidates, target - candidates[i], res, combination, i);\n combination.pop();\n }\n}"
] |
|
40 | combination-sum-ii | [] | /**
* @param {number[]} candidates
* @param {number} target
* @return {number[][]}
*/
var combinationSum2 = function(candidates, target) {
}; | Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target.
Each number in candidates may only be used once in the combination.
Note: The solution set must not contain duplicate combinations.
Example 1:
Input: candidates = [10,1,2,7,6,1,5], target = 8
Output:
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]
Example 2:
Input: candidates = [2,5,2,1,2], target = 5
Output:
[
[1,2,2],
[5]
]
Constraints:
1 <= candidates.length <= 100
1 <= candidates[i] <= 50
1 <= target <= 30
| Medium | [
"array",
"backtracking"
] | [
"const combinationSum2 = function(candidates, target) {\n candidates.sort((a, b) => a - b);\n const res = [];\n bt(candidates, target, res, [], 0);\n return res;\n};\n\nfunction bt(candidates, target, res, combination, start) {\n if (target === 0) {\n res.push(combination.slice(0));\n return;\n }\n for (let i = start; i < candidates.length && target >= candidates[i]; i++) {\n if (i > 0 && candidates[i] === candidates[i - 1] && i > start) continue;\n combination.push(candidates[i]);\n bt(candidates, target - candidates[i], res, combination, i + 1);\n combination.pop();\n }\n}"
] |
|
41 | first-missing-positive | [
"Think about how you would solve the problem in non-constant space. Can you apply that logic to the existing space?",
"We don't care about duplicates or non-positive integers",
"Remember that O(2n) = O(n)"
] | /**
* @param {number[]} nums
* @return {number}
*/
var firstMissingPositive = function(nums) {
}; | Given an unsorted integer array nums, return the smallest missing positive integer.
You must implement an algorithm that runs in O(n) time and uses O(1) auxiliary space.
Example 1:
Input: nums = [1,2,0]
Output: 3
Explanation: The numbers in the range [1,2] are all in the array.
Example 2:
Input: nums = [3,4,-1,1]
Output: 2
Explanation: 1 is in the array but 2 is missing.
Example 3:
Input: nums = [7,8,9,11,12]
Output: 1
Explanation: The smallest positive integer 1 is missing.
Constraints:
1 <= nums.length <= 105
-231 <= nums[i] <= 231 - 1
| Hard | [
"array",
"hash-table"
] | [
"const firstMissingPositive = function(nums) {\n if(nums.length === 0) return 1\n const arr = []\n let max = Number.MIN_SAFE_INTEGER\n for(let i = 0, len = nums.length; i < len; i++) {\n if(nums[i] > 0) arr[nums[i]] = nums[i]\n if(nums[i] > max) max = nums[i]\n }\n for(let i = 1; i < max; i++) {\n if(arr[i] == null) return i\n }\n return max < 0 ? 1 : max + 1\n};",
"function firstMissingPositive(nums) {\n const n = nums.length\n for (let i = 0; i < n; i++) {\n while (nums[i] > 0 && nums[i] <= n && nums[nums[i] - 1] !== nums[i])\n swap(nums, i, nums[i] - 1)\n }\n\n for (let i = 0; i < n; i++) {\n if (nums[i] !== i + 1) return i + 1\n }\n return n + 1\n}\n\nfunction swap(arr, i, j) {\n const tmp = arr[i]\n arr[i] = arr[j]\n arr[j] = tmp\n}",
"const firstMissingPositive = function(nums) {\n const n = nums.length\n for(let i = 0; i < n; i++) {\n while(nums[i] < n && nums[nums[i] - 1] !== nums[i]) {\n swap(nums, i, nums[i] - 1)\n }\n }\n \n for(let i = 0; i < n; i++) {\n if(nums[i] !== i + 1) return i + 1\n }\n \n return n + 1\n};\n\nfunction swap(arr, i, j) {\n const tmp = arr[i]\n arr[i] = arr[j]\n arr[j] = tmp\n}",
"const firstMissingPositive = function(nums) {\n const n = nums.length\n for(let i = 0; i < n; i++) {\n while(nums[i] > 0 && nums[i] !== nums[nums[i] - 1] && nums[i] <= n) {\n swap(i, nums[i] - 1) \n }\n }\n\n // console.log(nums)\n for(let i = 0; i < n; i++) {\n if(nums[i] !== i + 1) return i + 1\n }\n \n return n + 1\n \n \n function swap(i, j) {\n const tmp = nums[j]\n nums[j] = nums[i]\n nums[i] = tmp\n }\n};"
] |
|
42 | trapping-rain-water | [] | /**
* @param {number[]} height
* @return {number}
*/
var trap = function(height) {
}; | Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
Example 1:
Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Explanation: The above elevation map (black section) 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.
Example 2:
Input: height = [4,2,0,3,2,5]
Output: 9
Constraints:
n == height.length
1 <= n <= 2 * 104
0 <= height[i] <= 105
| Hard | [
"array",
"two-pointers",
"dynamic-programming",
"stack",
"monotonic-stack"
] | [
"const trap = function(height) {\n \n let s = height.length\n if(s === 0) return 0\n let res = 0\n const left_max = [height[0]]\n const right_max = []\n right_max[s - 1] = height[s - 1]\n for(let i = 1; i < s; i++) {\n left_max[i] = Math.max(height[i], left_max[i - 1])\n }\n for(let i = s - 2; i >= 0; i--) {\n right_max[i] = Math.max(height[i], right_max[i + 1])\n }\n for(let i = 1; i < s - 1; i++) {\n res += Math.min(left_max[i], right_max[i]) - height[i] \n }\n return res\n};",
"const trap = function(height) {\n const len = height.length\n if (len === 0) return 0\n const leftMax = [height[0]]\n const rightMax = []\n rightMax[len - 1] = height[len - 1]\n for (let i = len - 2; i >= 0; i--) {\n rightMax[i] = Math.max(height[i], rightMax[i + 1])\n }\n let res = 0\n for (let i = 1; i < len; i++) {\n leftMax[i] = Math.max(height[i], leftMax[i - 1])\n res += Math.min(leftMax[i], rightMax[i]) - height[i]\n }\n return res\n}",
"const trap = function(height) {\n const n = height.length\n let l = 0, r = n - 1, res = 0, leftMax = 0, rightMax = 0\n while(l <= r) {\n if(height[l] <= height[r]) {\n if(height[l] >= leftMax) leftMax = height[l]\n else res += leftMax - height[l]\n l++\n } else {\n if(height[r] >= rightMax) rightMax = height[r]\n else res += rightMax - height[r]\n r--\n }\n }\n return res\n};",
"const trap = function(height) {\n const n = height.length\n if(n === 0) return 0\n let res = 0\n let l = 0, r = n - 1, leftMax = height[l], rightMax = height[r]\n while(l < r) {\n if(height[l] <= height[r]) {\n l++\n leftMax = Math.max(leftMax, height[l])\n res += (leftMax - height[l]) \n } else {\n r--\n rightMax = Math.max(rightMax, height[r])\n res += rightMax - height[r]\n }\n }\n\n return res\n};",
"const trap = function(height) {\n const n = height.length, { max } = Math\n let res = 0, l = 0, r = n - 1, leftMax = height[0], rightMax = height[n - 1]\n while(l <= r) {\n if(leftMax < rightMax) {\n leftMax = max(leftMax, height[l])\n res += leftMax - height[l]\n l++\n } else {\n rightMax = max(rightMax, height[r])\n res += rightMax - height[r]\n r--\n }\n }\n\n return res\n};"
] |
|
43 | multiply-strings | [] | /**
* @param {string} num1
* @param {string} num2
* @return {string}
*/
var multiply = function(num1, num2) {
}; | Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.
Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.
Example 1:
Input: num1 = "2", num2 = "3"
Output: "6"
Example 2:
Input: num1 = "123", num2 = "456"
Output: "56088"
Constraints:
1 <= num1.length, num2.length <= 200
num1 and num2 consist of digits only.
Both num1 and num2 do not contain any leading zero, except the number 0 itself.
| Medium | [
"math",
"string",
"simulation"
] | [
"const multiply = function(num1, num2) {\n let m = num1.length,\n n = num2.length;\n let pos = new Array(m + n).fill(0);\n\n for (let i = m - 1; i >= 0; i--) {\n for (let j = n - 1; j >= 0; j--) {\n let mul = (num1.charAt(i) - \"0\") * (num2.charAt(j) - \"0\");\n let p1 = i + j,\n p2 = i + j + 1;\n let sum = mul + pos[p2];\n\n pos[p1] += Math.floor(sum / 10);\n pos[p2] = sum % 10;\n }\n }\n\n let str = \"\";\n for (let p of pos) if (!(str.length === 0 && p === 0)) str += p;\n return str.length === 0 ? \"0\" : str;\n};"
] |
|
44 | wildcard-matching | [] | /**
* @param {string} s
* @param {string} p
* @return {boolean}
*/
var isMatch = function(s, p) {
}; | Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*' where:
'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).
The matching should cover the entire input string (not partial).
Example 1:
Input: s = "aa", p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".
Example 2:
Input: s = "aa", p = "*"
Output: true
Explanation: '*' matches any sequence.
Example 3:
Input: s = "cb", p = "?a"
Output: false
Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'.
Constraints:
0 <= s.length, p.length <= 2000
s contains only lowercase English letters.
p contains only lowercase English letters, '?' or '*'.
| Hard | [
"string",
"dynamic-programming",
"greedy",
"recursion"
] | [
"const isMatch = function(s, p) {\n const M = s.length\n const N = p.length\n let i = 0,\n j = 0,\n lastMatchInS,\n lastStarPos\n while (i < M) {\n if (j < N && (p[j] === s[i] || p[j] === '?')) {\n i++\n j++\n } else if (j < N && p[j] === '*') {\n lastStarPos = j\n j++\n lastMatchInS = i\n } else if (lastStarPos !== undefined) {\n // back to previous step\n j = lastStarPos + 1\n lastMatchInS++\n i = lastMatchInS\n } else {\n return false\n }\n }\n while (j < N && p[j] === '*') {\n j++\n }\n return j === N\n}"
] |
|
45 | jump-game-ii | [] | /**
* @param {number[]} nums
* @return {number}
*/
var jump = function(nums) {
}; | You are given a 0-indexed array of integers nums of length n. You are initially positioned at nums[0].
Each element nums[i] represents the maximum length of a forward jump from index i. In other words, if you are at nums[i], you can jump to any nums[i + j] where:
0 <= j <= nums[i] and
i + j < n
Return the minimum number of jumps to reach nums[n - 1]. The test cases are generated such that you can reach nums[n - 1].
Example 1:
Input: nums = [2,3,1,1,4]
Output: 2
Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2:
Input: nums = [2,3,0,1,4]
Output: 2
Constraints:
1 <= nums.length <= 104
0 <= nums[i] <= 1000
It's guaranteed that you can reach nums[n - 1].
| Medium | [
"array",
"dynamic-programming",
"greedy"
] | [
"const jump = function(nums) {\n if (nums.length <= 1) return 0;\n let curMax = 0; // to mark the last element in a level\n let level = 0, i = 0;\n while (i <= curMax) { \n let furthest = curMax; // to mark the last element in the next level\n for (; i <= curMax; i++) {\n furthest = Math.max(furthest, nums[i] + i);\n if (furthest >= nums.length - 1) return level + 1;\n }\n level++;\n curMax = furthest;\n }\n return -1; // if i < curMax, i can't move forward anymore (the last element in the array can't be reached)\n};"
] |
|
46 | permutations | [] | /**
* @param {number[]} nums
* @return {number[][]}
*/
var permute = function(nums) {
}; | Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.
Example 1:
Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Example 2:
Input: nums = [0,1]
Output: [[0,1],[1,0]]
Example 3:
Input: nums = [1]
Output: [[1]]
Constraints:
1 <= nums.length <= 6
-10 <= nums[i] <= 10
All the integers of nums are unique.
| Medium | [
"array",
"backtracking"
] | [
"function permute(nums) {\n const list = [];\n // Arrays.sort(nums); // not necessary\n backtrack(list, [], nums);\n return list;\n}\n\nfunction backtrack(list, tempList, nums) {\n if (tempList.length == nums.length) {\n list.push(tempList.slice(0));\n } else {\n for (let i = 0; i < nums.length; i++) {\n if (tempList.includes(nums[i])) continue; // element already exists, skip\n tempList.push(nums[i]);\n backtrack(list, tempList, nums);\n tempList.pop();\n }\n }\n}",
"const permute = function(nums) {\n const res = []\n bt(nums, 0, [], res)\n return res\n};\n\nfunction bt(nums, idx, cur, res) {\n if(idx === nums.length) {\n res.push(cur.slice())\n return\n }\n for(let i = 0; i < nums.length; i++) {\n if(cur.indexOf(nums[i]) !== -1) continue\n cur.push(nums[i])\n bt(nums, idx + 1, cur, res)\n cur.pop()\n }\n}"
] |
|
47 | permutations-ii | [] | /**
* @param {number[]} nums
* @return {number[][]}
*/
var permuteUnique = function(nums) {
}; | Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order.
Example 1:
Input: nums = [1,1,2]
Output:
[[1,1,2],
[1,2,1],
[2,1,1]]
Example 2:
Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Constraints:
1 <= nums.length <= 8
-10 <= nums[i] <= 10
| Medium | [
"array",
"backtracking"
] | [
"const permuteUnique = function(nums) {\n const result = [];\n if (nums == null || nums.length === 0) {\n return result;\n }\n const map = {};\n for (let n of nums) {\n map[n] = map.hasOwnProperty(n) ? map[n] + 1 : 1;\n }\n permuteUniqueHelper(map, nums.length, [], 0, result);\n return result;\n};\n\nfunction permuteUniqueHelper(m, l, p, i, r) {\n if (l === i) {\n r.push(p.slice(0, l));\n return;\n }\n for (let key of Object.keys(m)) {\n if (m[key] > 0) {\n m[key] = m[key] - 1;\n p[i] = key;\n permuteUniqueHelper(m, l, p, i + 1, r);\n m[key] = m[key] + 1;\n }\n }\n}",
"const permuteUnique = function(nums) {\n const set = new Set()\n const used = new Set()\n bt(nums, 0, [], used, set)\n const res = []\n for(let item of set) {\n res.push(item.split(','))\n }\n return res\n};\n\nfunction bt(nums, i, cur, used, set) {\n if(i === nums.length) {\n set.add(cur.slice().join(','))\n return\n }\n for(let idx = 0; idx < nums.length; idx++) {\n if(used.has(idx)) continue\n cur.push(nums[idx])\n used.add(idx)\n bt(nums, i + 1, cur, used, set)\n used.delete(idx)\n cur.pop()\n }\n}"
] |
|
48 | rotate-image | [] | /**
* @param {number[][]} matrix
* @return {void} Do not return anything, modify matrix in-place instead.
*/
var rotate = function(matrix) {
}; | You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).
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:
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[7,4,1],[8,5,2],[9,6,3]]
Example 2:
Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]
Constraints:
n == matrix.length == matrix[i].length
1 <= n <= 20
-1000 <= matrix[i][j] <= 1000
| Medium | [
"array",
"math",
"matrix"
] | [
"const rotate = function(matrix) {\n let s = 0,\n e = matrix.length - 1\n while (s < e) {\n let temp = matrix[s]\n matrix[s] = matrix[e]\n matrix[e] = temp\n s++\n e--\n }\n\n for (let i = 0; i < matrix.length; i++) {\n for (let j = i + 1; j < matrix[i].length; j++) {\n let temp = matrix[i][j]\n matrix[i][j] = matrix[j][i]\n matrix[j][i] = temp\n }\n }\n}",
"const rotate = function (matrix) {\n matrix.reverse()\n for (let i = 0; i < matrix.length; ++i) {\n for (let j = i + 1; j < matrix[i].length; ++j) swap(matrix, i, j)\n }\n}\n\nfunction swap(matrix, i, j) {\n const tmp = matrix[j][i]\n matrix[j][i] = matrix[i][j]\n matrix[i][j] = tmp\n}",
"const rotate = function (matrix) {\n matrix.reverse()\n for (let i = 0; i < matrix.length; ++i) {\n for (let j = matrix[i].length - 1; j > i; j--) swap(matrix, i, j)\n }\n}\n\nfunction swap(matrix, i, j) {\n const tmp = matrix[j][i]\n matrix[j][i] = matrix[i][j]\n matrix[i][j] = tmp\n}"
] |
|
49 | group-anagrams | [] | /**
* @param {string[]} strs
* @return {string[][]}
*/
var groupAnagrams = function(strs) {
}; | Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Example 1:
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Example 2:
Input: strs = [""]
Output: [[""]]
Example 3:
Input: strs = ["a"]
Output: [["a"]]
Constraints:
1 <= strs.length <= 104
0 <= strs[i].length <= 100
strs[i] consists of lowercase English letters.
| Medium | [
"array",
"hash-table",
"string",
"sorting"
] | [
"const groupAnagrams = (strs) => {\n const resp = new Array(),\n termsGrouped = new Map()\n strs.forEach((term) => {\n const hashed = hash(term)\n if (!termsGrouped.has(hashed)) termsGrouped.set(hashed, new Array())\n termsGrouped.get(hashed).push(term)\n })\n termsGrouped.forEach((terms) => {\n resp.push(terms)\n })\n return resp\n}\n\nconst hash = (term) => {\n const arr = Array(26).fill(0)\n const a = 'a'.charCodeAt(0)\n for(let i = 0, len = term.length; i < len; i++) {\n arr[term[i].charCodeAt(0) - a]++\n }\n return arr.join('-')\n}",
"const groupAnagrams = function(strs) {\n if (strs.length === 0) {\n return [];\n }\n const ans = [];\n const hash = {};\n for (let el of strs) {\n let sel = el\n .split(\"\")\n .sort()\n .join(\"\");\n if (hash.hasOwnProperty(sel)) {\n hash[sel].push(el);\n } else {\n hash[sel] = [el];\n }\n }\n return Object.values(hash);\n};"
] |
|
50 | powx-n | [] | /**
* @param {number} x
* @param {number} n
* @return {number}
*/
var myPow = function(x, n) {
}; | Implement pow(x, n), which calculates x raised to the power n (i.e., xn).
Example 1:
Input: x = 2.00000, n = 10
Output: 1024.00000
Example 2:
Input: x = 2.10000, n = 3
Output: 9.26100
Example 3:
Input: x = 2.00000, n = -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25
Constraints:
-100.0 < x < 100.0
-231 <= n <= 231-1
n is an integer.
Either x is not zero or n > 0.
-104 <= xn <= 104
| Medium | [
"math",
"recursion"
] | [
"const myPow = function(x, n) {\n if (n === 0) return 1;\n if (n === 1) return x;\n if (x === 0) return 0;\n\n if (n > 0) {\n return (n % 2 === 1 ? x : 1) * myPow(x * x, Math.floor(n / 2));\n } else {\n return myPow(1 / x, -n);\n }\n};",
"const myPow = function(x, n) {\n if(n === 0) return 1\n if(n === 1) return x\n if(n < 0) {\n x = 1 / x\n n = -n\n }\n return n % 2 === 1 ? myPow(x, ~~(n / 2)) ** 2 * x : myPow(x, ~~(n / 2)) ** 2\n};",
"const myPow = function (x, n) {\n if (n === 0) return 1\n if (n < 0) {\n if (n === -(2 ** 31)) {\n ++n\n n = -n\n x = 1 / x\n return x * x * myPow(x * x, n / 2)\n }\n n = -n\n x = 1 / x\n }\n return n % 2 == 0 ? myPow(x * x, n / 2) : x * myPow(x * x, (n / 2) >> 0)\n}",
"const myPow = function (x, n) {\n if (n === 0) return 1\n if (n < 0) {\n n = -n\n x = 1 / x\n }\n let res = 1\n while (n > 0) {\n if (n & 1) {\n res *= x\n --n\n }\n x *= x\n n /= 2\n }\n return res\n}"
] |
|
51 | n-queens | [] | /**
* @param {number} n
* @return {string[][]}
*/
var solveNQueens = function(n) {
}; | The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle. You may return the answer in any order.
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 1:
Input: n = 4
Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above
Example 2:
Input: n = 1
Output: [["Q"]]
Constraints:
1 <= n <= 9
| Hard | [
"array",
"backtracking"
] | [
"const solveNQueens = function(n) {\n const res = []\n const chess = Array.from({length: n}, () => new Array(n).fill('.'))\n bt(res, chess, 0)\n return res\n}\n\nfunction bt(res, chess, row) {\n if(row === chess.length) {\n res.push(build(chess))\n return\n }\n for(let i = 0, num = chess[0].length; i < num; i++) {\n if(valid(chess, row, i)) {\n chess[row][i] = 'Q'\n bt(res, chess, row + 1)\n chess[row][i] = '.'\n }\n }\n}\n\nfunction valid(chess, row, col) {\n for(let i = row - 1; i >= 0; i--) {\n if(chess[i][col] === 'Q') return false\n }\n for(let i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {\n if(chess[i][j] === 'Q') return false\n }\n for(let i = row - 1, j = col + 1; i >= 0 && j < chess[0].length; i--, j++) {\n if(chess[i][j] === 'Q') return false\n }\n return true\n}\n\nfunction build(chess) {\n return chess.map(el => el.join(''))\n}",
"const solveNQueens = function(n) {\n const res = []\n bt(res, n)\n return res\n}\n\nfunction bt(res, n, board = [], r = 0) {\n if (r === n) {\n res.push(board.map(c => '.'.repeat(c) + 'Q' + '.'.repeat(n - c - 1)))\n return\n }\n for (let c = 0; c < n; c++) {\n if (\n !board.some(\n (bc, br) => bc === c || bc === c + r - br || bc === c - r + br\n )\n ) {\n board.push(c)\n bt(res, n, board, r + 1)\n board.pop()\n }\n }\n}"
] |
|
52 | n-queens-ii | [] | /**
* @param {number} n
* @return {number}
*/
var totalNQueens = function(n) {
}; | The n-queens puzzle is the problem of placing n queens on an n x 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 1:
Input: n = 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown.
Example 2:
Input: n = 1
Output: 1
Constraints:
1 <= n <= 9
| Hard | [
"backtracking"
] | [
"const totalNQueens = function(n) {\n //Keeps track of the # of valid solutions\n let count = 0;\n\n //Helps identify valid solutions\n const done = Math.pow(2, n) - 1;\n\n //Checks all possible board configurations\n const innerRecurse = function(ld, col, rd) {\n //All columns are occupied,\n //so the solution must be complete\n if (col === done) {\n count++;\n return;\n }\n\n //Gets a bit sequence with \"1\"s\n //whereever there is an open \"slot\"\n let poss = ~(ld | rd | col);\n\n //Loops as long as there is a valid\n //place to put another queen.\n while (poss & done) {\n let bit = poss & -poss;\n poss -= bit;\n innerRecurse((ld | bit) >> 1, col | bit, (rd | bit) << 1);\n }\n };\n\n innerRecurse(0, 0, 0);\n\n return count;\n};"
] |
|
53 | maximum-subarray | [] | /**
* @param {number[]} nums
* @return {number}
*/
var maxSubArray = function(nums) {
}; | Given an integer array nums, find the subarray with the largest sum, and return its sum.
Example 1:
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: The subarray [4,-1,2,1] has the largest sum 6.
Example 2:
Input: nums = [1]
Output: 1
Explanation: The subarray [1] has the largest sum 1.
Example 3:
Input: nums = [5,4,-1,7,8]
Output: 23
Explanation: The subarray [5,4,-1,7,8] has the largest sum 23.
Constraints:
1 <= nums.length <= 105
-104 <= nums[i] <= 104
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.
| Medium | [
"array",
"divide-and-conquer",
"dynamic-programming"
] | [
"const maxSubArray = function (nums) {\n let res = -1e9, sum = 0\n for(const e of nums) {\n sum += e\n res = Math.max(res, sum)\n if(sum < 0) sum = 0\n }\n return res\n}",
"const maxSubArray = function(nums) {\n let preSum = nums[0];\n let maxSum = preSum;\n for (let i = 1; i < nums.length; i++) {\n preSum = preSum > 0 ? preSum + nums[i] : nums[i];\n maxSum = Math.max(preSum, maxSum);\n }\n return maxSum;\n};",
"const maxSubArray = function(nums) {\n const n = nums.length, dp = Array(n).fill(0)\n dp[0] = nums[0]\n let res = dp[0]\n for(let i = 1; i < n; i++) {\n dp[i] = Math.max(dp[i - 1], 0) + nums[i]\n res = Math.max(res, dp[i])\n }\n return res\n};",
"const maxSubArray = function(nums) {\n return helper(nums, 0, nums.length - 1)\n};\n\nfunction helper(arr, l, r) {\n if(l > r) return -Infinity\n const mid = l + ((r - l) >> 1)\n let cur = 0, leftMax = 0, rightMax = 0\n for(let i = mid - 1; i >= l; i--) {\n cur += arr[i]\n leftMax = Math.max(leftMax, cur)\n }\n cur = 0\n for(let i = mid + 1; i <= r; i++) {\n cur += arr[i]\n rightMax = Math.max(rightMax, cur)\n }\n const res = arr[mid] + leftMax + rightMax\n const leftRes = helper(arr, l, mid - 1)\n const rightRes = helper(arr, mid + 1, r)\n \n return Math.max(res, leftRes, rightRes)\n}"
] |
|
54 | spiral-matrix | [
"Well for some problems, the best way really is to come up with some algorithms for simulation. Basically, you need to simulate what the problem asks us to do.",
"We go boundary by boundary and move inwards. That is the essential operation. First row, last column, last row, first column, and then we move inwards by 1 and repeat. That's all. That is all the simulation that we need.",
"Think about when you want to switch the progress on one of the indexes. If you progress on i out of [i, j], you'll shift in the same column. Similarly, by changing values for j, you'd be shifting in the same row.\r\nAlso, keep track of the end of a boundary so that you can move inwards and then keep repeating. It's always best to simulate edge cases like a single column or a single row to see if anything breaks or not."
] | /**
* @param {number[][]} matrix
* @return {number[]}
*/
var spiralOrder = function(matrix) {
}; | Given an m x n matrix, return all elements of the matrix in spiral order.
Example 1:
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]
Example 2:
Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]
Constraints:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100
| Medium | [
"array",
"matrix",
"simulation"
] | [
"const spiralOrder = function(matrix) {\n const res = []\n let dir = 'top'\n while(matrix.length) {\n switch (dir) {\n case 'top':\n res.push(...matrix.shift())\n dir = 'right'\n break;\n case 'right':\n for(let i = 0; i < matrix.length - 1; ) {\n res.push(matrix[i].pop())\n if (matrix[i].length === 0) {\n matrix.splice(i, 1)\n } else {\n i++\n }\n }\n dir = 'bottom'\n break;\n case 'bottom':\n res.push(...matrix.pop().reverse())\n dir = 'left'\n break;\n case 'left':\n for(let i = matrix.length - 1; i >= 0; i--) {\n res.push(matrix[i].shift())\n if (matrix[i].length === 0) {\n matrix.splice(i, 1)\n }\n }\n dir = 'top'\n break;\n }\n }\n return res\n};",
"const spiralOrder = function(matrix) {\n const res = [], m = matrix.length, n = matrix[0].length\n const dirs = [[0, 1], [1, 0], [0, -1], [-1, 0]]\n let di = 0, i = 0, j = 0, nx = 0, ny = 1\n while(true) {\n res.push(matrix[i][j])\n matrix[i][j] = Infinity\n if(chk(i, j)) {\n if(di === 0 && (j + 1 >= n || matrix[i][j + 1] === Infinity)) {\n i++\n di = 1\n } else if(di === 1 && (i + 1 >= m || matrix[i + 1][j] === Infinity)) {\n j--\n di = 2\n } else if(di === 2 && (j - 1 < 0 || matrix[i][j - 1] === Infinity)) {\n i--\n di = 3\n } else if(di === 3 && (i - 1 < 0 || matrix[i - 1][j] === Infinity)) {\n j++\n di = 0\n } else {\n i += dirs[di][0]\n j += dirs[di][1]\n }\n } else break\n }\n return res\n\n function chk(i, j) {\n for(let dir of dirs) {\n const nx = i + dir[0], ny = j + dir[1]\n if(nx >= 0 && nx < matrix.length && ny >= 0 && ny < matrix[0].length && matrix[nx][ny] !== Infinity) return true\n }\n return false\n } \n};\n "
] |
|
55 | jump-game | [] | /**
* @param {number[]} nums
* @return {boolean}
*/
var canJump = function(nums) {
}; | You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position.
Return true if you can reach the last index, or false otherwise.
Example 1:
Input: nums = [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2:
Input: nums = [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.
Constraints:
1 <= nums.length <= 104
0 <= nums[i] <= 105
| Medium | [
"array",
"dynamic-programming",
"greedy"
] | [
"const canJump = function(nums) {\n let max = 0\n for(let i = 0, len = nums.length; i < len; i++) {\n if(i <= max && nums[i] > 0) {\n max = Math.max(max, i + nums[i])\n }\n }\n return max >= nums.length - 1\n};",
"const canJump = function(nums) {\n let max = 0\n const n = nums.length\n for(let i = 0; i < n; i++) {\n if(max < i) return false\n max = Math.max(max, i + nums[i])\n if(max >= n - 1) return true\n }\n};"
] |
|
56 | merge-intervals | [] | /**
* @param {number[][]} intervals
* @return {number[][]}
*/
var merge = function(intervals) {
}; | Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.
Example 1:
Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6].
Example 2:
Input: intervals = [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.
Constraints:
1 <= intervals.length <= 104
intervals[i].length == 2
0 <= starti <= endi <= 104
| Medium | [
"array",
"sorting"
] | [
"const merge = function(intervals) {\n intervals.sort((a, b) => a[0] - b[0] || a[1] - b[1])\n const res = [intervals[0]]\n for(let i = 1, n = intervals.length; i < n; i++) {\n const [s, e] = intervals[i]\n const pre = res[res.length - 1]\n if(s <= pre[1]) {\n pre[1] = Math.max(pre[1], e)\n } else {\n res.push(intervals[i])\n }\n }\n return res\n};",
"const merge = function(intervals) {\n if(intervals == null || intervals.length === 0) return []\n intervals.sort((a, b) => a[0] === b[0] ? a[1] - b[1] : a[0] - b[0])\n const res = [intervals[0]]\n for(let i = 1, n = intervals.length; i < n; i++) {\n const last = res[res.length - 1]\n const lastEnd = last[1]\n const [s, e] = intervals[i]\n if(s > lastEnd) {\n res.push(intervals[i])\n } else {\n last[1] = Math.max(last[1], e)\n }\n }\n return res\n};",
"const merge = function(intervals) {\n const hash = {}\n intervals.forEach(el => {\n if (hash.hasOwnProperty(el.start)) {\n hash[el.start][1] = Math.max(hash[el.start][1], el.end)\n } else {\n hash[el.start] = [el.start, el.end]\n }\n })\n\n const startArr = Object.keys(hash).sort((a, b) => +a - +b)\n const res = []\n\n while(startArr.length) {\n let start = startArr.shift()\n let end = hash[start][1]\n \n for(let i = 0; i < startArr.length; ) {\n if (+startArr[i] <= end) {\n end = Math.max(end, hash[startArr[i]][1])\n startArr.shift()\n } else {\n break\n }\n }\n let ins = new Interval(+start, end)\n res.push(ins)\n\n }\n return res\n};"
] |
|
57 | insert-interval | [] | /**
* @param {number[][]} intervals
* @param {number[]} newInterval
* @return {number[][]}
*/
var insert = function(intervals, newInterval) {
}; | You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start, end] that represents the start and end of another interval.
Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary).
Return intervals after the insertion.
Example 1:
Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
Output: [[1,5],[6,9]]
Example 2:
Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
Output: [[1,2],[3,10],[12,16]]
Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].
Constraints:
0 <= intervals.length <= 104
intervals[i].length == 2
0 <= starti <= endi <= 105
intervals is sorted by starti in ascending order.
newInterval.length == 2
0 <= start <= end <= 105
| Medium | [
"array"
] | [
"const insert = function(intervals, newInterval) {\n let i = 0\n while (i < intervals.length && intervals[i][1] < newInterval[0]) i++\n while (i < intervals.length && intervals[i][0] <= newInterval[1]) {\n newInterval[0] = Math.min(newInterval[0], intervals[i][0])\n newInterval[1] = Math.max(newInterval[1], intervals[i][1])\n intervals.splice(i, 1)\n }\n intervals.splice(i, 0, newInterval)\n return intervals\n}"
] |
|
58 | length-of-last-word | [] | /**
* @param {string} s
* @return {number}
*/
var lengthOfLastWord = function(s) {
}; | Given a string s consisting of words and spaces, return the length of the last word in the string.
A word is a maximal substring consisting of non-space characters only.
Example 1:
Input: s = "Hello World"
Output: 5
Explanation: The last word is "World" with length 5.
Example 2:
Input: s = " fly me to the moon "
Output: 4
Explanation: The last word is "moon" with length 4.
Example 3:
Input: s = "luffy is still joyboy"
Output: 6
Explanation: The last word is "joyboy" with length 6.
Constraints:
1 <= s.length <= 104
s consists of only English letters and spaces ' '.
There will be at least one word in s.
| Easy | [
"string"
] | [
"const lengthOfLastWord = function(s) {\n const arr = s.split(\" \");\n for (let i = arr.length - 1; i >= 0; i--) {\n if (arr[i].length > 0) return arr[i].length;\n }\n return 0;\n};"
] |
|
59 | spiral-matrix-ii | [] | /**
* @param {number} n
* @return {number[][]}
*/
var generateMatrix = function(n) {
}; | Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.
Example 1:
Input: n = 3
Output: [[1,2,3],[8,9,4],[7,6,5]]
Example 2:
Input: n = 1
Output: [[1]]
Constraints:
1 <= n <= 20
| Medium | [
"array",
"matrix",
"simulation"
] | [
"const generateMatrix = function(n) {\n const res = [];\n for (let i = 0; i < n; i++) {\n res[i] = [];\n }\n let i = 0,\n j = 0,\n cur = 1;\n while (n > 0) {\n res[i][j] = cur++;\n n--;\n let step = n;\n while (step > 0) {\n res[i][++j] = cur++;\n step--;\n }\n step = n;\n while (step > 0) {\n res[++i][j] = cur++;\n step--;\n }\n step = n--;\n while (step > 0) {\n res[i][--j] = cur++;\n step--;\n }\n step = n;\n while (step > 0) {\n res[--i][j] = cur++;\n step--;\n }\n j++;\n }\n return res;\n};"
] |
|
60 | permutation-sequence | [] | /**
* @param {number} n
* @param {number} k
* @return {string}
*/
var getPermutation = function(n, k) {
}; | The set [1, 2, 3, ..., n] contains a total of n! unique permutations.
By listing and labeling all of the permutations in order, we get the following sequence for n = 3:
"123"
"132"
"213"
"231"
"312"
"321"
Given n and k, return the kth permutation sequence.
Example 1:
Input: n = 3, k = 3
Output: "213"
Example 2:
Input: n = 4, k = 9
Output: "2314"
Example 3:
Input: n = 3, k = 1
Output: "123"
Constraints:
1 <= n <= 9
1 <= k <= n!
| Hard | [
"math",
"recursion"
] | [
"const getPermutation = function(n, k) {\n const factorial = Array(n + 1).fill(0)\n factorial[0] = 1\n for(let i = 1; i <= n; i++) {\n factorial[i] = factorial[i - 1] * i\n }\n let res = ''\n const visited = Array(n + 1).fill(0)\n dfs(0)\n return res\n \n function dfs(idx) {\n if(idx === n) return\n \n const cnt = factorial[n - idx - 1]\n for(let i = 1; i <= n; i++) {\n if(visited[i]) continue\n if(cnt < k) {\n k -= cnt\n continue\n }\n res += i\n visited[i] = 1\n dfs(idx + 1)\n return\n }\n }\n};",
"const getPermutation = function(n, k) {\n const factorial = Array(n + 1).fill(0)\n factorial[0] = 1\n for(let i = 1, pre = 1; i <= n; i++) {\n factorial[i] = pre * i\n pre = factorial[i]\n }\n const nums = Array.from({length: n}, (_, i) => i + 1)\n \n let res = ''\n k--\n for(let i = 1; i <= n; i++) {\n const idx = ~~(k / factorial[n - i])\n res += nums[idx]\n nums.splice(idx, 1)\n k -= idx * factorial[n - i]\n }\n \n return res\n};",
"const getPermutation = function (n, k) {\n let sb = ''\n const num = []\n let fact = 1\n for (let i = 1; i <= n; i++) {\n fact *= i\n num.push(i)\n }\n for (let i = 0, l = k - 1; i < n; i++) {\n fact = Math.floor(fact / (n - i))\n const index = Math.floor(l / fact)\n sb += num.splice(index, 1)[0]\n l -= index * fact\n }\n return sb\n}",
"const getPermutation = function(n, k) {\n const factorial = []\n const nums = []\n let res = ''\n factorial[0] = 1\n for(let i = 1, sum = 1; i <= n; i++) {\n sum *= i\n factorial[i] = sum\n }\n for(let i = 1; i <= n; i++) {\n nums.push(i)\n }\n k--\n for(let i = 0; i <= n; i++) {\n const idx = ~~(k / factorial[n - i])\n res += nums[idx]\n nums.splice(idx, 1)\n k -= idx * factorial[n - i]\n }\n\n return res\n};"
] |
|
61 | rotate-list | [] | /**
* 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 rotateRight = function(head, k) {
}; | Given the head of a linked list, rotate the list to the right by k places.
Example 1:
Input: head = [1,2,3,4,5], k = 2
Output: [4,5,1,2,3]
Example 2:
Input: head = [0,1,2], k = 4
Output: [2,0,1]
Constraints:
The number of nodes in the list is in the range [0, 500].
-100 <= Node.val <= 100
0 <= k <= 2 * 109
| Medium | [
"linked-list",
"two-pointers"
] | /**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/ | [
"const rotateRight = function(head, k) {\n if (head === null || head.next === null) return head;\n const dummy = new ListNode(0);\n dummy.next = head;\n let fast = dummy,slow = dummy;\n\n let i;\n for (i = 0; fast.next != null; i++)//Get the total length \n \tfast = fast.next;\n \n for (let j = i - k % i; j > 0; j--) //Get the i-n%i th node\n \tslow = slow.next;\n \n fast.next = dummy.next; //Do the rotation\n dummy.next = slow.next;\n slow.next = null;\n \n return dummy.next;\n};",
"const rotateRight = function(head, k) {\n if(head == null) return null\n let len = 1\n let tmp = head\n while(tmp.next) {\n len++\n tmp = tmp.next\n }\n k = k % len\n if(k === 0) return head\n let tail = head\n for(let i = 1; i < len - k; i++) {\n tail = tail.next\n }\n const newHead = tail.next\n tmp.next = head\n tail.next = null\n return newHead\n};"
] |
62 | unique-paths | [] | /**
* @param {number} m
* @param {number} n
* @return {number}
*/
var uniquePaths = function(m, n) {
}; | There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time.
Given the two integers m and n, return the number of possible unique paths that the robot can take to reach the bottom-right corner.
The test cases are generated so that the answer will be less than or equal to 2 * 109.
Example 1:
Input: m = 3, n = 7
Output: 28
Example 2:
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 -> Down -> Down
2. Down -> Down -> Right
3. Down -> Right -> Down
Constraints:
1 <= m, n <= 100
| Medium | [
"math",
"dynamic-programming",
"combinatorics"
] | [
"const uniquePaths = function(m, n) {\n if(m === 0 || n === 0) return 0\n const dp = Array.from({length: m+1}, () => new Array(n+1).fill(1))\n dp[0][1] = dp[1][0] = 1\n for(let i = 1; i <= m; i++) {\n for(let j = 1; j <= n; j++) {\n dp[i][j] = dp[i - 1][j] + dp[i][j - 1]\n }\n }\n return dp[m - 1][n - 1]\n};",
"const uniquePaths = function(m, n) {\n const dp = Array(m).fill(0)\n for(let i = 0; i < n; i++) {\n dp[0] = 1\n for(let j = 1; j < m; j++) {\n dp[j] += dp[j - 1]\n }\n }\n return dp[m - 1]\n};",
"const uniquePaths = function(m, n) {\n return factorial(m+n-2)/(factorial(m - 1) * factorial(n - 1))\n};\n\nfunction factorial(n) {\n let res = 1\n while(n > 0) {\n res *= n\n n--\n }\n return res\n}"
] |
|
63 | unique-paths-ii | [
"Use dynamic programming since, from each cell, you can move to the right or down.",
"assume dp[i][j] is the number of unique paths to reach (i, j). dp[i][j] = dp[i][j -1] + dp[i - 1][j]. Be careful when you encounter an obstacle. set its value in dp to 0."
] | /**
* @param {number[][]} obstacleGrid
* @return {number}
*/
var uniquePathsWithObstacles = function(obstacleGrid) {
}; | You are given an m x n integer array grid. There is a robot initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time.
An obstacle and space are marked as 1 or 0 respectively in grid. A path that the robot takes cannot include any square that is an obstacle.
Return the number of possible unique paths that the robot can take to reach the bottom-right corner.
The testcases are generated so that the answer will be less than or equal to 2 * 109.
Example 1:
Input: obstacleGrid = [[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
Example 2:
Input: obstacleGrid = [[0,1],[0,0]]
Output: 1
Constraints:
m == obstacleGrid.length
n == obstacleGrid[i].length
1 <= m, n <= 100
obstacleGrid[i][j] is 0 or 1.
| Medium | [
"array",
"dynamic-programming",
"matrix"
] | [
"const uniquePathsWithObstacles = function(obstacleGrid) {\n const rows = obstacleGrid.length\n const cols = obstacleGrid[0].length\n const dp = Array.from({ length: rows }, () => new Array(cols).fill(0))\n if (obstacleGrid[0][0] === 1) return 0\n else dp[0][0] = 1\n let firstRowOneIdx\n let firstColOneIdx\n for (let i = 0; i < cols; i++) {\n if (obstacleGrid[0][i] === 1) {\n firstRowOneIdx = i\n break\n } else {\n dp[0][i] = 1\n }\n }\n for (let i = 0; i < rows; i++) {\n if (obstacleGrid[i][0] === 1) {\n firstColOneIdx = i\n break\n } else {\n dp[i][0] = 1\n }\n }\n\n for (let i = 1; i < rows; i++) {\n for (let j = 1; j < cols; j++) {\n if (obstacleGrid[i][j] !== 1) {\n dp[i][j] = dp[i - 1][j] + dp[i][j - 1]\n }\n }\n }\n return dp[rows - 1][cols - 1]\n}"
] |
|
64 | minimum-path-sum | [] | /**
* @param {number[][]} grid
* @return {number}
*/
var minPathSum = function(grid) {
}; | Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
Example 1:
Input: grid = [[1,3,1],[1,5,1],[4,2,1]]
Output: 7
Explanation: Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.
Example 2:
Input: grid = [[1,2,3],[4,5,6]]
Output: 12
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 200
0 <= grid[i][j] <= 200
| Medium | [
"array",
"dynamic-programming",
"matrix"
] | [
"const minPathSum = function(grid) {\n const m = grid.length;\n const n = grid[0].length;\n for (let i = 1; i < n; i++) {\n grid[0][i] += grid[0][i - 1];\n }\n for (let i = 1; i < m; i++) {\n grid[i][0] += grid[i - 1][0];\n }\n for (let i = 1; i < m; i++) {\n for (let j = 1; j < n; j++) {\n grid[i][j] += Math.min(grid[i - 1][j], grid[i][j - 1]);\n }\n }\n return grid[m - 1][n - 1];\n};"
] |
|
65 | valid-number | [] | /**
* @param {string} s
* @return {boolean}
*/
var isNumber = function(s) {
}; | A valid number can be split up into these components (in order):
A decimal number or an integer.
(Optional) An 'e' or 'E', followed by an integer.
A decimal number can be split up into these components (in order):
(Optional) A sign character (either '+' or '-').
One of the following formats:
One or more digits, followed by a dot '.'.
One or more digits, followed by a dot '.', followed by one or more digits.
A dot '.', followed by one or more digits.
An integer can be split up into these components (in order):
(Optional) A sign character (either '+' or '-').
One or more digits.
For example, all the following are valid numbers: ["2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789"], while the following are not valid numbers: ["abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53"].
Given a string s, return true if s is a valid number.
Example 1:
Input: s = "0"
Output: true
Example 2:
Input: s = "e"
Output: false
Example 3:
Input: s = "."
Output: false
Constraints:
1 <= s.length <= 20
s consists of only English letters (both uppercase and lowercase), digits (0-9), plus '+', minus '-', or dot '.'.
| Hard | [
"string"
] | [
"const isNumber = function(str) {\n let i = 0;\n let s = str;\n // 跳过前导空格\n for (; i < s.length && \" \" == s[i]; ++i);\n // 处理正负号\n if (\"+\" == s[i] || \"-\" == s[i]) ++i;\n // 处理后面数字部分\n let digit = false,\n dot = false,\n exp = false;\n for (; i < s.length; ++i) {\n if (\".\" == s[i] && !dot)\n // '.'不能出现2次,'.'前面可以没有数字\n dot = true;\n else if (\"e\" == s[i] && !exp && digit) {\n // 'e'不能出现2次,'e'前面必须有数字\n // 'e'后面不能出现'.','e'后面必须是整数(可以是正的或负的)\n dot = exp = true;\n if (i + 1 < s.length && (\"+\" == s[i + 1] || \"-\" == s[i + 1])) ++i;\n if (i + 1 >= s.length || !(s[i + 1] >= \"0\" && s[i + 1] <= \"9\"))\n return false;\n } else if (s[i] >= \"0\" && s[i] <= \"9\") digit = true;\n else break;\n }\n\n // 跳过后面空格\n for (; i < s.length && \" \" == s[i]; ++i);\n\n return digit && i == s.length;\n};"
] |
|
66 | plus-one | [] | /**
* @param {number[]} digits
* @return {number[]}
*/
var plusOne = function(digits) {
}; | You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's.
Increment the large integer by one and return the resulting array of digits.
Example 1:
Input: digits = [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Incrementing by one gives 123 + 1 = 124.
Thus, the result should be [1,2,4].
Example 2:
Input: digits = [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
Incrementing by one gives 4321 + 1 = 4322.
Thus, the result should be [4,3,2,2].
Example 3:
Input: digits = [9]
Output: [1,0]
Explanation: The array represents the integer 9.
Incrementing by one gives 9 + 1 = 10.
Thus, the result should be [1,0].
Constraints:
1 <= digits.length <= 100
0 <= digits[i] <= 9
digits does not contain any leading 0's.
| Easy | [
"array",
"math"
] | [
"const plusOne = function (digits) {\n for (let i = digits.length - 1; i >= 0; i--) {\n if (digits[i] !== 9) {\n digits[i]++\n return digits\n } else {\n digits[i] = 0\n }\n }\n digits.unshift(1)\n return digits\n}"
] |
|
67 | add-binary | [] | /**
* @param {string} a
* @param {string} b
* @return {string}
*/
var addBinary = function(a, b) {
}; | Given two binary strings a and b, return their sum as a binary string.
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
Constraints:
1 <= a.length, b.length <= 104
a and b consist only of '0' or '1' characters.
Each string does not contain leading zeros except for the zero itself.
| Easy | [
"math",
"string",
"bit-manipulation",
"simulation"
] | [
"const addBinary = function(a, b) {\n let s = ''\n let c = 0\n let i = a.length - 1\n let j = b.length - 1\n while(i >= 0 || j >= 0 || c === 1) {\n c += i >= 0 ? +a[i--] : 0\n c += j >= 0 ? +b[j--] : 0\n s = (c % 2 === 1 ? '1' : '0') + s\n c = Math.floor(c / 2)\n }\n return s\n};",
"const addBinary = function(a, b) {\n let next = false\n let res = []\n let ai = a.length - 1\n let bi = b.length - 1\n while((ai >= 0 && bi >=0) || next) {\n const tmp = (ai >= 0 ? +a[ai--] : 0) + (bi >= 0 ? +b[bi--] : 0) + (next ? 1 : 0)\n if(tmp > 1) next = true\n else next = false\n res.unshift('' + (tmp % 2))\n }\n\n while(ai >= 0) res.unshift(a[ai--])\n while(bi >= 0) res.unshift(b[bi--])\n \n return res.join('')\n};"
] |
|
68 | text-justification | [] | /**
* @param {string[]} words
* @param {number} maxWidth
* @return {string[]}
*/
var fullJustify = function(words, maxWidth) {
}; | Given an array of strings 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 does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.
For the last line of text, it should be left-justified, and no extra space is inserted between words.
Note:
A word is defined as a character sequence consisting of non-space characters only.
Each word's length is guaranteed to be greater than 0 and not exceed maxWidth.
The input array words contains at least one word.
Example 1:
Input: words = ["This", "is", "an", "example", "of", "text", "justification."], maxWidth = 16
Output:
[
"This is an",
"example of text",
"justification. "
]
Example 2:
Input: words = ["What","must","be","acknowledgment","shall","be"], maxWidth = 16
Output:
[
"What must be",
"acknowledgment ",
"shall be "
]
Explanation: Note that the last line is "shall be " instead of "shall be", because the last line must be left-justified instead of fully-justified.
Note that the second line is also left-justified because it contains only one word.
Example 3:
Input: words = ["Science","is","what","we","understand","well","enough","to","explain","to","a","computer.","Art","is","everything","else","we","do"], maxWidth = 20
Output:
[
"Science is what we",
"understand well",
"enough to explain to",
"a computer. Art is",
"everything else we",
"do "
]
Constraints:
1 <= words.length <= 300
1 <= words[i].length <= 20
words[i] consists of only English letters and symbols.
1 <= maxWidth <= 100
words[i].length <= maxWidth
| Hard | [
"array",
"string",
"simulation"
] | [
"const fullJustify = function(words, maxWidth) {\n const res = []\n let curRow = []\n let numOfChars = 0\n \n for (let w of words) {\n if (numOfChars + w.length + curRow.length > maxWidth) {\n for(let i = 0; i < maxWidth - numOfChars; i++) {\n if(curRow.length === 1) {\n curRow[0] += ' '\n } else {\n curRow[i % (curRow.length - 1)] += ' '\n }\n }\n res.push(curRow.join(''))\n curRow = []\n numOfChars = 0\n }\n curRow.push(w)\n numOfChars += w.length\n }\n\n const numOfSpace = maxWidth - numOfChars - (curRow.length - 1)\n let tail = ''\n for(let i = 0; i < numOfSpace; i++) tail += ' '\n res.push(curRow.join(' ') + tail)\n\n return res\n};",
"const fullJustify = function(words, L) {\n const res = [\"\"];\n if (words.length === 0 || L === 0) {\n return res;\n } else {\n res.shift();\n for (let i = 0, k, l; i < words.length; i += k) {\n for (\n k = l = 0;\n i + k < words.length && l + words[i + k].length <= L - k;\n k++\n ) {\n l += words[i + k].length;\n }\n let tmp = words[i];\n for (j = 0; j < k - 1; j++) {\n if (i + k >= words.length) {\n tmp += \" \";\n } else {\n // for (i = 0; i < ((L - l) / (k - 1) + (j < (L - l) % (k - 1))) - 1; i++) {\n // tmp += ' ';\n // }\n tmp += Array(\n parseInt((L - l) / (k - 1) + (j < (L - l) % (k - 1))) + 1\n ).join(\" \");\n }\n // tmp += (L - l) / (k - 1) + (j < (L - l) % (k - 1)) + ' ';\n tmp += words[i + j + 1];\n }\n // for (i = 0; i < (L - tmp.length); i++) {\n // tmp += ' '\n // }\n tmp += Array(parseInt(L - tmp.length) + 1).join(\" \");\n // tmp += L - tmp.length + ' ';\n res.push(tmp);\n }\n return res;\n }\n};"
] |
|
69 | sqrtx | [
"Try exploring all integers. (Credits: @annujoshi)",
"Use the sorted property of integers to reduced the search space. (Credits: @annujoshi)"
] | /**
* @param {number} x
* @return {number}
*/
var mySqrt = function(x) {
}; | Given a non-negative integer x, return the square root of x rounded down to the nearest integer. The returned integer should be non-negative as well.
You must not use any built-in exponent function or operator.
For example, do not use pow(x, 0.5) in c++ or x ** 0.5 in python.
Example 1:
Input: x = 4
Output: 2
Explanation: The square root of 4 is 2, so we return 2.
Example 2:
Input: x = 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned.
Constraints:
0 <= x <= 231 - 1
| Easy | [
"math",
"binary-search"
] | [
"const mySqrt = function(x) {\n let left = 0, right = x;\n while (left < right) {\n let mid = right - ((right - left) >> 1);\n if (mid * mid > x) {\n right = mid - 1;\n } else {\n left = mid;\n }\n }\n return left;\n};",
"const mySqrt = function(x) {\n r = x;\n while (r * r > x) r = ((r + x / r) / 2) | 0;\n return r;\n};",
"const mySqrt = function(x) {\n let l = 1, r = x\n if(x === 0) return 0\n while(true) {\n let mid = l + ((r - l) >> 1)\n if(mid * mid > x) r = mid - 1\n else {\n if((mid + 1) * (mid + 1) > x) return mid\n l = mid + 1\n }\n }\n};"
] |
|
70 | climbing-stairs | [
"To reach nth step, what could have been your previous steps? (Think about the step sizes)"
] | /**
* @param {number} n
* @return {number}
*/
var climbStairs = function(n) {
}; | You are climbing a staircase. It takes n steps to reach the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Example 1:
Input: n = 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
Example 2:
Input: n = 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
Constraints:
1 <= n <= 45
| Easy | [
"math",
"dynamic-programming",
"memoization"
] | [
"const climbStairs = function(n) {\n const hash = {};\n return single(n, hash);\n};\n\nfunction single(i, hash) {\n if (hash.hasOwnProperty(i)) {\n return hash[i];\n }\n if (i === 1) {\n hash[1] = 1;\n return 1;\n }\n if (i === 2) {\n hash[2] = 2;\n return 2;\n }\n hash[i] = single(i - 1, hash) + single(i - 2, hash);\n return hash[i];\n}",
"const climbStairs = function (n) {\n const dp = new Array(n + 1).fill(0)\n if (n === 1) {\n return 1\n }\n if (n === 2) {\n return 2\n }\n dp[0] = 0\n dp[1] = 1\n dp[2] = 2\n for (let i = 3; i <= n; i++) {\n dp[i] = dp[i - 1] + dp[i - 2]\n }\n return dp[n]\n}"
] |
|
71 | simplify-path | [] | /**
* @param {string} path
* @return {string}
*/
var simplifyPath = function(path) {
}; | Given a string path, which is an absolute path (starting with a slash '/') to a file or directory in a Unix-style file system, convert it to the simplified canonical path.
In a Unix-style file system, a period '.' refers to the current directory, a double period '..' refers to the directory up a level, and any multiple consecutive slashes (i.e. '//') are treated as a single slash '/'. For this problem, any other format of periods such as '...' are treated as file/directory names.
The canonical path should have the following format:
The path starts with a single slash '/'.
Any two directories are separated by a single slash '/'.
The path does not end with a trailing '/'.
The path only contains the directories on the path from the root directory to the target file or directory (i.e., no period '.' or double period '..')
Return the simplified canonical path.
Example 1:
Input: path = "/home/"
Output: "/home"
Explanation: Note that there is no trailing slash after the last directory name.
Example 2:
Input: path = "/../"
Output: "/"
Explanation: Going one level up from the root directory is a no-op, as the root level is the highest level you can go.
Example 3:
Input: path = "/home//foo/"
Output: "/home/foo"
Explanation: In the canonical path, multiple consecutive slashes are replaced by a single one.
Constraints:
1 <= path.length <= 3000
path consists of English letters, digits, period '.', slash '/' or '_'.
path is a valid absolute Unix path.
| Medium | [
"string",
"stack"
] | [
"const simplifyPath = function(path) {\n path = path.split('/').filter(s => !!s && s !== '.')\n while (path[0] === '..') path = path.slice(1)\n let result = []\n for (let val of path) {\n if (val === '..') result.pop()\n else result.push(val)\n }\n return '/' + result.join('/')\n}"
] |
|
72 | edit-distance | [] | /**
* @param {string} word1
* @param {string} word2
* @return {number}
*/
var minDistance = function(word1, word2) {
}; | Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2.
You have the following three operations permitted on a word:
Insert a character
Delete a character
Replace a character
Example 1:
Input: word1 = "horse", word2 = "ros"
Output: 3
Explanation:
horse -> rorse (replace 'h' with 'r')
rorse -> rose (remove 'r')
rose -> ros (remove 'e')
Example 2:
Input: word1 = "intention", word2 = "execution"
Output: 5
Explanation:
intention -> inention (remove 't')
inention -> enention (replace 'i' with 'e')
enention -> exention (replace 'n' with 'x')
exention -> exection (replace 'n' with 'c')
exection -> execution (insert 'u')
Constraints:
0 <= word1.length, word2.length <= 500
word1 and word2 consist of lowercase English letters.
| Medium | [
"string",
"dynamic-programming"
] | [
"const minDistance = function(word1, word2) {\n let m = word1.length, n = word2.length;\n const dp = Array.from({length: m + 1}, ()=> new Array(n+ 1).fill(0))\n for (let i = 1; i <= m; i++) {\n dp[i][0] = i;\n }\n for (let j = 1; j <= n; j++) {\n dp[0][j] = j;\n }\n for (let i = 1; i <= m; i++) {\n for (let j = 1; j <= n; j++) {\n if (word1[i - 1] === word2[j - 1]) {\n dp[i][j] = dp[i - 1][j - 1];\n } else {\n dp[i][j] = Math.min(dp[i - 1][j - 1], Math.min(dp[i][j - 1], dp[i - 1][j])) + 1;\n }\n }\n }\n return dp[m][n];\n};",
"const minDistance = function(word1, word2) {\n const m = word1.length, n = word2.length\n const dp = Array(n + 1).fill(0)\n for(let i = 1; i <= n; i++) dp[i] = i \n let pre = 0\n for(let i = 1; i <= m; i++) {\n pre = dp[0]\n dp[0] = i\n for(let j = 1; j <= n; j++) {\n let tmp = dp[j]\n if(word1[i - 1] === word2[j - 1]) {\n dp[j] = pre\n } else {\n dp[j] = Math.min(pre, dp[j], dp[j - 1]) + 1\n }\n pre = tmp\n }\n }\n\n return dp[n]\n};"
] |
|
73 | set-matrix-zeroes | [
"If any cell of the matrix has a zero we can record its row and column number using additional memory.\r\nBut if you don't want to use extra memory then you can manipulate the array instead. i.e. simulating exactly what the question says.",
"Setting cell values to zero on the fly while iterating might lead to discrepancies. What if you use some other integer value as your marker?\r\nThere is still a better approach for this problem with 0(1) space.",
"We could have used 2 sets to keep a record of rows/columns which need to be set to zero. But for an O(1) space solution, you can use one of the rows and and one of the columns to keep track of this information.",
"We can use the first cell of every row and column as a flag. This flag would determine whether a row or column has been set to zero."
] | /**
* @param {number[][]} matrix
* @return {void} Do not return anything, modify matrix in-place instead.
*/
var setZeroes = function(matrix) {
}; | Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's.
You must do it in place.
Example 1:
Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[1,0,1],[0,0,0],[1,0,1]]
Example 2:
Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]]
Constraints:
m == matrix.length
n == matrix[0].length
1 <= m, n <= 200
-231 <= matrix[i][j] <= 231 - 1
Follow up:
A straightforward 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?
| Medium | [
"array",
"hash-table",
"matrix"
] | [
"const setZeroes = function(matrix) {\n const rows = []\n const cols = []\n const rowNum = matrix.length\n const colNum = matrix[0].length\n for(let i = 0; i < rowNum; i++) {\n for(let j = 0; j < colNum; j++) {\n if(matrix[i][j] === 0) {\n rows.push(i)\n cols.push(j)\n }\n }\n }\n const mrows = rows.filter((el, idx, arr) => arr.indexOf(el) === idx)\n const mcols = cols.filter((el, idx, arr) => arr.indexOf(el) === idx)\n for(let i = 0; i < mrows.length; i++) {\n matrix[mrows[i]] = new Array(colNum).fill(0)\n }\n for(let j = 0; j < mcols.length; j++) {\n for(let k = 0; k < rowNum; k++) {\n matrix[k][mcols[j]] = 0\n }\n }\n return matrix\n};"
] |
|
74 | search-a-2d-matrix | [] | /**
* @param {number[][]} matrix
* @param {number} target
* @return {boolean}
*/
var searchMatrix = function(matrix, target) {
}; | You are given an m x n integer matrix matrix with the following two properties:
Each row is sorted in non-decreasing order.
The first integer of each row is greater than the last integer of the previous row.
Given an integer target, return true if target is in matrix or false otherwise.
You must write a solution in O(log(m * n)) time complexity.
Example 1:
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
Output: true
Example 2:
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
Output: false
Constraints:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 100
-104 <= matrix[i][j], target <= 104
| Medium | [
"array",
"binary-search",
"matrix"
] | [
"const searchMatrix = function(matrix, target) {\n const rows = matrix.length\n const cols = (matrix[0] || []).length\n const r = chkRow(matrix, rows, cols, target)\n if(r === -1) return false\n for(let i = 0; i < cols; i++) {\n if(matrix[r][i] === target) return true\n }\n return false\n};\n\nfunction chkRow(matrix, rows, cols, target) {\n if(cols <= 0) return -1\n for(let i = 0; i < rows; i++) {\n if(target <= matrix[i][cols - 1]) return i\n }\n return -1\n}"
] |
|
75 | sort-colors | [
"A rather straight forward solution is a two-pass algorithm using counting sort.",
"Iterate the array counting number of 0's, 1's, and 2's.",
"Overwrite array with the total number of 0's, then 1's and followed by 2's."
] | /**
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var sortColors = function(nums) {
}; | Given an array nums 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.
We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.
You must solve this problem without using the library's sort function.
Example 1:
Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Example 2:
Input: nums = [2,0,1]
Output: [0,1,2]
Constraints:
n == nums.length
1 <= n <= 300
nums[i] is either 0, 1, or 2.
Follow up: Could you come up with a one-pass algorithm using only constant extra space?
| Medium | [
"array",
"two-pointers",
"sorting"
] | [
"const sortColors = function(nums) {\n let j = 0;\n let k = nums.length - 1;\n const swap = (a, b) => {\n const t = nums[a];\n nums[a] = nums[b];\n nums[b] = t;\n };\n for (let i = 0; i <= k; i++) {\n if (nums[i] === 2) {\n swap(i--, k--);\n } else if (nums[i] === 0) {\n swap(i, j++);\n }\n }\n};"
] |
|
76 | minimum-window-substring | [
"Use two pointers to create a window of letters in s, which would have all the characters from t.",
"Expand the right pointer until all the characters of t are covered.",
"Once all the characters are covered, move the left pointer and ensure that all the characters are still covered to minimize the subarray size.",
"Continue expanding the right and left pointers until you reach the end of s."
] | /**
* @param {string} s
* @param {string} t
* @return {string}
*/
var minWindow = function(s, t) {
}; | Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string "".
The testcases will be generated such that the answer is unique.
Example 1:
Input: s = "ADOBECODEBANC", t = "ABC"
Output: "BANC"
Explanation: The minimum window substring "BANC" includes 'A', 'B', and 'C' from string t.
Example 2:
Input: s = "a", t = "a"
Output: "a"
Explanation: The entire string s is the minimum window.
Example 3:
Input: s = "a", t = "aa"
Output: ""
Explanation: Both 'a's from t must be included in the window.
Since the largest window of s only has one 'a', return empty string.
Constraints:
m == s.length
n == t.length
1 <= m, n <= 105
s and t consist of uppercase and lowercase English letters.
Follow up: Could you find an algorithm that runs in O(m + n) time?
| Hard | [
"hash-table",
"string",
"sliding-window"
] | [
"const minWindow = function(s, t) {\n const map = {}\n for (const c of t) {\n map[c] = (map[c] || 0) + 1\n }\n let counter = t.length\n let start = 0\n let end = 0\n let minLen = Infinity\n let minStart = 0\n while (end < s.length) {\n const eChar = s[end]\n if (map[eChar] > 0) {\n counter--\n }\n map[eChar] = (map[eChar] || 0) - 1\n end++\n while (counter === 0) {\n if (end - start < minLen) {\n minStart = start\n minLen = end - start\n }\n const sChar = s[start]\n map[sChar] = (map[sChar] || 0) + 1\n if (map[sChar] > 0) {\n counter++\n }\n start++\n }\n }\n if (minLen !== Infinity) {\n return s.substring(minStart, minStart + minLen)\n }\n return ''\n}"
] |
|
77 | combinations | [] | /**
* @param {number} n
* @param {number} k
* @return {number[][]}
*/
var combine = function(n, k) {
}; | Given two integers n and k, return all possible combinations of k numbers chosen from the range [1, n].
You may return the answer in any order.
Example 1:
Input: n = 4, k = 2
Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
Explanation: There are 4 choose 2 = 6 total combinations.
Note that combinations are unordered, i.e., [1,2] and [2,1] are considered to be the same combination.
Example 2:
Input: n = 1, k = 1
Output: [[1]]
Explanation: There is 1 choose 1 = 1 total combination.
Constraints:
1 <= n <= 20
1 <= k <= n
| Medium | [
"backtracking"
] | [
"const combine = function(n, k) {\n const res = [];\n bt(res, [], 1, n, k);\n return res;\n};\n\nfunction bt(res, tmp, start, n, k) {\n if (k === 0) {\n res.push(tmp.slice(0));\n return;\n }\n for (let i = start; i <= n - k + 1; i++) {\n tmp.push(i);\n bt(res, tmp, i + 1, n, k - 1);\n tmp.pop();\n }\n}"
] |
|
78 | subsets | [] | /**
* @param {number[]} nums
* @return {number[][]}
*/
var subsets = function(nums) {
}; | Given an integer array nums of unique elements, return all possible subsets (the power set).
The solution set must not contain duplicate subsets. Return the solution in any order.
Example 1:
Input: nums = [1,2,3]
Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
Example 2:
Input: nums = [0]
Output: [[],[0]]
Constraints:
1 <= nums.length <= 10
-10 <= nums[i] <= 10
All the numbers of nums are unique.
| Medium | [
"array",
"backtracking",
"bit-manipulation"
] | [
"function subsets(nums) {\n const list = [];\n const len = nums.length;\n const subsetNum = Math.pow(2, len);\n for (let n = 0; n < subsetNum; n++) {\n list[n] = [];\n }\n for (let i = 0; i < len; i++) {\n for (let j = 0; j < subsetNum; j++) {\n if ((j >> i) & 1) {\n list[j].push(nums[i]);\n }\n }\n }\n return list;\n}\n\nconsole.log(subsets([1, 2, 3]));",
"function subsets(nums) {\n const subs = [[]]\n for (let num of nums) {\n const n = subs.length\n for (let i = 0; i < n; i++) {\n subs.push(subs[i].slice(0))\n subs[subs.length - 1].push(num)\n }\n }\n return subs\n}"
] |
|
79 | word-search | [] | /**
* @param {character[][]} board
* @param {string} word
* @return {boolean}
*/
var exist = function(board, word) {
}; | Given an m x n grid of characters board and a string word, return true if word exists in the grid.
The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
Example 1:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
Output: true
Example 2:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
Output: true
Example 3:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
Output: false
Constraints:
m == board.length
n = board[i].length
1 <= m, n <= 6
1 <= word.length <= 15
board and word consists of only lowercase and uppercase English letters.
Follow up: Could you use search pruning to make your solution faster with a larger board?
| Medium | [
"array",
"backtracking",
"matrix"
] | [
"const exist = function(board, word) {\n const dirs = [[0, 1], [0, -1], [-1, 0], [1, 0]];\n for (let j = 0; j < board.length; j++) {\n for (let i = 0; i < board[0].length; i++) {\n let res = dfs(board, i, j, dirs, word, 0);\n if (res) {\n return true;\n }\n }\n }\n return false;\n};\n\nfunction dfs(board, x, y, dirs, word, start) {\n if (start >= word.length) return true;\n if (x < 0 || y < 0 || x >= board[0].length || y >= board.length) return false;\n if (word[start] !== board[y][x] || board[y][x] === \"#\") return false;\n\n let res = false;\n let c = board[y][x];\n board[y][x] = \"#\";\n for (let el of dirs) {\n let posx = x + el[0];\n let posy = y + el[1];\n res = res || dfs(board, posx, posy, dirs, word, start + 1);\n if (res) return true;\n }\n board[y][x] = c;\n\n return false;\n}\n\n// time complexity: O(M * N * 3^L), where L is the length of word.\n// we have a visited array and we never go back, so 3 directions",
"const exist = function(board, word) {\n if (!word || !board || board.length === 0) return false\n const dirs = [[-1, 0], [1, 0], [0, -1], [0, 1]]\n for (let row = 0; row < board.length; row++) {\n for (let col = 0; col < board[row].length; col++) {\n if (searchWord(board, row, col, word, 0, dirs)) return true\n }\n }\n return false\n}\n\nconst searchWord = (board, row, col, word, widx, dirs) => {\n if (widx === word.length) return true\n if (\n row < 0 ||\n col < 0 ||\n row === board.length ||\n col === board[0].length ||\n board[row][col] === null ||\n board[row][col] !== word[widx]\n ) return false\n\n const ch = board[row][col]\n board[row][col] = null // mark visited\n\n for (let dir of dirs) {\n if (searchWord(board, row + dir[0], col + dir[1], word, widx + 1, dirs)) {\n return true\n }\n }\n board[row][col] = ch // recover\n}"
] |
|
80 | remove-duplicates-from-sorted-array-ii | [] | /**
* @param {number[]} nums
* @return {number}
*/
var removeDuplicates = function(nums) {
}; | Given an integer array nums sorted in non-decreasing order, remove some duplicates in-place such that each unique element appears at most twice. The relative order of the elements should be kept the same.
Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.
Return k after placing the final result in the first k slots of nums.
Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.
Custom Judge:
The judge will test your solution with the following code:
int[] nums = [...]; // Input array
int[] expectedNums = [...]; // The expected answer with correct length
int k = removeDuplicates(nums); // Calls your implementation
assert k == expectedNums.length;
for (int i = 0; i < k; i++) {
assert nums[i] == expectedNums[i];
}
If all assertions pass, then your solution will be accepted.
Example 1:
Input: nums = [1,1,1,2,2,3]
Output: 5, nums = [1,1,2,2,3,_]
Explanation: Your function should return k = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
Example 2:
Input: nums = [0,0,1,1,1,1,2,3,3]
Output: 7, nums = [0,0,1,1,2,3,3,_,_]
Explanation: Your function should return k = 7, with the first seven elements of nums being 0, 0, 1, 1, 2, 3 and 3 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
Constraints:
1 <= nums.length <= 3 * 104
-104 <= nums[i] <= 104
nums is sorted in non-decreasing order.
| Medium | [
"array",
"two-pointers"
] | [
"const removeDuplicates = function(nums) {\n for(let i = 0; i < nums.length;) {\n if(i >= 0 && i - 1 >= 0 && i- 2 >= 0 && nums[i] === nums[i - 1] && nums[i] === nums[i - 2]) {\n nums.splice(i, 1)\n } else {\n i++\n }\n }\n};"
] |
|
81 | search-in-rotated-sorted-array-ii | [] | /**
* @param {number[]} nums
* @param {number} target
* @return {boolean}
*/
var search = function(nums, target) {
}; | There is an integer array nums sorted in non-decreasing order (not necessarily with distinct values).
Before being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,4,4,5,6,6,7] might be rotated at pivot index 5 and become [4,5,6,6,7,0,1,2,4,4].
Given the array nums after the rotation and an integer target, return true if target is in nums, or false if it is not in nums.
You must decrease the overall operation steps as much as possible.
Example 1:
Input: nums = [2,5,6,0,0,1,2], target = 0
Output: true
Example 2:
Input: nums = [2,5,6,0,0,1,2], target = 3
Output: false
Constraints:
1 <= nums.length <= 5000
-104 <= nums[i] <= 104
nums is guaranteed to be rotated at some pivot.
-104 <= target <= 104
Follow up: This problem is similar to Search in Rotated Sorted Array, but nums may contain duplicates. Would this affect the runtime complexity? How and why?
| Medium | [
"array",
"binary-search"
] | [
"const search = function(nums, target) {\n const len = nums.length\n if(len === 0) return false\n if(nums[0] === target) return true\n if(target > nums[0]) {\n for(let i = 1; i < len; i++) {\n if(nums[i] === target) {\n return true\n } else {\n if(nums[i] < nums[i - 1]) return false\n }\n }\n } else {\n for(let i = len - 1; i >= 0; i--) {\n if(nums[i] === target) {\n return true\n } else {\n if(nums[i] < nums[i - 1]) return false\n }\n }\n }\n return false\n};"
] |
|
82 | remove-duplicates-from-sorted-list-ii | [] | /**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var deleteDuplicates = function(head) {
}; | Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.
Example 1:
Input: head = [1,2,3,3,4,4,5]
Output: [1,2,5]
Example 2:
Input: head = [1,1,1,2,3]
Output: [2,3]
Constraints:
The number of nodes in the list is in the range [0, 300].
-100 <= Node.val <= 100
The list is guaranteed to be sorted in ascending order.
| Medium | [
"linked-list",
"two-pointers"
] | /**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/ | [
"const deleteDuplicates = function(head) {\n let dummy = new ListNode(undefined);\n dummy.next = head;\n let prev = dummy;\n let curr = head;\n \n while(curr) {\n while(curr.next && curr.next.val === curr.val) {\n curr = curr.next;\n }\n if(prev.next === curr) { // detect if it has deleted some elements\n prev = prev.next;\n curr = curr.next;\n } else {\n prev.next = curr.next;\n curr = curr.next;\n }\n }\n \n return dummy.next;\n };"
] |
83 | remove-duplicates-from-sorted-list | [] | /**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var deleteDuplicates = function(head) {
}; | Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.
Example 1:
Input: head = [1,1,2]
Output: [1,2]
Example 2:
Input: head = [1,1,2,3,3]
Output: [1,2,3]
Constraints:
The number of nodes in the list is in the range [0, 300].
-100 <= Node.val <= 100
The list is guaranteed to be sorted in ascending order.
| Easy | [
"linked-list"
] | /**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/ | [
"const deleteDuplicates = function(head) {\n let current = head;\n while (current !== null && current.next !== null) {\n if (current.val === current.next.val) {\n current.next = current.next.next;\n } else {\n current = current.next;\n }\n }\n return head;\n};",
"const deleteDuplicates = function(head) {\n let prev = null, cur = head\n while(cur) {\n if(prev && prev.val === cur.val) {\n prev.next = cur.next\n cur = cur.next\n } else {\n prev = cur\n cur = cur.next \n }\n }\n return head\n};"
] |
84 | largest-rectangle-in-histogram | [] | /**
* @param {number[]} heights
* @return {number}
*/
var largestRectangleArea = function(heights) {
}; | Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.
Example 1:
Input: heights = [2,1,5,6,2,3]
Output: 10
Explanation: The above is a histogram where width of each bar is 1.
The largest rectangle is shown in the red area, which has an area = 10 units.
Example 2:
Input: heights = [2,4]
Output: 4
Constraints:
1 <= heights.length <= 105
0 <= heights[i] <= 104
| Hard | [
"array",
"stack",
"monotonic-stack"
] | [
"const largestRectangleArea = function(heights) {\n let height = heights;\n if (height == null || height.length == 0) {\n return 0;\n }\n const lessFromLeft = new Array(height.length).fill(0);\n const lessFromRight = new Array(height.length).fill(0);\n lessFromRight[height.length - 1] = height.length;\n lessFromLeft[0] = -1;\n for (let i = 1; i < height.length; i++) {\n let p = i - 1;\n while (p >= 0 && height[p] >= height[i]) {\n p = lessFromLeft[p];\n }\n lessFromLeft[i] = p;\n }\n for (let i = height.length - 2; i >= 0; i--) {\n let p = i + 1;\n while (p < height.length && height[p] >= height[i]) {\n p = lessFromRight[p];\n }\n lessFromRight[i] = p;\n }\n let maxArea = 0;\n for (let i = 0; i < height.length; i++) {\n maxArea = Math.max(\n maxArea,\n height[i] * (lessFromRight[i] - lessFromLeft[i] - 1)\n );\n }\n return maxArea;\n};",
"const largestRectangleArea = function(heights) {\n if (!heights.length) return 0;\n let stack = [];\n let max = 0;\n for (let i = 0, cur, len = heights.length; i <= len; i++) {\n cur = i === len ? -1 : heights[i];\n while (stack.length && cur < heights[stack[stack.length - 1]]) {\n let index = stack.pop();\n let h = heights[index];\n let w = !stack.length ? i : i - stack[stack.length - 1] - 1;\n max = Math.max(max, h * w);\n }\n stack.push(i);\n }\n return max;\n};",
"const largestRectangleArea = function(heights) {\n heights.push(0)\n const st = [], n = heights.length\n let res = 0\n for(let i = 0; i <= n; i++) {\n while(st.length && heights[st[st.length - 1]] >= heights[i]) {\n const top = st.pop()\n const pre = st.length ? st[st.length - 1] : -1\n res = Math.max(res, heights[top] * (i - pre - 1))\n }\n st.push(i)\n }\n return res\n};"
] |
|
85 | maximal-rectangle | [] | /**
* @param {character[][]} matrix
* @return {number}
*/
var maximalRectangle = function(matrix) {
}; | Given a rows x cols binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
Example 1:
Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
Output: 6
Explanation: The maximal rectangle is shown in the above picture.
Example 2:
Input: matrix = [["0"]]
Output: 0
Example 3:
Input: matrix = [["1"]]
Output: 1
Constraints:
rows == matrix.length
cols == matrix[i].length
1 <= row, cols <= 200
matrix[i][j] is '0' or '1'.
| Hard | [
"array",
"dynamic-programming",
"stack",
"matrix",
"monotonic-stack"
] | [
"const maximalRectangle = function(matrix) {\n const m = matrix.length, n = matrix[0].length\n const left = Array(n).fill(0)\n const right = Array(n).fill(n - 1)\n const height = Array(n).fill(0)\n \n let res = 0\n \n for(let i = 0; i < m; i++) {\n let l = 0, r = n - 1\n for(let j = 0; j < n; j++) {\n if(matrix[i][j] === '1') left[j] = Math.max(left[j], l)\n else {\n left[j] = 0\n l = j + 1\n }\n }\n \n for(let j = n - 1; j >= 0; j--) {\n if(matrix[i][j] === '1') right[j] = Math.min(right[j], r)\n else {\n right[j] = n - 1\n r = j - 1\n }\n }\n\n for(let j = 0; j < n; j++) {\n height[j] = matrix[i][j] === '1' ? height[j] + 1 : 0\n res = Math.max(res, (right[j] - left[j] + 1) * height[j])\n }\n \n // console.log(left, right, height)\n }\n \n return res\n};",
"const maximalRectangle = function(matrix) {\n if(matrix.length === 0) return 0;\n const m = matrix.length; // rows\n const n = matrix[0].length; // cols\n const left = new Array(n).fill(0)\n const right = new Array(n).fill(n)\n const height = new Array(n).fill(0);\n let maxA = 0;\n for(let i = 0; i < m; i++) {\n let cur_left = 0, cur_right = n;\n // compute height (can do this from either side)\n for(let j = 0; j < n; j++) {\n if(matrix[i][j] === '1') height[j]++; \n else height[j] = 0;\n }\n // compute left (from left to right)\n for(let j = 0; j < n; j++) {\n if(matrix[i][j] ==='1') left[j] = Math.max(left[j], cur_left);\n else {left[j] = 0; cur_left = j + 1;}\n }\n // compute right (from right to left)\n for(let j = n - 1; j >= 0; j--) {\n if(matrix[i][j] === '1') right[j] = Math.min(right[j], cur_right);\n else {right[j] = n; cur_right = j;} \n }\n // compute the area of rectangle (can do this from either side)\n for(let j = 0; j < n; j++) {\n maxA = Math.max(maxA, (right[j] - left[j]) * height[j]); \n }\n }\n return maxA; \n};",
"const maximalRectangle = function(matrix) {\n if (matrix == null || matrix.length === 0 || matrix[0] == null || matrix[0].length === 0) return 0;\n let m = matrix.length, n = matrix[0].length, maxArea = 0;\n\n const left = new Array(n).fill(0)\n const right = new Array(n).fill(n - 1)\n const height = new Array(n).fill(0)\n for (let i = 0; i < m; i++) {\n let rB = n - 1;\n for (let j = n - 1; j >= 0; j--) {\n if (matrix[i][j] === '1') {\n right[j] = Math.min(right[j], rB);\n } else {\n right[j] = n - 1;\n rB = j - 1;\n }\n }\n let lB = 0;\n for (let j = 0; j < n; j++) {\n if (matrix[i][j] === '1') {\n left[j] = Math.max(left[j], lB);\n height[j]++;\n maxArea = Math.max(maxArea, height[j] * (right[j] - left[j] + 1));\n } else {\n height[j] = 0;\n left[j] = 0;\n lB = j + 1;\n }\n }\n }\n return maxArea;\n};"
] |
|
86 | partition-list | [] | /**
* 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} x
* @return {ListNode}
*/
var partition = function(head, x) {
}; | Given the head of 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 1:
Input: head = [1,4,3,2,5,2], x = 3
Output: [1,2,2,4,3,5]
Example 2:
Input: head = [2,1], x = 2
Output: [1,2]
Constraints:
The number of nodes in the list is in the range [0, 200].
-100 <= Node.val <= 100
-200 <= x <= 200
| Medium | [
"linked-list",
"two-pointers"
] | /**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/ | [
"const partition = function(head, x) {\n const leftHead = new ListNode(); \n const rightHead = new ListNode(); \n let left = leftHead;\n let right = rightHead;\n \n // split list into two sides, left if val < x, else right\n for (let node = head; node !== null; node = node.next) {\n if (node.val < x) {\n left.next = node;\n left = node;\n } else {\n right.next = node;\n right = node;\n }\n }\n \n // combine the two sides\n left.next = rightHead.next;\n right.next = null;\n \n return leftHead.next;\n};",
"const partition = function(head, x) {\n const left = []\n const right = []\n let containX = false\n let cur = head\n while(cur !== null) {\n if (containX === true) {\n if (cur.val < x) {\n left.push(cur)\n } else {\n right.push(cur)\n }\n } else {\n if (cur.val >= x) {\n containX = true\n right.push(cur)\n } else {\n left.push(cur)\n }\n }\n cur = cur.next\n }\n const arr = left.concat(right)\n \n for(let i = 0; i < arr.length; i++) {\n if (i === arr.length - 1) {\n arr[i].next = null\n } else {\n arr[i].next = arr[i+1]\n }\n }\n return arr[0] == null ? null : arr[0]\n};"
] |
End of preview. Expand
in Data Studio
- Downloads last month
- 23