QID
int64 1
2.85k
| titleSlug
stringlengths 3
77
| Hints
list | Code
stringlengths 80
1.34k
| Body
stringlengths 190
4.55k
| Difficulty
stringclasses 3
values | Topics
list | Definitions
stringclasses 14
values | Solutions
list |
---|---|---|---|---|---|---|---|---|
790 | domino-and-tromino-tiling | []
| /**
* @param {number} n
* @return {number}
*/
var numTilings = function(n) {
}; | You have two types of tiles: a 2 x 1 domino shape and a tromino shape. You may rotate these shapes.
Given an integer n, return the number of ways to tile an 2 x n board. Since the answer may be very large, return it modulo 109 + 7.
In a tiling, every square must be covered by a tile. Two tilings are different if and only if there are two 4-directionally adjacent cells on the board such that exactly one of the tilings has both squares occupied by a tile.
Example 1:
Input: n = 3
Output: 5
Explanation: The five different ways are show above.
Example 2:
Input: n = 1
Output: 1
Constraints:
1 <= n <= 1000
| Medium | [
"dynamic-programming"
]
| null | []
|
791 | custom-sort-string | []
| /**
* @param {string} order
* @param {string} s
* @return {string}
*/
var customSortString = function(order, s) {
}; | You are given two strings order and s. All the characters of order are unique and were sorted in some custom order previously.
Permute the characters of s so that they match the order that order was sorted. More specifically, if a character x occurs before a character y in order, then x should occur before y in the permuted string.
Return any permutation of s that satisfies this property.
Example 1:
Input: order = "cba", s = "abcd"
Output: "cbad"
Explanation:
"a", "b", "c" appear in order, so the order of "a", "b", "c" should be "c", "b", and "a".
Since "d" does not appear in order, it can be at any position in the returned string. "dcba", "cdba", "cbda" are also valid outputs.
Example 2:
Input: order = "cbafg", s = "abcd"
Output: "cbad"
Constraints:
1 <= order.length <= 26
1 <= s.length <= 200
order and s consist of lowercase English letters.
All the characters of order are unique.
| Medium | [
"hash-table",
"string",
"sorting"
]
| [
"const customSortString = function(S, T) {\n const arr = [];\n const remaining = [];\n const hash = {};\n for (let i = 0; i < S.length; i++) {\n if (T.indexOf(S.charAt(i)) !== -1) {\n arr.push(S.charAt(i));\n }\n }\n let char;\n for (let j = 0; j < T.length; j++) {\n char = T.charAt(j);\n if (arr.indexOf(char) === -1 && remaining.indexOf(char) === -1) {\n remaining.push(char);\n }\n hash[char] = hash.hasOwnProperty(char) ? hash[char] + 1 : 1;\n }\n return `${genPart(arr, hash)}${genPart(remaining, hash)}`;\n};\n\nfunction constructStr(char, num) {\n let str = \"\";\n for (let i = 0; i < num; i++) {\n str += char;\n }\n return str;\n}\n\nfunction genPart(arr, hash) {\n return arr.reduce((ac, el) => {\n return ac + constructStr(el, hash[el]);\n }, \"\");\n}\n\nconsole.log(customSortString(\"kqep\", \"pekeq\"));\nconsole.log(\n customSortString(\n \"hucw\",\n \"utzoampdgkalexslxoqfkdjoczajxtuhqyxvlfatmptqdsochtdzgypsfkgqwbgqbcamdqnqztaqhqanirikahtmalzqjjxtqfnh\"\n )\n);"
]
|
|
792 | number-of-matching-subsequences | []
| /**
* @param {string} s
* @param {string[]} words
* @return {number}
*/
var numMatchingSubseq = function(s, words) {
}; | Given a string s and an array of strings words, return the number of words[i] that is a subsequence of s.
A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
For example, "ace" is a subsequence of "abcde".
Example 1:
Input: s = "abcde", words = ["a","bb","acd","ace"]
Output: 3
Explanation: There are three strings in words that are a subsequence of s: "a", "acd", "ace".
Example 2:
Input: s = "dsahjpjauf", words = ["ahjpjau","ja","ahbwzgqnuk","tnmlanowax"]
Output: 2
Constraints:
1 <= s.length <= 5 * 104
1 <= words.length <= 5000
1 <= words[i].length <= 50
s and words[i] consist of only lowercase English letters.
| Medium | [
"array",
"hash-table",
"string",
"binary-search",
"dynamic-programming",
"trie",
"sorting"
]
| [
"const numMatchingSubseq = function(s, words) {\n const hash = {}\n for(let w of words) {\n if(hash[w[0]] == null) hash[w[0]] = []\n const it = w[Symbol.iterator]()\n hash[w[0]].push( it )\n it.next()\n }\n let res = 0\n for(let ch of s) {\n const advance = hash[ch] || []\n hash[ch] = []\n for(let it of advance) {\n const obj = it.next()\n if(obj.done === false) {\n if(hash[obj.value] == null) hash[obj.value] = []\n hash[obj.value].push(it)\n } else {\n res++\n }\n }\n }\n\n return res\n};",
"const numMatchingSubseq = function(S, words) {\n let res=0;\n for(let i=0;i<words.length;i++){\n let lastIdx=-1,isSub=true\n for(let j=0;j<words[i].length;j++){\n const curAlp=words[i][j]\n const curIdx=S.indexOf(curAlp,lastIdx+1)\n if(curIdx===-1){\n isSub=false;\n break;\n }\n lastIdx=curIdx\n }\n if(isSub)res++\n }\n return res\n };",
"const numMatchingSubseq = function(s, words) {\n const hash = {}\n for(const w of words) {\n const ch = w[0], it = w[Symbol.iterator]()\n if(hash[ch] == null) hash[ch] = []\n hash[ch].push(it)\n it.next()\n }\n let res = 0\n for(const e of s) {\n const arr = hash[e] || []\n hash[e] = []\n for(const it of arr) {\n const { value, done } = it.next()\n if(done) res++\n else {\n if(hash[value] == null) hash[value] = []\n hash[value].push(it)\n }\n }\n }\n \n return res\n};"
]
|
|
793 | preimage-size-of-factorial-zeroes-function | []
| /**
* @param {number} k
* @return {number}
*/
var preimageSizeFZF = function(k) {
}; | Let f(x) be the number of zeroes at the end of x!. Recall that x! = 1 * 2 * 3 * ... * x and by convention, 0! = 1.
For example, f(3) = 0 because 3! = 6 has no zeroes at the end, while f(11) = 2 because 11! = 39916800 has two zeroes at the end.
Given an integer k, return the number of non-negative integers x have the property that f(x) = k.
Example 1:
Input: k = 0
Output: 5
Explanation: 0!, 1!, 2!, 3!, and 4! end with k = 0 zeroes.
Example 2:
Input: k = 5
Output: 0
Explanation: There is no x such that x! ends in k = 5 zeroes.
Example 3:
Input: k = 3
Output: 5
Constraints:
0 <= k <= 109
| Hard | [
"math",
"binary-search"
]
| [
"const preimageSizeFZF = function(K) {\n let last = 1\n while (last < K) last = last * 5 + 1\n while (last > 1) {\n K %= last\n if (last - 1 == K) return 0\n last = ((last - 1) / 5) >> 0\n }\n return 5\n}"
]
|
|
794 | valid-tic-tac-toe-state | []
| /**
* @param {string[]} board
* @return {boolean}
*/
var validTicTacToe = function(board) {
}; | Given a Tic-Tac-Toe board as a string array board, return true if and only if it is possible to reach this board position during the course of a valid tic-tac-toe game.
The board is a 3 x 3 array that consists of characters ' ', 'X', and 'O'. The ' ' character represents an empty square.
Here are the rules of Tic-Tac-Toe:
Players take turns placing characters into empty squares ' '.
The first player always places 'X' characters, while the second player always places 'O' characters.
'X' and 'O' characters are always placed into empty squares, never filled ones.
The game ends when there are three of the same (non-empty) character filling any row, column, or diagonal.
The game also ends if all squares are non-empty.
No more moves can be played if the game is over.
Example 1:
Input: board = ["O "," "," "]
Output: false
Explanation: The first player always plays "X".
Example 2:
Input: board = ["XOX"," X "," "]
Output: false
Explanation: Players take turns making moves.
Example 3:
Input: board = ["XOX","O O","XOX"]
Output: true
Constraints:
board.length == 3
board[i].length == 3
board[i][j] is either 'X', 'O', or ' '.
| Medium | [
"array",
"string"
]
| [
"const validTicTacToe = function(board) {\n if (board.length == 0) return false\n // turns = 0 represents 'X' will move, otherwise, 'O' will move\n let turns = 0\n // check whether 'X' wins or 'O' wins, or no players win\n let xWin = isGameOver(board, 'X')\n let oWin = isGameOver(board, 'O')\n\n for (let i = 0; i < board.length; i++) {\n for (let j = 0; j < board[0].length; j++) {\n if (board[i].charAt(j) == 'X') turns++\n else if (board[i].charAt(j) == 'O') turns--\n }\n }\n\n \n if (turns < 0 || turns > 1 || (turns == 0 && xWin) || (turns == 1 && oWin))\n return false\n return true\n}\n\nfunction isGameOver(board, player) {\n // check horizontal\n for (let i = 0; i < 3; i++) {\n if (\n board[i].charAt(0) === player &&\n board[i].charAt(0) === board[i].charAt(1) &&\n board[i].charAt(1) === board[i].charAt(2)\n ) {\n return true\n }\n }\n\n // check vertical\n for (let j = 0; j < 3; j++) {\n if (\n board[0].charAt(j) == player &&\n board[0].charAt(j) == board[1].charAt(j) &&\n board[1].charAt(j) == board[2].charAt(j)\n ) {\n return true\n }\n }\n\n // check diagonal\n if (\n board[1].charAt(1) == player &&\n ((board[0].charAt(0) == board[1].charAt(1) &&\n board[1].charAt(1) == board[2].charAt(2)) ||\n (board[0].charAt(2) == board[1].charAt(1) &&\n board[1].charAt(1) == board[2].charAt(0)))\n ) {\n return true\n }\n return false\n}"
]
|
|
795 | number-of-subarrays-with-bounded-maximum | []
| /**
* @param {number[]} nums
* @param {number} left
* @param {number} right
* @return {number}
*/
var numSubarrayBoundedMax = function(nums, left, right) {
}; | Given an integer array nums and two integers left and right, return the number of contiguous non-empty subarrays such that the value of the maximum array element in that subarray is in the range [left, right].
The test cases are generated so that the answer will fit in a 32-bit integer.
Example 1:
Input: nums = [2,1,4,3], left = 2, right = 3
Output: 3
Explanation: There are three subarrays that meet the requirements: [2], [2, 1], [3].
Example 2:
Input: nums = [2,9,2,5,6], left = 2, right = 8
Output: 7
Constraints:
1 <= nums.length <= 105
0 <= nums[i] <= 109
0 <= left <= right <= 109
| Medium | [
"array",
"two-pointers"
]
| [
"const numSubarrayBoundedMax = function(A, L, R) {\n let res = 0;\n let j = 0;\n let count = 0;\n for(let i = 0; i < A.length; i++) {\n if(A[i] >= L && A[i] <= R) {\n res += i - j + 1\n count = i - j + 1\n } else if(A[i] < L) {\n res += count\n } else {\n j = i + 1\n count = 0\n }\n }\n return res\n};",
"const numSubarrayBoundedMax = function(nums, left, right) {\n let prev = -1, dp = 0, res = 0\n for(let i = 0, n = nums.length; i < n; i++) {\n const cur = nums[i]\n if(cur < left) res += dp\n else if(cur > right) {\n dp = 0\n prev = i\n } else {\n dp = i - prev\n res += dp\n }\n }\n return res\n};"
]
|
|
796 | rotate-string | []
| /**
* @param {string} s
* @param {string} goal
* @return {boolean}
*/
var rotateString = function(s, goal) {
}; | Given two strings s and goal, return true if and only if s can become goal after some number of shifts on s.
A shift on s consists of moving the leftmost character of s to the rightmost position.
For example, if s = "abcde", then it will be "bcdea" after one shift.
Example 1:
Input: s = "abcde", goal = "cdeab"
Output: true
Example 2:
Input: s = "abcde", goal = "abced"
Output: false
Constraints:
1 <= s.length, goal.length <= 100
s and goal consist of lowercase English letters.
| Easy | [
"string",
"string-matching"
]
| [
"const rotateString = function(A, B) {\n if (A.length != B.length) return false;\n return A.concat(A).includes(B);\n};"
]
|
|
797 | all-paths-from-source-to-target | []
| /**
* @param {number[][]} graph
* @return {number[][]}
*/
var allPathsSourceTarget = function(graph) {
}; | Given a directed acyclic graph (DAG) of n nodes labeled from 0 to n - 1, find all possible paths from node 0 to node n - 1 and return them in any order.
The graph is given as follows: graph[i] is a list of all nodes you can visit from node i (i.e., there is a directed edge from node i to node graph[i][j]).
Example 1:
Input: graph = [[1,2],[3],[3],[]]
Output: [[0,1,3],[0,2,3]]
Explanation: There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3.
Example 2:
Input: graph = [[4,3,1],[3,2,4],[3],[4],[]]
Output: [[0,4],[0,3,4],[0,1,3,4],[0,1,2,3,4],[0,1,4]]
Constraints:
n == graph.length
2 <= n <= 15
0 <= graph[i][j] < n
graph[i][j] != i (i.e., there will be no self-loops).
All the elements of graph[i] are unique.
The input graph is guaranteed to be a DAG.
| Medium | [
"backtracking",
"depth-first-search",
"breadth-first-search",
"graph"
]
| [
"const allPathsSourceTarget = function(graph) {\n const res = []\n const path = []\n bt(graph, res, path, 0)\n return res\n};\n\nfunction bt(g, res, path, cur) {\n path.push(cur)\n if(cur === g.length - 1) res.push(path.slice())\n else {\n for(let i of g[cur]) bt(g, res, path, i)\n }\n path.pop()\n}"
]
|
|
798 | smallest-rotation-with-highest-score | []
| /**
* @param {number[]} nums
* @return {number}
*/
var bestRotation = function(nums) {
}; | You are given an array nums. You can rotate it by a non-negative integer k so that the array becomes [nums[k], nums[k + 1], ... nums[nums.length - 1], nums[0], nums[1], ..., nums[k-1]]. Afterward, any entries that are less than or equal to their index are worth one point.
For example, if we have nums = [2,4,1,3,0], and we rotate by k = 2, it becomes [1,3,0,2,4]. This is worth 3 points because 1 > 0 [no points], 3 > 1 [no points], 0 <= 2 [one point], 2 <= 3 [one point], 4 <= 4 [one point].
Return the rotation index k that corresponds to the highest score we can achieve if we rotated nums by it. If there are multiple answers, return the smallest such index k.
Example 1:
Input: nums = [2,3,1,4,0]
Output: 3
Explanation: Scores for each k are listed below:
k = 0, nums = [2,3,1,4,0], score 2
k = 1, nums = [3,1,4,0,2], score 3
k = 2, nums = [1,4,0,2,3], score 3
k = 3, nums = [4,0,2,3,1], score 4
k = 4, nums = [0,2,3,1,4], score 3
So we should choose k = 3, which has the highest score.
Example 2:
Input: nums = [1,3,0,2,4]
Output: 0
Explanation: nums will always have 3 points no matter how it shifts.
So we will choose the smallest k, which is 0.
Constraints:
1 <= nums.length <= 105
0 <= nums[i] < nums.length
| Hard | [
"array",
"prefix-sum"
]
| [
"const bestRotation = function(A) {\n const N = A.length\n const bad = new Array(N).fill(0)\n for (let i = 0; i < N; ++i) {\n let left = (i - A[i] + 1 + N) % N\n let right = (i + 1) % N\n bad[left]--\n bad[right]++\n if (left > right) bad[0]--\n }\n\n let best = -N\n let ans = 0,\n cur = 0\n for (let i = 0; i < N; ++i) {\n cur += bad[i]\n if (cur > best) {\n best = cur\n ans = i\n }\n }\n return ans\n}",
"var bestRotation = function(nums) {\n const n = nums.length\n const arr = Array(n).fill(0)\n for(let i = 0; i < n; i++) {\n arr[(i - nums[i] + 1 + n) % n] -= 1\n }\n let res = 0\n for(let i = 1; i < n; i++) {\n arr[i] += arr[i - 1] + 1\n if(arr[i] > arr[res]) res = i\n }\n return res\n};"
]
|
|
799 | champagne-tower | []
| /**
* @param {number} poured
* @param {number} query_row
* @param {number} query_glass
* @return {number}
*/
var champagneTower = function(poured, query_row, query_glass) {
}; | We stack glasses in a pyramid, where the first row has 1 glass, the second row has 2 glasses, and so on until the 100th row. Each glass holds one cup of champagne.
Then, some champagne is poured into the first glass at the top. When the topmost glass is full, any excess liquid poured will fall equally to the glass immediately to the left and right of it. When those glasses become full, any excess champagne will fall equally to the left and right of those glasses, and so on. (A glass at the bottom row has its excess champagne fall on the floor.)
For example, after one cup of champagne is poured, the top most glass is full. After two cups of champagne are poured, the two glasses on the second row are half full. After three cups of champagne are poured, those two cups become full - there are 3 full glasses total now. After four cups of champagne are poured, the third row has the middle glass half full, and the two outside glasses are a quarter full, as pictured below.
Now after pouring some non-negative integer cups of champagne, return how full the jth glass in the ith row is (both i and j are 0-indexed.)
Example 1:
Input: poured = 1, query_row = 1, query_glass = 1
Output: 0.00000
Explanation: We poured 1 cup of champange to the top glass of the tower (which is indexed as (0, 0)). There will be no excess liquid so all the glasses under the top glass will remain empty.
Example 2:
Input: poured = 2, query_row = 1, query_glass = 1
Output: 0.50000
Explanation: We poured 2 cups of champange to the top glass of the tower (which is indexed as (0, 0)). There is one cup of excess liquid. The glass indexed as (1, 0) and the glass indexed as (1, 1) will share the excess liquid equally, and each will get half cup of champange.
Example 3:
Input: poured = 100000009, query_row = 33, query_glass = 17
Output: 1.00000
Constraints:
0 <= poured <= 109
0 <= query_glass <= query_row < 100
| Medium | [
"dynamic-programming"
]
| [
"const champagneTower = function(poured, query_row, query_glass) {\n let curRow = [poured]\n for(let i = 0; i <= query_row; i++) {\n const nxtRow = Array(i + 2).fill(0)\n for(let j = 0; j <= i; j++) {\n if(curRow[j] > 1) {\n nxtRow[j] += (curRow[j] - 1) / 2\n nxtRow[j + 1] += (curRow[j] - 1) / 2\n curRow[j] = 1\n }\n }\n if(i !== query_row) curRow = nxtRow\n }\n \n return curRow[query_glass]\n};"
]
|
|
801 | minimum-swaps-to-make-sequences-increasing | []
| /**
* @param {number[]} nums1
* @param {number[]} nums2
* @return {number}
*/
var minSwap = function(nums1, nums2) {
}; | You are given two integer arrays of the same length nums1 and nums2. In one operation, you are allowed to swap nums1[i] with nums2[i].
For example, if nums1 = [1,2,3,8], and nums2 = [5,6,7,4], you can swap the element at i = 3 to obtain nums1 = [1,2,3,4] and nums2 = [5,6,7,8].
Return the minimum number of needed operations to make nums1 and nums2 strictly increasing. The test cases are generated so that the given input always makes it possible.
An array arr is strictly increasing if and only if arr[0] < arr[1] < arr[2] < ... < arr[arr.length - 1].
Example 1:
Input: nums1 = [1,3,5,4], nums2 = [1,2,3,7]
Output: 1
Explanation:
Swap nums1[3] and nums2[3]. Then the sequences are:
nums1 = [1, 3, 5, 7] and nums2 = [1, 2, 3, 4]
which are both strictly increasing.
Example 2:
Input: nums1 = [0,3,5,8,9], nums2 = [2,1,4,6,9]
Output: 1
Constraints:
2 <= nums1.length <= 105
nums2.length == nums1.length
0 <= nums1[i], nums2[i] <= 2 * 105
| Hard | [
"array",
"dynamic-programming"
]
| [
"const minSwap = function(A, B) {\n let swapRecord = 1, fixRecord = 0;\n for (let i = 1; i < A.length; i++) {\n if (A[i - 1] >= B[i] || B[i - 1] >= A[i]) {\n // In this case, the ith manipulation should be same as the i-1th manipulation\n // fixRecord = fixRecord;\n swapRecord++;\n } else if (A[i - 1] >= A[i] || B[i - 1] >= B[i]) {\n // In this case, the ith manipulation should be the opposite of the i-1th manipulation\n let temp = swapRecord;\n swapRecord = fixRecord + 1;\n fixRecord = temp;\n } else {\n // Either swap or fix is OK. Let's keep the minimum one\n let min = Math.min(swapRecord, fixRecord);\n swapRecord = min + 1;\n fixRecord = min;\n }\n }\n return Math.min(swapRecord, fixRecord);\n};"
]
|
|
802 | find-eventual-safe-states | []
| /**
* @param {number[][]} graph
* @return {number[]}
*/
var eventualSafeNodes = function(graph) {
}; | There is a directed graph of n nodes with each node labeled from 0 to n - 1. The graph is represented by a 0-indexed 2D integer array graph where graph[i] is an integer array of nodes adjacent to node i, meaning there is an edge from node i to each node in graph[i].
A node is a terminal node if there are no outgoing edges. A node is a safe node if every possible path starting from that node leads to a terminal node (or another safe node).
Return an array containing all the safe nodes of the graph. The answer should be sorted in ascending order.
Example 1:
Input: graph = [[1,2],[2,3],[5],[0],[5],[],[]]
Output: [2,4,5,6]
Explanation: The given graph is shown above.
Nodes 5 and 6 are terminal nodes as there are no outgoing edges from either of them.
Every path starting at nodes 2, 4, 5, and 6 all lead to either node 5 or 6.
Example 2:
Input: graph = [[1,2,3,4],[1,2],[3,4],[0,4],[]]
Output: [4]
Explanation:
Only node 4 is a terminal node, and every path starting at node 4 leads to node 4.
Constraints:
n == graph.length
1 <= n <= 104
0 <= graph[i].length <= n
0 <= graph[i][j] <= n - 1
graph[i] is sorted in a strictly increasing order.
The graph may contain self-loops.
The number of edges in the graph will be in the range [1, 4 * 104].
| Medium | [
"depth-first-search",
"breadth-first-search",
"graph",
"topological-sort"
]
| [
"const eventualSafeNodes = function (graph) {\n const ing = {},\n n = graph.length\n const outDegree = Array(n).fill(0)\n let q = []\n for (let i = 0; i < n; i++) {\n outDegree[i] = graph[i].length\n if (outDegree[i] === 0) {\n q.push(i)\n }\n for (const e of graph[i]) {\n if (ing[e] == null) ing[e] = []\n ing[e].push(i)\n }\n }\n\n for (const term of q) {\n for (const come of ing[term] || []) {\n outDegree[come]--\n if (outDegree[come] === 0) q.push(come)\n }\n }\n q.sort((a, b) => a - b)\n return q\n}",
"const eventualSafeNodes = function(graph) {\n const n = graph.length, memo = {}, visited = new Set(), res = []\n for(let i = 0; i < n; i++) {\n if(!dfs(graph, i, memo, visited)) res.push(i)\n }\n return res\n};\n\nfunction dfs(graph, node, memo, visited) {\n if(memo[node] != null) return memo[node]\n let hasCycle = false\n visited.add(node)\n for(let e of graph[node]) {\n if(visited.has(e) || dfs(graph, e, memo, visited)) {\n hasCycle = true\n break\n }\n }\n visited.delete(node)\n memo[node] = hasCycle\n return hasCycle\n}",
"const eventualSafeNodes = function(graph) {\n const res = []\n if(graph == null || graph.length === 0) return res\n const n = graph.length\n const color = Array(n).fill(0)\n for(let i = 0; i < n; i++) {\n if(bt(graph, i, color)) res.push(i)\n }\n return res\n\n function bt(graph, start, color) {\n if(color[start] !== 0) return color[start] === 1\n color[start] = 2\n for(let next of graph[start]) {\n if(!bt(graph, next, color)) return false\n }\n color[start] = 1\n return true\n }\n};"
]
|
|
803 | bricks-falling-when-hit | []
| /**
* @param {number[][]} grid
* @param {number[][]} hits
* @return {number[]}
*/
var hitBricks = function(grid, hits) {
}; | You are given an m x n binary grid, where each 1 represents a brick and 0 represents an empty space. A brick is stable if:
It is directly connected to the top of the grid, or
At least one other brick in its four adjacent cells is stable.
You are also given an array hits, which is a sequence of erasures we want to apply. Each time we want to erase the brick at the location hits[i] = (rowi, coli). The brick on that location (if it exists) will disappear. Some other bricks may no longer be stable because of that erasure and will fall. Once a brick falls, it is immediately erased from the grid (i.e., it does not land on other stable bricks).
Return an array result, where each result[i] is the number of bricks that will fall after the ith erasure is applied.
Note that an erasure may refer to a location with no brick, and if it does, no bricks drop.
Example 1:
Input: grid = [[1,0,0,0],[1,1,1,0]], hits = [[1,0]]
Output: [2]
Explanation: Starting with the grid:
[[1,0,0,0],
[1,1,1,0]]
We erase the underlined brick at (1,0), resulting in the grid:
[[1,0,0,0],
[0,1,1,0]]
The two underlined bricks are no longer stable as they are no longer connected to the top nor adjacent to another stable brick, so they will fall. The resulting grid is:
[[1,0,0,0],
[0,0,0,0]]
Hence the result is [2].
Example 2:
Input: grid = [[1,0,0,0],[1,1,0,0]], hits = [[1,1],[1,0]]
Output: [0,0]
Explanation: Starting with the grid:
[[1,0,0,0],
[1,1,0,0]]
We erase the underlined brick at (1,1), resulting in the grid:
[[1,0,0,0],
[1,0,0,0]]
All remaining bricks are still stable, so no bricks fall. The grid remains the same:
[[1,0,0,0],
[1,0,0,0]]
Next, we erase the underlined brick at (1,0), resulting in the grid:
[[1,0,0,0],
[0,0,0,0]]
Once again, all remaining bricks are still stable, so no bricks fall.
Hence the result is [0,0].
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 200
grid[i][j] is 0 or 1.
1 <= hits.length <= 4 * 104
hits[i].length == 2
0 <= xi <= m - 1
0 <= yi <= n - 1
All (xi, yi) are unique.
| Hard | [
"array",
"union-find",
"matrix"
]
| [
"const hitBricks = function (grid, hits) {\n const n = grid[0].length\n const m = hits.length\n const res = new Array(m).fill(0)\n for (const [r, c] of hits) {\n if (grid[r][c] == 1) grid[r][c] = 0\n else grid[r][c] = -1\n }\n for (let j = 0; j < n; j++) {\n getConnectedCount(grid, 0, j)\n }\n for (let i = m - 1; i >= 0; i--) {\n const [r, c] = hits[i]\n if (grid[r][c] == -1) continue\n grid[r][c] = 1\n if (isConnectedToTop(grid, r, c)) {\n res[i] = getConnectedCount(grid, r, c) - 1\n }\n }\n return res\n}\nconst isConnectedToTop = (grid, i, j) => {\n if (i == 0) return true\n const dircs = [\n [-1, 0],\n [1, 0],\n [0, -1],\n [0, 1],\n ]\n for (const [dx, dy] of dircs) {\n const nx = i + dx\n const ny = j + dy\n if (\n 0 <= nx &&\n nx < grid.length &&\n 0 <= ny &&\n ny < grid[0].length &&\n grid[nx][ny] == 2\n ) {\n return true\n }\n }\n return false\n}\n\nconst getConnectedCount = (grid, i, j) => {\n if (\n i < 0 ||\n i >= grid.length ||\n j < 0 ||\n j >= grid[0].length ||\n grid[i][j] != 1\n )\n return 0\n let count = 1\n grid[i][j] = 2\n count +=\n getConnectedCount(grid, i + 1, j) +\n getConnectedCount(grid, i - 1, j) +\n getConnectedCount(grid, i, j + 1) +\n getConnectedCount(grid, i, j - 1)\n return count\n}",
"const hitBricks = function (grid, hits) {\n const SPACE = 0\n const BRICK = 1\n const WILL_HIT = 2\n const DIRECTIONS = [\n [0, 1],\n [1, 0],\n [0, -1],\n [-1, 0],\n ]\n const rows = grid.length\n const cols = grid[0].length\n const ds = new DisjointSet(rows * cols + 1)\n\n for (const [hitR, hitC] of hits) {\n if (grid[hitR][hitC] === BRICK) {\n grid[hitR][hitC] = WILL_HIT\n }\n }\n\n function hash(r, c) {\n return r * cols + c + 1\n }\n\n function unionAround(r, c) {\n const hashed = hash(r, c)\n for (const [rDiff, cDiff] of DIRECTIONS) {\n const rNext = r + rDiff\n const cNext = c + cDiff\n if (grid[rNext] !== undefined && grid[rNext][cNext] === BRICK) {\n ds.union(hashed, hash(rNext, cNext))\n }\n }\n if (r === 0) ds.union(0, hashed)\n }\n for (let i = 0; i < grid.length; i++) {\n for (let j = 0; j < grid[i].length; j++) {\n if (grid[i][j] === BRICK) unionAround(i, j)\n }\n }\n let numBricksLeft = ds.size[ds.find(0)]\n const numBricksDropped = new Array(hits.length)\n // backwards\n for (let i = hits.length - 1; i >= 0; i--) {\n const [hitR, hitC] = hits[i]\n if (grid[hitR][hitC] === WILL_HIT) {\n grid[hitR][hitC] = BRICK\n unionAround(hitR, hitC)\n const newNumBricksLeft = ds.size[ds.find(0)]\n numBricksDropped[i] = Math.max(newNumBricksLeft - numBricksLeft - 1, 0)\n numBricksLeft = newNumBricksLeft\n } else {\n numBricksDropped[i] = 0\n }\n }\n return numBricksDropped\n}\n\nclass DisjointSet {\n constructor(n) {\n this.size = new Array(n).fill(1)\n this.parent = new Array(n)\n for (let i = 0; i < n; i++) {\n this.parent[i] = i\n }\n }\n find(x) {\n if (x === this.parent[x]) return x\n this.parent[x] = this.find(this.parent[x])\n\n return this.parent[x]\n }\n union(x, y) {\n const rootX = this.find(x)\n const rootY = this.find(y)\n if (rootX !== rootY) {\n // attach X onto Y\n this.parent[rootX] = rootY\n this.size[rootY] += this.size[rootX]\n }\n }\n}",
"const hitBricks = function(grid, hits) {\n const res = Array(hits.length).fill(0), dirs = [-1, 0, 1, 0, -1]\n for(let [r, c] of hits) {\n grid[r][c] -= 1\n }\n for(let i = 0; i < grid[0].length; i++) {\n dfs(0, i, grid)\n }\n for(let i = hits.length - 1; i >= 0; i--) {\n const [r, c] = hits[i]\n grid[r][c] += 1\n if(grid[r][c] === 1 && isConnected(r, c, grid, dirs)) {\n res[i] = dfs(r, c, grid) - 1\n }\n }\n return res\n}\nfunction dfs(i, j, grid) {\n if(i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] !== 1) return 0\n grid[i][j] = 2\n return 1 + dfs(i + 1, j, grid) + dfs(i - 1, j, grid) + dfs(i, j + 1, grid) + dfs(i, j - 1, grid)\n}\nfunction isConnected(i, j, grid, dirs) {\n if(i === 0) return true\n for(let k = 1; k < dirs.length; k++) {\n const r = i + dirs[k - 1], c = j + dirs[k]\n if(r >= 0 && r < grid.length && c >= 0 && c < grid[0].length && grid[r][c] === 2) {\n return true\n }\n }\n return false\n}",
"const hitBricks = function (grid, hits) {\n const m = grid.length,\n n = grid[0].length,\n res = Array(hits.length).fill(0),\n dirs = [\n [-1, 0],\n [1, 0],\n [0, 1],\n [0, -1],\n ];\n for (let [r, c] of hits) grid[r][c] -= 1;\n\n for (let i = 0; i < n; i++) dfs(grid, 0, i, m, n, dirs);\n\n for (let i = hits.length - 1; i >= 0; i--) {\n const [r, c] = hits[i];\n grid[r][c] += 1;\n if (grid[r][c] === 1 && connected(grid, r, c, m, n, dirs)) {\n res[i] = dfs(grid, r, c, m, n, dirs) - 1;\n }\n }\n\n return res;\n};\n\nfunction dfs(grid, i, j, m, n, dirs) {\n if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] !== 1) return 0;\n grid[i][j] = 2;\n let res = 1;\n for (let [dr, dc] of dirs) {\n res += dfs(grid, i + dr, j + dc, m, n, dirs);\n }\n return res;\n}\n\nfunction connected(grid, i, j, m, n, dirs) {\n if (i === 0) return true;\n for (let [dr, dc] of dirs) {\n const nr = i + dr,\n nc = j + dc;\n if (nr >= 0 && nr < m && nc >= 0 && nc < n && grid[nr][nc] === 2)\n return true;\n }\n\n return false;\n}"
]
|
|
804 | unique-morse-code-words | []
| /**
* @param {string[]} words
* @return {number}
*/
var uniqueMorseRepresentations = function(words) {
}; | International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows:
'a' maps to ".-",
'b' maps to "-...",
'c' maps to "-.-.", and so on.
For convenience, the full table for the 26 letters of the English alphabet is given below:
[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
Given an array of strings words where each word can be written as a concatenation of the Morse code of each letter.
For example, "cab" can be written as "-.-..--...", which is the concatenation of "-.-.", ".-", and "-...". We will call such a concatenation the transformation of a word.
Return the number of different transformations among all words we have.
Example 1:
Input: words = ["gin","zen","gig","msg"]
Output: 2
Explanation: The transformation of each word is:
"gin" -> "--...-."
"zen" -> "--...-."
"gig" -> "--...--."
"msg" -> "--...--."
There are 2 different transformations: "--...-." and "--...--.".
Example 2:
Input: words = ["a"]
Output: 1
Constraints:
1 <= words.length <= 100
1 <= words[i].length <= 12
words[i] consists of lowercase English letters.
| Easy | [
"array",
"hash-table",
"string"
]
| null | []
|
805 | split-array-with-same-average | []
| /**
* @param {number[]} nums
* @return {boolean}
*/
var splitArraySameAverage = function(nums) {
}; | You are given an integer array nums.
You should move each element of nums into one of the two arrays A and B such that A and B are non-empty, and average(A) == average(B).
Return true if it is possible to achieve that and false otherwise.
Note that for an array arr, average(arr) is the sum of all the elements of arr over the length of arr.
Example 1:
Input: nums = [1,2,3,4,5,6,7,8]
Output: true
Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have an average of 4.5.
Example 2:
Input: nums = [3,1]
Output: false
Constraints:
1 <= nums.length <= 30
0 <= nums[i] <= 104
| Hard | [
"array",
"math",
"dynamic-programming",
"bit-manipulation",
"bitmask"
]
| [
"const splitArraySameAverage = function(A) {\n const totalSum = A.reduce((ac, el) => ac + el, 0)\n const len = A.length\n const mid = Math.floor(len / 2)\n A.sort((a, b) => b - a)\n for (let i = 1; i <= mid; i++) {\n if ((totalSum * i) % len === 0 && combinationSum(A, 0, i, (totalSum * i) / len)) return true\n }\n return false\n}\n\nfunction combinationSum(nums, idx, k, target) {\n if (target > k * nums[idx]) return false\n if (k === 0) return target === 0\n for (let i = idx; i < nums.length - k; i++) {\n if (nums[i] <= target && combinationSum(nums, i + 1, k - 1, target - nums[i])) return true\n }\n return false\n}"
]
|
|
806 | number-of-lines-to-write-string | []
| /**
* @param {number[]} widths
* @param {string} s
* @return {number[]}
*/
var numberOfLines = function(widths, s) {
}; | You are given a string s of lowercase English letters and an array widths denoting how many pixels wide each lowercase English letter is. Specifically, widths[0] is the width of 'a', widths[1] is the width of 'b', and so on.
You are trying to write s across several lines, where each line is no longer than 100 pixels. Starting at the beginning of s, write as many letters on the first line such that the total width does not exceed 100 pixels. Then, from where you stopped in s, continue writing as many letters as you can on the second line. Continue this process until you have written all of s.
Return an array result of length 2 where:
result[0] is the total number of lines.
result[1] is the width of the last line in pixels.
Example 1:
Input: widths = [10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], s = "abcdefghijklmnopqrstuvwxyz"
Output: [3,60]
Explanation: You can write s as follows:
abcdefghij // 100 pixels wide
klmnopqrst // 100 pixels wide
uvwxyz // 60 pixels wide
There are a total of 3 lines, and the last line is 60 pixels wide.
Example 2:
Input: widths = [4,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], s = "bbbcccdddaaa"
Output: [2,4]
Explanation: You can write s as follows:
bbbcccdddaa // 98 pixels wide
a // 4 pixels wide
There are a total of 2 lines, and the last line is 4 pixels wide.
Constraints:
widths.length == 26
2 <= widths[i] <= 10
1 <= s.length <= 1000
s contains only lowercase English letters.
| Easy | [
"array",
"string"
]
| null | []
|
807 | max-increase-to-keep-city-skyline | []
| /**
* @param {number[][]} grid
* @return {number}
*/
var maxIncreaseKeepingSkyline = function(grid) {
}; | There is a city composed of n x n blocks, where each block contains a single building shaped like a vertical square prism. You are given a 0-indexed n x n integer matrix grid where grid[r][c] represents the height of the building located in the block at row r and column c.
A city's skyline is the outer contour formed by all the building when viewing the side of the city from a distance. The skyline from each cardinal direction north, east, south, and west may be different.
We are allowed to increase the height of any number of buildings by any amount (the amount can be different per building). The height of a 0-height building can also be increased. However, increasing the height of a building should not affect the city's skyline from any cardinal direction.
Return the maximum total sum that the height of the buildings can be increased by without changing the city's skyline from any cardinal direction.
Example 1:
Input: grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]
Output: 35
Explanation: The building heights are shown in the center of the above image.
The skylines when viewed from each cardinal direction are drawn in red.
The grid after increasing the height of buildings without affecting skylines is:
gridNew = [ [8, 4, 8, 7],
[7, 4, 7, 7],
[9, 4, 8, 7],
[3, 3, 3, 3] ]
Example 2:
Input: grid = [[0,0,0],[0,0,0],[0,0,0]]
Output: 0
Explanation: Increasing the height of any building will result in the skyline changing.
Constraints:
n == grid.length
n == grid[r].length
2 <= n <= 50
0 <= grid[r][c] <= 100
| Medium | [
"array",
"greedy",
"matrix"
]
| null | []
|
808 | soup-servings | []
| /**
* @param {number} n
* @return {number}
*/
var soupServings = function(n) {
}; | There are two types of soup: type A and type B. Initially, we have n ml of each type of soup. There are four kinds of operations:
Serve 100 ml of soup A and 0 ml of soup B,
Serve 75 ml of soup A and 25 ml of soup B,
Serve 50 ml of soup A and 50 ml of soup B, and
Serve 25 ml of soup A and 75 ml of soup B.
When we serve some soup, we give it to someone, and we no longer have it. Each turn, we will choose from the four operations with an equal probability 0.25. If the remaining volume of soup is not enough to complete the operation, we will serve as much as possible. We stop once we no longer have some quantity of both types of soup.
Note that we do not have an operation where all 100 ml's of soup B are used first.
Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time. Answers within 10-5 of the actual answer will be accepted.
Example 1:
Input: n = 50
Output: 0.62500
Explanation: If we choose the first two operations, A will become empty first.
For the third operation, A and B will become empty at the same time.
For the fourth operation, B will become empty first.
So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.
Example 2:
Input: n = 100
Output: 0.71875
Constraints:
0 <= n <= 109
| Medium | [
"math",
"dynamic-programming",
"probability-and-statistics"
]
| null | []
|
809 | expressive-words | []
| /**
* @param {string} s
* @param {string[]} words
* @return {number}
*/
var expressiveWords = function(s, words) {
}; | Sometimes people repeat letters to represent extra feeling. For example:
"hello" -> "heeellooo"
"hi" -> "hiiii"
In these strings like "heeellooo", we have groups of adjacent letters that are all the same: "h", "eee", "ll", "ooo".
You are given a string s and an array of query strings words. A query word is stretchy if it can be made to be equal to s by any number of applications of the following extension operation: choose a group consisting of characters c, and add some number of characters c to the group so that the size of the group is three or more.
For example, starting with "hello", we could do an extension on the group "o" to get "hellooo", but we cannot get "helloo" since the group "oo" has a size less than three. Also, we could do another extension like "ll" -> "lllll" to get "helllllooo". If s = "helllllooo", then the query word "hello" would be stretchy because of these two extension operations: query = "hello" -> "hellooo" -> "helllllooo" = s.
Return the number of query strings that are stretchy.
Example 1:
Input: s = "heeellooo", words = ["hello", "hi", "helo"]
Output: 1
Explanation:
We can extend "e" and "o" in the word "hello" to get "heeellooo".
We can't extend "helo" to get "heeellooo" because the group "ll" is not size 3 or more.
Example 2:
Input: s = "zzzzzyyyyy", words = ["zzyy","zy","zyy"]
Output: 3
Constraints:
1 <= s.length, words.length <= 100
1 <= words[i].length <= 100
s and words[i] consist of lowercase letters.
| Medium | [
"array",
"two-pointers",
"string"
]
| null | []
|
810 | chalkboard-xor-game | []
| /**
* @param {number[]} nums
* @return {boolean}
*/
var xorGame = function(nums) {
}; | You are given an array of integers nums represents the numbers written on a chalkboard.
Alice and Bob take turns erasing exactly one number from the chalkboard, with Alice starting first. If erasing a number causes the bitwise XOR of all the elements of the chalkboard to become 0, then that player loses. The bitwise XOR of one element is that element itself, and the bitwise XOR of no elements is 0.
Also, if any player starts their turn with the bitwise XOR of all the elements of the chalkboard equal to 0, then that player wins.
Return true if and only if Alice wins the game, assuming both players play optimally.
Example 1:
Input: nums = [1,1,2]
Output: false
Explanation:
Alice has two choices: erase 1 or erase 2.
If she erases 1, the nums array becomes [1, 2]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 2 = 3. Now Bob can remove any element he wants, because Alice will be the one to erase the last element and she will lose.
If Alice erases 2 first, now nums become [1, 1]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 1 = 0. Alice will lose.
Example 2:
Input: nums = [0,1]
Output: true
Example 3:
Input: nums = [1,2,3]
Output: true
Constraints:
1 <= nums.length <= 1000
0 <= nums[i] < 216
| Hard | [
"array",
"math",
"bit-manipulation",
"brainteaser",
"game-theory"
]
| [
"const xorGame = function(nums) {\n const xor = nums.reduce((xor,ele) => xor^ele, 0)\n return xor === 0 || (nums.length & 1) === 0\n};"
]
|
|
811 | subdomain-visit-count | []
| /**
* @param {string[]} cpdomains
* @return {string[]}
*/
var subdomainVisits = function(cpdomains) {
}; | A website domain "discuss.leetcode.com" consists of various subdomains. At the top level, we have "com", at the next level, we have "leetcode.com" and at the lowest level, "discuss.leetcode.com". When we visit a domain like "discuss.leetcode.com", we will also visit the parent domains "leetcode.com" and "com" implicitly.
A count-paired domain is a domain that has one of the two formats "rep d1.d2.d3" or "rep d1.d2" where rep is the number of visits to the domain and d1.d2.d3 is the domain itself.
For example, "9001 discuss.leetcode.com" is a count-paired domain that indicates that discuss.leetcode.com was visited 9001 times.
Given an array of count-paired domains cpdomains, return an array of the count-paired domains of each subdomain in the input. You may return the answer in any order.
Example 1:
Input: cpdomains = ["9001 discuss.leetcode.com"]
Output: ["9001 leetcode.com","9001 discuss.leetcode.com","9001 com"]
Explanation: We only have one website domain: "discuss.leetcode.com".
As discussed above, the subdomain "leetcode.com" and "com" will also be visited. So they will all be visited 9001 times.
Example 2:
Input: cpdomains = ["900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org"]
Output: ["901 mail.com","50 yahoo.com","900 google.mail.com","5 wiki.org","5 org","1 intel.mail.com","951 com"]
Explanation: We will visit "google.mail.com" 900 times, "yahoo.com" 50 times, "intel.mail.com" once and "wiki.org" 5 times.
For the subdomains, we will visit "mail.com" 900 + 1 = 901 times, "com" 900 + 50 + 1 = 951 times, and "org" 5 times.
Constraints:
1 <= cpdomain.length <= 100
1 <= cpdomain[i].length <= 100
cpdomain[i] follows either the "repi d1i.d2i.d3i" format or the "repi d1i.d2i" format.
repi is an integer in the range [1, 104].
d1i, d2i, and d3i consist of lowercase English letters.
| Medium | [
"array",
"hash-table",
"string",
"counting"
]
| null | []
|
812 | largest-triangle-area | []
| /**
* @param {number[][]} points
* @return {number}
*/
var largestTriangleArea = function(points) {
}; | Given an array of points on the X-Y plane points where points[i] = [xi, yi], return the area of the largest triangle that can be formed by any three different points. Answers within 10-5 of the actual answer will be accepted.
Example 1:
Input: points = [[0,0],[0,1],[1,0],[0,2],[2,0]]
Output: 2.00000
Explanation: The five points are shown in the above figure. The red triangle is the largest.
Example 2:
Input: points = [[1,0],[0,0],[0,1]]
Output: 0.50000
Constraints:
3 <= points.length <= 50
-50 <= xi, yi <= 50
All the given points are unique.
| Easy | [
"array",
"math",
"geometry"
]
| [
"const largestTriangleArea = function(points) {\n const N = points.length\n let ans = 0\n for(let i = 0; i < N; i++) {\n for(let j = i + 1; j < N; j++) {\n for(let k = j + 1; k < N; k++) {\n ans = Math.max(ans, area(points[i], points[j], points[k]))\n }\n }\n }\n return ans\n};\n\nfunction area(P,Q,R) {\n return 0.5 * Math.abs(P[0]*Q[1] + Q[0]*R[1] + R[0]*P[1] -P[1]*Q[0] - Q[1]*R[0] - R[1]*P[0])\n}"
]
|
|
813 | largest-sum-of-averages | []
| /**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var largestSumOfAverages = function(nums, k) {
}; | You are given an integer array nums and an integer k. You can partition the array into at most k non-empty adjacent subarrays. The score of a partition is the sum of the averages of each subarray.
Note that the partition must use every integer in nums, and that the score is not necessarily an integer.
Return the maximum score you can achieve of all the possible partitions. Answers within 10-6 of the actual answer will be accepted.
Example 1:
Input: nums = [9,1,2,3,9], k = 3
Output: 20.00000
Explanation:
The best choice is to partition nums into [9], [1, 2, 3], [9]. The answer is 9 + (1 + 2 + 3) / 3 + 9 = 20.
We could have also partitioned nums into [9, 1], [2], [3, 9], for example.
That partition would lead to a score of 5 + 2 + 6 = 13, which is worse.
Example 2:
Input: nums = [1,2,3,4,5,6,7], k = 4
Output: 20.50000
Constraints:
1 <= nums.length <= 100
1 <= nums[i] <= 104
1 <= k <= nums.length
| Medium | [
"array",
"dynamic-programming",
"prefix-sum"
]
| [
"const largestSumOfAverages = function(A, K) {\n const len = A.length\n const P = [0]\n for(let i = 0; i < len; i++) {\n P[i+1] = (P[i] || 0) + A[i]\n }\n const dp = []\n for(let j = 0; j < len; j++) {\n dp[j] = (P[len] - P[j]) / (len - j)\n }\n for(let m = 0; m < K - 1; m++) {\n for(let n = 0; n < len; n++) {\n for(let k = n + 1; k < len; k++) {\n dp[n] = Math.max(dp[n], (P[k] - P[n]) / (k - n) + dp[k])\n }\n }\n }\n return dp[0]\n}"
]
|
|
814 | binary-tree-pruning | []
| /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
var pruneTree = function(root) {
}; | Given the root of a binary tree, return the same tree where every subtree (of the given tree) not containing a 1 has been removed.
A subtree of a node node is node plus every node that is a descendant of node.
Example 1:
Input: root = [1,null,0,0,1]
Output: [1,null,0,null,1]
Explanation:
Only the red nodes satisfy the property "every subtree not containing a 1".
The diagram on the right represents the answer.
Example 2:
Input: root = [1,0,1,0,0,0,1]
Output: [1,null,1,null,1]
Example 3:
Input: root = [1,1,0,1,1,0,1,0]
Output: [1,1,0,1,1,null,1]
Constraints:
The number of nodes in the tree is in the range [1, 200].
Node.val is either 0 or 1.
| Medium | [
"tree",
"depth-first-search",
"binary-tree"
]
| null | []
|
815 | bus-routes | []
| /**
* @param {number[][]} routes
* @param {number} source
* @param {number} target
* @return {number}
*/
var numBusesToDestination = function(routes, source, target) {
}; | You are given an array routes representing bus routes where routes[i] is a bus route that the ith bus repeats forever.
For example, if routes[0] = [1, 5, 7], this means that the 0th bus travels in the sequence 1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ... forever.
You will start at the bus stop source (You are not on any bus initially), and you want to go to the bus stop target. You can travel between bus stops by buses only.
Return the least number of buses you must take to travel from source to target. Return -1 if it is not possible.
Example 1:
Input: routes = [[1,2,7],[3,6,7]], source = 1, target = 6
Output: 2
Explanation: The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6.
Example 2:
Input: routes = [[7,12],[4,5,15],[6],[15,19],[9,12,13]], source = 15, target = 12
Output: -1
Constraints:
1 <= routes.length <= 500.
1 <= routes[i].length <= 105
All the values of routes[i] are unique.
sum(routes[i].length) <= 105
0 <= routes[i][j] < 106
0 <= source, target < 106
| Hard | [
"array",
"hash-table",
"breadth-first-search"
]
| [
"const numBusesToDestination = function (routes, S, T) {\n if (S === T) return 0\n const map = {}\n const visited = new Array(routes.length).fill(false),\n queue = [S]\n let rides = 0\n for (let i = 0; i < routes.length; i++) {\n for (const stop of routes[i]) {\n if (map[stop] === undefined) {\n map[stop] = []\n }\n map[stop].push(i)\n }\n }\n while (queue.length > 0) {\n let size = queue.length\n rides += 1\n while (size > 0) {\n const currStop = queue.shift()\n size -= 1\n for (const bus of map[currStop]) {\n if (visited[bus]) continue\n visited[bus] = true\n for (const stop of routes[bus]) {\n if (stop === T) return rides\n queue.push(stop)\n }\n }\n }\n }\n return -1\n}"
]
|
|
816 | ambiguous-coordinates | []
| /**
* @param {string} s
* @return {string[]}
*/
var ambiguousCoordinates = function(s) {
}; | We had some 2-dimensional coordinates, like "(1, 3)" or "(2, 0.5)". Then, we removed all commas, decimal points, and spaces and ended up with the string s.
For example, "(1, 3)" becomes s = "(13)" and "(2, 0.5)" becomes s = "(205)".
Return a list of strings representing all possibilities for what our original coordinates could have been.
Our original representation never had extraneous zeroes, so we never started with numbers like "00", "0.0", "0.00", "1.0", "001", "00.01", or any other number that can be represented with fewer digits. Also, a decimal point within a number never occurs without at least one digit occurring before it, so we never started with numbers like ".1".
The final answer list can be returned in any order. All coordinates in the final answer have exactly one space between them (occurring after the comma.)
Example 1:
Input: s = "(123)"
Output: ["(1, 2.3)","(1, 23)","(1.2, 3)","(12, 3)"]
Example 2:
Input: s = "(0123)"
Output: ["(0, 1.23)","(0, 12.3)","(0, 123)","(0.1, 2.3)","(0.1, 23)","(0.12, 3)"]
Explanation: 0.0, 00, 0001 or 00.01 are not allowed.
Example 3:
Input: s = "(00011)"
Output: ["(0, 0.011)","(0.001, 1)"]
Constraints:
4 <= s.length <= 12
s[0] == '(' and s[s.length - 1] == ')'.
The rest of s are digits.
| Medium | [
"string",
"backtracking"
]
| null | []
|
817 | linked-list-components | []
| /**
* 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[]} nums
* @return {number}
*/
var numComponents = function(head, nums) {
}; | You are given the head of a linked list containing unique integer values and an integer array nums that is a subset of the linked list values.
Return the number of connected components in nums where two values are connected if they appear consecutively in the linked list.
Example 1:
Input: head = [0,1,2,3], nums = [0,1,3]
Output: 2
Explanation: 0 and 1 are connected, so [0, 1] and [3] are the two connected components.
Example 2:
Input: head = [0,1,2,3,4], nums = [0,3,1,4]
Output: 2
Explanation: 0 and 1 are connected, 3 and 4 are connected, so [0, 1] and [3, 4] are the two connected components.
Constraints:
The number of nodes in the linked list is n.
1 <= n <= 104
0 <= Node.val < n
All the values Node.val are unique.
1 <= nums.length <= n
0 <= nums[i] < n
All the values of nums are unique.
| Medium | [
"array",
"hash-table",
"linked-list"
]
| null | []
|
818 | race-car | []
| /**
* @param {number} target
* @return {number}
*/
var racecar = function(target) {
}; | Your car starts at position 0 and speed +1 on an infinite number line. Your car can go into negative positions. Your car drives automatically according to a sequence of instructions 'A' (accelerate) and 'R' (reverse):
When you get an instruction 'A', your car does the following:
position += speed
speed *= 2
When you get an instruction 'R', your car does the following:
If your speed is positive then speed = -1
otherwise speed = 1
Your position stays the same.
For example, after commands "AAR", your car goes to positions 0 --> 1 --> 3 --> 3, and your speed goes to 1 --> 2 --> 4 --> -1.
Given a target position target, return the length of the shortest sequence of instructions to get there.
Example 1:
Input: target = 3
Output: 2
Explanation:
The shortest instruction sequence is "AA".
Your position goes from 0 --> 1 --> 3.
Example 2:
Input: target = 6
Output: 5
Explanation:
The shortest instruction sequence is "AAARA".
Your position goes from 0 --> 1 --> 3 --> 7 --> 7 --> 6.
Constraints:
1 <= target <= 104
| Hard | [
"dynamic-programming"
]
| [
"const racecar = function (target) {\n const dp = new Array(target + 1).fill(0)\n for (let i = 1; i <= target; i++) {\n dp[i] = Number.MAX_VALUE\n let m = 1,\n j = 1\n for (; j < i; j = (1 << ++m) - 1) {\n for (let q = 0, p = 0; p < j; p = (1 << ++q) - 1) {\n dp[i] = Math.min(dp[i], m + 1 + q + 1 + dp[i - (j - p)])\n }\n }\n dp[i] = Math.min(dp[i], m + (i == j ? 0 : 1 + dp[j - i]))\n }\n return dp[target]\n}"
]
|
|
819 | most-common-word | []
| /**
* @param {string} paragraph
* @param {string[]} banned
* @return {string}
*/
var mostCommonWord = function(paragraph, banned) {
}; | Given a string paragraph and a string array of the banned words banned, return the most frequent word that is not banned. It is guaranteed there is at least one word that is not banned, and that the answer is unique.
The words in paragraph are case-insensitive and the answer should be returned in lowercase.
Example 1:
Input: paragraph = "Bob hit a ball, the hit BALL flew far after it was hit.", banned = ["hit"]
Output: "ball"
Explanation:
"hit" occurs 3 times, but it is a banned word.
"ball" occurs twice (and no other word does), so it is the most frequent non-banned word in the paragraph.
Note that words in the paragraph are not case sensitive,
that punctuation is ignored (even if adjacent to words, such as "ball,"),
and that "hit" isn't the answer even though it occurs more because it is banned.
Example 2:
Input: paragraph = "a.", banned = []
Output: "a"
Constraints:
1 <= paragraph.length <= 1000
paragraph consists of English letters, space ' ', or one of the symbols: "!?',;.".
0 <= banned.length <= 100
1 <= banned[i].length <= 10
banned[i] consists of only lowercase English letters.
| Easy | [
"hash-table",
"string",
"counting"
]
| [
"const mostCommonWord = function(paragraph, banned) {\n const str = paragraph.toLowerCase()\n const arr = str.replace(/\\W+/g, ' ').trim().split(' ')\n const hash = {}\n for(let el of arr) {\n if(banned.indexOf(el) !== -1) {\n\n } else {\n if(hash.hasOwnProperty(el)) {\n hash[el] += 1\n } else {\n hash[el] = 1\n }\n }\n }\n const res = Object.entries(hash).sort((a, b) => b[1] - a[1])\n return res[0][0]\n};"
]
|
|
820 | short-encoding-of-words | []
| /**
* @param {string[]} words
* @return {number}
*/
var minimumLengthEncoding = function(words) {
}; | A valid encoding of an array of words is any reference string s and array of indices indices such that:
words.length == indices.length
The reference string s ends with the '#' character.
For each index indices[i], the substring of s starting from indices[i] and up to (but not including) the next '#' character is equal to words[i].
Given an array of words, return the length of the shortest reference string s possible of any valid encoding of words.
Example 1:
Input: words = ["time", "me", "bell"]
Output: 10
Explanation: A valid encoding would be s = "time#bell#" and indices = [0, 2, 5].
words[0] = "time", the substring of s starting from indices[0] = 0 to the next '#' is underlined in "time#bell#"
words[1] = "me", the substring of s starting from indices[1] = 2 to the next '#' is underlined in "time#bell#"
words[2] = "bell", the substring of s starting from indices[2] = 5 to the next '#' is underlined in "time#bell#"
Example 2:
Input: words = ["t"]
Output: 2
Explanation: A valid encoding would be s = "t#" and indices = [0].
Constraints:
1 <= words.length <= 2000
1 <= words[i].length <= 7
words[i] consists of only lowercase letters.
| Medium | [
"array",
"hash-table",
"string",
"trie"
]
| null | []
|
821 | shortest-distance-to-a-character | []
| /**
* @param {string} s
* @param {character} c
* @return {number[]}
*/
var shortestToChar = function(s, c) {
}; | Given a string s and a character c that occurs in s, return an array of integers answer where answer.length == s.length and answer[i] is the distance from index i to the closest occurrence of character c in s.
The distance between two indices i and j is abs(i - j), where abs is the absolute value function.
Example 1:
Input: s = "loveleetcode", c = "e"
Output: [3,2,1,0,1,0,0,1,2,2,1,0]
Explanation: The character 'e' appears at indices 3, 5, 6, and 11 (0-indexed).
The closest occurrence of 'e' for index 0 is at index 3, so the distance is abs(0 - 3) = 3.
The closest occurrence of 'e' for index 1 is at index 3, so the distance is abs(1 - 3) = 2.
For index 4, there is a tie between the 'e' at index 3 and the 'e' at index 5, but the distance is still the same: abs(4 - 3) == abs(4 - 5) = 1.
The closest occurrence of 'e' for index 8 is at index 6, so the distance is abs(8 - 6) = 2.
Example 2:
Input: s = "aaab", c = "b"
Output: [3,2,1,0]
Constraints:
1 <= s.length <= 104
s[i] and c are lowercase English letters.
It is guaranteed that c occurs at least once in s.
| Easy | [
"array",
"two-pointers",
"string"
]
| [
"const shortestToChar = function(S, C) {\n const res = [];\n const idxArr = [];\n for (let i = 0; i < S.length; i++) {\n S.charAt(i) === C ? idxArr.push(i) : null;\n }\n let coordIdx = 0;\n let nextCoordIdx = 1;\n let val;\n for (let idx = 0; idx < S.length; idx++) {\n if (S.charAt(idx) === C) {\n val = 0;\n nextCoordIdx = idxArr[coordIdx + 1] == null ? coordIdx : coordIdx + 1;\n if (\n Math.abs(idxArr[coordIdx] - idx) >= Math.abs(idxArr[nextCoordIdx] - idx)\n ) {\n coordIdx = idxArr[coordIdx + 1] == null ? coordIdx : coordIdx + 1;\n }\n } else {\n nextCoordIdx = idxArr[coordIdx + 1] == null ? coordIdx : coordIdx + 1;\n if (\n Math.abs(idxArr[coordIdx] - idx) < Math.abs(idxArr[nextCoordIdx] - idx)\n ) {\n val = Math.abs(idxArr[coordIdx] - idx);\n } else {\n val = Math.abs(idxArr[nextCoordIdx] - idx);\n coordIdx = idxArr[coordIdx + 1] == null ? coordIdx : coordIdx + 1;\n }\n }\n res[idx] = val;\n }\n return res;\n};\n\nconsole.log(shortestToChar(\"aaab\", \"b\"));\nconsole.log(shortestToChar(\"bbba\", \"b\"));"
]
|
|
822 | card-flipping-game | []
| /**
* @param {number[]} fronts
* @param {number[]} backs
* @return {number}
*/
var flipgame = function(fronts, backs) {
}; | You are given two 0-indexed integer arrays fronts and backs of length n, where the ith card has the positive integer fronts[i] printed on the front and backs[i] printed on the back. Initially, each card is placed on a table such that the front number is facing up and the other is facing down. You may flip over any number of cards (possibly zero).
After flipping the cards, an integer is considered good if it is facing down on some card and not facing up on any card.
Return the minimum possible good integer after flipping the cards. If there are no good integers, return 0.
Example 1:
Input: fronts = [1,2,4,4,7], backs = [1,3,4,1,3]
Output: 2
Explanation:
If we flip the second card, the face up numbers are [1,3,4,4,7] and the face down are [1,2,4,1,3].
2 is the minimum good integer as it appears facing down but not facing up.
It can be shown that 2 is the minimum possible good integer obtainable after flipping some cards.
Example 2:
Input: fronts = [1], backs = [1]
Output: 0
Explanation:
There are no good integers no matter how we flip the cards, so we return 0.
Constraints:
n == fronts.length == backs.length
1 <= n <= 1000
1 <= fronts[i], backs[i] <= 2000
| Medium | [
"array",
"hash-table"
]
| null | []
|
823 | binary-trees-with-factors | []
| /**
* @param {number[]} arr
* @return {number}
*/
var numFactoredBinaryTrees = function(arr) {
}; | Given an array of unique integers, arr, where each integer arr[i] is strictly greater than 1.
We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of its children.
Return the number of binary trees we can make. The answer may be too large so return the answer modulo 109 + 7.
Example 1:
Input: arr = [2,4]
Output: 3
Explanation: We can make these trees: [2], [4], [4, 2, 2]
Example 2:
Input: arr = [2,4,5,10]
Output: 7
Explanation: We can make these trees: [2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2].
Constraints:
1 <= arr.length <= 1000
2 <= arr[i] <= 109
All the values of arr are unique.
| Medium | [
"array",
"hash-table",
"dynamic-programming",
"sorting"
]
| [
"const numFactoredBinaryTrees = function(A) {\n const mod = 10 ** 9 + 7\n let res = 0\n A.sort((a, b) => a - b)\n const dp = {}\n for(let i = 0; i < A.length; i++) {\n dp[A[i]] = 1\n for(let j = 0; j < i; j++) {\n if(A[i] % A[j] === 0 && dp.hasOwnProperty(Math.floor( A[i] / A[j]))) {\n dp[A[i]] = (dp[A[i]] + dp[A[j]] * dp[Math.floor(A[i] / A[j])]) % mod\n }\n }\n }\n for(let el of Object.values(dp)) res = (res + el) % mod\n return res\n};"
]
|
|
824 | goat-latin | []
| /**
* @param {string} sentence
* @return {string}
*/
var toGoatLatin = function(sentence) {
}; | You are given a string sentence that consist of words separated by spaces. Each word consists of lowercase and uppercase letters only.
We would like to convert the sentence to "Goat Latin" (a made-up language similar to Pig Latin.) The rules of Goat Latin are as follows:
If a word begins with a vowel ('a', 'e', 'i', 'o', or 'u'), append "ma" to the end of the word.
For example, the word "apple" becomes "applema".
If a word begins with a consonant (i.e., not a vowel), remove the first letter and append it to the end, then add "ma".
For example, the word "goat" becomes "oatgma".
Add one letter 'a' to the end of each word per its word index in the sentence, starting with 1.
For example, the first word gets "a" added to the end, the second word gets "aa" added to the end, and so on.
Return the final sentence representing the conversion from sentence to Goat Latin.
Example 1:
Input: sentence = "I speak Goat Latin"
Output: "Imaa peaksmaaa oatGmaaaa atinLmaaaaa"
Example 2:
Input: sentence = "The quick brown fox jumped over the lazy dog"
Output: "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa"
Constraints:
1 <= sentence.length <= 150
sentence consists of English letters and spaces.
sentence has no leading or trailing spaces.
All the words in sentence are separated by a single space.
| Easy | [
"string"
]
| [
"const toGoatLatin = function(sentence) {\n const arr = sentence.split(' ')\n const vowel = new Set(['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'])\n for(let i = 0, n = arr.length; i < n; i++) {\n const first = arr[i][0]\n const ma = vowel.has(first) ? 'ma' : ''\n const tmp = !vowel.has(first) ? `${arr[i].slice(1)}${first}ma` : arr[i]\n const suffix = 'a'.repeat(i + 1)\n arr[i] = `${tmp}${ma}${suffix}`\n }\n return arr.join(' ')\n};"
]
|
|
825 | friends-of-appropriate-ages | []
| /**
* @param {number[]} ages
* @return {number}
*/
var numFriendRequests = function(ages) {
}; | There are n persons on a social media website. You are given an integer array ages where ages[i] is the age of the ith person.
A Person x will not send a friend request to a person y (x != y) if any of the following conditions is true:
age[y] <= 0.5 * age[x] + 7
age[y] > age[x]
age[y] > 100 && age[x] < 100
Otherwise, x will send a friend request to y.
Note that if x sends a request to y, y will not necessarily send a request to x. Also, a person will not send a friend request to themself.
Return the total number of friend requests made.
Example 1:
Input: ages = [16,16]
Output: 2
Explanation: 2 people friend request each other.
Example 2:
Input: ages = [16,17,18]
Output: 2
Explanation: Friend requests are made 17 -> 16, 18 -> 17.
Example 3:
Input: ages = [20,30,100,110,120]
Output: 3
Explanation: Friend requests are made 110 -> 100, 120 -> 110, 120 -> 100.
Constraints:
n == ages.length
1 <= n <= 2 * 104
1 <= ages[i] <= 120
| Medium | [
"array",
"two-pointers",
"binary-search",
"sorting"
]
| null | []
|
826 | most-profit-assigning-work | []
| /**
* @param {number[]} difficulty
* @param {number[]} profit
* @param {number[]} worker
* @return {number}
*/
var maxProfitAssignment = function(difficulty, profit, worker) {
}; | You have n jobs and m workers. You are given three arrays: difficulty, profit, and worker where:
difficulty[i] and profit[i] are the difficulty and the profit of the ith job, and
worker[j] is the ability of jth worker (i.e., the jth worker can only complete a job with difficulty at most worker[j]).
Every worker can be assigned at most one job, but one job can be completed multiple times.
For example, if three workers attempt the same job that pays $1, then the total profit will be $3. If a worker cannot complete any job, their profit is $0.
Return the maximum profit we can achieve after assigning the workers to the jobs.
Example 1:
Input: difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7]
Output: 100
Explanation: Workers are assigned jobs of difficulty [4,4,6,6] and they get a profit of [20,20,30,30] separately.
Example 2:
Input: difficulty = [85,47,57], profit = [24,66,99], worker = [40,25,25]
Output: 0
Constraints:
n == difficulty.length
n == profit.length
m == worker.length
1 <= n, m <= 104
1 <= difficulty[i], profit[i], worker[i] <= 105
| Medium | [
"array",
"two-pointers",
"binary-search",
"greedy",
"sorting"
]
| [
"const maxProfitAssignment = function(difficulty, profit, worker) {\n let res = 0\n const n = profit.length\n const jobs = []\n for(let i = 0; i < n; i++) {\n jobs.push([difficulty[i], profit[i]])\n }\n jobs.sort((a,b) => a[0] - b[0])\n worker.sort((a, b) => a - b)\n let i = 0, tmp = 0\n for(let w of worker) {\n while(i < n && w >= jobs[i][0]) {\n tmp = Math.max(tmp, jobs[i++][1])\n }\n res += tmp\n }\n \n return res\n};\n "
]
|
|
827 | making-a-large-island | []
| /**
* @param {number[][]} grid
* @return {number}
*/
var largestIsland = function(grid) {
}; | You are given an n x n binary matrix grid. You are allowed to change at most one 0 to be 1.
Return the size of the largest island in grid after applying this operation.
An island is a 4-directionally connected group of 1s.
Example 1:
Input: grid = [[1,0],[0,1]]
Output: 3
Explanation: Change one 0 to 1 and connect two 1s, then we get an island with area = 3.
Example 2:
Input: grid = [[1,1],[1,0]]
Output: 4
Explanation: Change the 0 to 1 and make the island bigger, only one island with area = 4.
Example 3:
Input: grid = [[1,1],[1,1]]
Output: 4
Explanation: Can't change any 0 to 1, only one island with area = 4.
Constraints:
n == grid.length
n == grid[i].length
1 <= n <= 500
grid[i][j] is either 0 or 1.
| Hard | [
"array",
"depth-first-search",
"breadth-first-search",
"union-find",
"matrix"
]
| [
"function largestIsland(grid) {\n const map = new Map() //Key: color, Val: size of island painted of that color\n map.set(0, 0) //We won't paint island 0, hence make its size 0, we will use this value later\n let n = grid.length\n let colorIndex = 2 //0 and 1 is already used in grid, hence we start colorIndex from 2\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < n; j++) {\n if (grid[i][j] == 1) {\n let size = paint(grid, i, j, colorIndex)\n map.set(colorIndex, size)\n colorIndex++\n }\n }\n }\n\n //If there is no island 0 from grid, res should be the size of islands of first color\n //If there is no island 1 from grid, res should be 0\n let res = map.get(2) || 0\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < n; j++) {\n if (grid[i][j] === 0) {\n //We use a set to avoid repeatly adding islands with the same color\n const set = new Set()\n //If current island is at the boundary, we add 0 to the set, whose value is 0 in the map\n set.add(i > 0 ? grid[i - 1][j] : 0)\n set.add(i < n - 1 ? grid[i + 1][j] : 0)\n set.add(j > 0 ? grid[i][j - 1] : 0)\n set.add(j < n - 1 ? grid[i][j + 1] : 0)\n\n let newSize = 1 //We need to count current island as well, hence we init newSize with 1\n for (let color of set) newSize += map.get(color)\n res = Math.max(res, newSize)\n }\n }\n }\n return res\n}\n\n//Helper method to paint current island and all its connected neighbors\n//Return the size of all painted islands at the end\nfunction paint(grid, i, j, color) {\n if (i < 0 || j < 0 || i >= grid.length || j >= grid[0].length || grid[i][j] != 1) return 0\n grid[i][j] = color\n return (\n 1 +\n paint(grid, i + 1, j, color) +\n paint(grid, i - 1, j, color) +\n paint(grid, i, j + 1, color) +\n paint(grid, i, j - 1, color)\n )\n}"
]
|
|
828 | count-unique-characters-of-all-substrings-of-a-given-string | []
| /**
* @param {string} s
* @return {number}
*/
var uniqueLetterString = function(s) {
}; | Let's define a function countUniqueChars(s) that returns the number of unique characters in s.
For example, calling countUniqueChars(s) if s = "LEETCODE" then "L", "T", "C", "O", "D" are the unique characters since they appear only once in s, therefore countUniqueChars(s) = 5.
Given a string s, return the sum of countUniqueChars(t) where t is a substring of s. The test cases are generated such that the answer fits in a 32-bit integer.
Notice that some substrings can be repeated so in this case you have to count the repeated ones too.
Example 1:
Input: s = "ABC"
Output: 10
Explanation: All possible substrings are: "A","B","C","AB","BC" and "ABC".
Every substring is composed with only unique letters.
Sum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10
Example 2:
Input: s = "ABA"
Output: 8
Explanation: The same as example 1, except countUniqueChars("ABA") = 1.
Example 3:
Input: s = "LEETCODE"
Output: 92
Constraints:
1 <= s.length <= 105
s consists of uppercase English letters only.
| Hard | [
"hash-table",
"string",
"dynamic-programming"
]
| [
"const uniqueLetterString = function(s) {\n const n = s.length\n const arr = Array.from({ length: 26 }, () => Array(2).fill(-1))\n const A = 'A'.charCodeAt(0)\n let res = 0\n for(let i = 0; i < n; i++) {\n const idx = s.charCodeAt(i) - A\n res += (i - arr[idx][1]) * (arr[idx][1] - arr[idx][0])\n arr[idx] = [arr[idx][1], i]\n }\n \n for(let i = 0; i < 26; i++) {\n res += (n - arr[i][1]) * (arr[i][1] - arr[i][0])\n }\n \n return res\n};",
"const uniqueLetterString = function(S) {\n const s = S.split('')\n let res = 0\n for (let n = S.length, i = 0, l = 0, r = 0; i < n; i++) {\n for (l = i - 1; l >= 0 && s[l] != s[i]; l--);\n for (r = i + 1; r < n && s[r] != s[i]; r++);\n res += (r - i) * (i - l)\n }\n return res % (10 ** 9 + 7)\n}",
"const uniqueLetterString = function(S) {\n const len = S.length\n if (len === 0) return 0\n if (len === 1) return 1\n let count = 0\n let lastP = new Array(26).fill(0)\n let lastLastP = new Array(26).fill(0)\n let pre = 0\n for (let i = 0; i < len; i++) {\n let idx = S.charCodeAt(i) - 'A'.charCodeAt(0)\n pre += i - lastP[idx] + 1\n pre -= lastP[idx] - lastLastP[idx]\n count += pre\n lastLastP[idx] = lastP[idx]\n lastP[idx] = i + 1\n }\n return count % 1000000007\n}"
]
|
|
829 | consecutive-numbers-sum | []
| /**
* @param {number} n
* @return {number}
*/
var consecutiveNumbersSum = function(n) {
}; | Given an integer n, return the number of ways you can write n as the sum of consecutive positive integers.
Example 1:
Input: n = 5
Output: 2
Explanation: 5 = 2 + 3
Example 2:
Input: n = 9
Output: 3
Explanation: 9 = 4 + 5 = 2 + 3 + 4
Example 3:
Input: n = 15
Output: 4
Explanation: 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5
Constraints:
1 <= n <= 109
| Hard | [
"math",
"enumeration"
]
| [
"const consecutiveNumbersSum = function (N) {\n let count = 1\n for (let k = 2; k < Math.sqrt(2 * N); k++) {\n if ((N - (k * (k - 1)) / 2) % k === 0) count++\n }\n return count\n}",
"const consecutiveNumbersSum = function(N) {\n let res = 0\n for(let i = 1; i <= N; i++) {\n const diff = i * (i - 1) / 2\n const nd = N - diff\n if(nd <= 0) break\n if(nd % i === 0) res++\n }\n \n return res\n};"
]
|
|
830 | positions-of-large-groups | []
| /**
* @param {string} s
* @return {number[][]}
*/
var largeGroupPositions = function(s) {
}; | In a string s of lowercase letters, these letters form consecutive groups of the same character.
For example, a string like s = "abbxxxxzyy" has the groups "a", "bb", "xxxx", "z", and "yy".
A group is identified by an interval [start, end], where start and end denote the start and end indices (inclusive) of the group. In the above example, "xxxx" has the interval [3,6].
A group is considered large if it has 3 or more characters.
Return the intervals of every large group sorted in increasing order by start index.
Example 1:
Input: s = "abbxxxxzzy"
Output: [[3,6]]
Explanation: "xxxx" is the only large group with start index 3 and end index 6.
Example 2:
Input: s = "abc"
Output: []
Explanation: We have groups "a", "b", and "c", none of which are large groups.
Example 3:
Input: s = "abcdddeeeeaabbbcd"
Output: [[3,5],[6,9],[12,14]]
Explanation: The large groups are "ddd", "eeee", and "bbb".
Constraints:
1 <= s.length <= 1000
s contains lowercase English letters only.
| Easy | [
"string"
]
| [
"const largeGroupPositions = function(S) {\n if (S.length === 0) return [];\n let prevChar = S[0];\n let curChar = S[0];\n let curStartIdx = 0;\n let curCount = 1;\n const res = [];\n let tmpChar;\n for (let i = 1; i < S.length; i++) {\n tmpChar = S[i];\n if (tmpChar === prevChar) {\n curCount += 1;\n } else {\n if (curCount >= 3) {\n res.push([curStartIdx, curStartIdx + curCount - 1]);\n }\n\n prevChar = S[i];\n curStartIdx = i;\n curCount = 1;\n }\n }\n\n if (curCount >= 3) {\n res.push([curStartIdx, curStartIdx + curCount - 1]);\n }\n\n return res;\n};\n\nconsole.log(largeGroupPositions(\"aaa\"));\nconsole.log(largeGroupPositions(\"abbxxxxzzy\"));\nconsole.log(largeGroupPositions(\"abcdddeeeeaabbbcd\"));"
]
|
|
831 | masking-personal-information | []
| /**
* @param {string} s
* @return {string}
*/
var maskPII = function(s) {
}; | You are given a personal information string s, representing either an email address or a phone number. Return the masked personal information using the below rules.
Email address:
An email address is:
A name consisting of uppercase and lowercase English letters, followed by
The '@' symbol, followed by
The domain consisting of uppercase and lowercase English letters with a dot '.' somewhere in the middle (not the first or last character).
To mask an email:
The uppercase letters in the name and domain must be converted to lowercase letters.
The middle letters of the name (i.e., all but the first and last letters) must be replaced by 5 asterisks "*****".
Phone number:
A phone number is formatted as follows:
The phone number contains 10-13 digits.
The last 10 digits make up the local number.
The remaining 0-3 digits, in the beginning, make up the country code.
Separation characters from the set {'+', '-', '(', ')', ' '} separate the above digits in some way.
To mask a phone number:
Remove all separation characters.
The masked phone number should have the form:
"***-***-XXXX" if the country code has 0 digits.
"+*-***-***-XXXX" if the country code has 1 digit.
"+**-***-***-XXXX" if the country code has 2 digits.
"+***-***-***-XXXX" if the country code has 3 digits.
"XXXX" is the last 4 digits of the local number.
Example 1:
Input: s = "LeetCode@LeetCode.com"
Output: "l*****e@leetcode.com"
Explanation: s is an email address.
The name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks.
Example 2:
Input: s = "AB@qq.com"
Output: "a*****b@qq.com"
Explanation: s is an email address.
The name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks.
Note that even though "ab" is 2 characters, it still must have 5 asterisks in the middle.
Example 3:
Input: s = "1(234)567-890"
Output: "***-***-7890"
Explanation: s is a phone number.
There are 10 digits, so the local number is 10 digits and the country code is 0 digits.
Thus, the resulting masked number is "***-***-7890".
Constraints:
s is either a valid email or a phone number.
If s is an email:
8 <= s.length <= 40
s consists of uppercase and lowercase English letters and exactly one '@' symbol and '.' symbol.
If s is a phone number:
10 <= s.length <= 20
s consists of digits, spaces, and the symbols '(', ')', '-', and '+'.
| Medium | [
"string"
]
| null | []
|
832 | flipping-an-image | []
| /**
* @param {number[][]} image
* @return {number[][]}
*/
var flipAndInvertImage = function(image) {
}; | Given an n x n binary matrix image, flip the image horizontally, then invert it, and return the resulting image.
To flip an image horizontally means that each row of the image is reversed.
For example, flipping [1,1,0] horizontally results in [0,1,1].
To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0.
For example, inverting [0,1,1] results in [1,0,0].
Example 1:
Input: image = [[1,1,0],[1,0,1],[0,0,0]]
Output: [[1,0,0],[0,1,0],[1,1,1]]
Explanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]].
Then, invert the image: [[1,0,0],[0,1,0],[1,1,1]]
Example 2:
Input: image = [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]
Output: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
Explanation: First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]].
Then invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
Constraints:
n == image.length
n == image[i].length
1 <= n <= 20
images[i][j] is either 0 or 1.
| Easy | [
"array",
"two-pointers",
"matrix",
"simulation"
]
| null | []
|
833 | find-and-replace-in-string | []
| /**
* @param {string} s
* @param {number[]} indices
* @param {string[]} sources
* @param {string[]} targets
* @return {string}
*/
var findReplaceString = function(s, indices, sources, targets) {
}; | You are given a 0-indexed string s that you must perform k replacement operations on. The replacement operations are given as three 0-indexed parallel arrays, indices, sources, and targets, all of length k.
To complete the ith replacement operation:
Check if the substring sources[i] occurs at index indices[i] in the original string s.
If it does not occur, do nothing.
Otherwise if it does occur, replace that substring with targets[i].
For example, if s = "abcd", indices[i] = 0, sources[i] = "ab", and targets[i] = "eee", then the result of this replacement will be "eeecd".
All replacement operations must occur simultaneously, meaning the replacement operations should not affect the indexing of each other. The testcases will be generated such that the replacements will not overlap.
For example, a testcase with s = "abc", indices = [0, 1], and sources = ["ab","bc"] will not be generated because the "ab" and "bc" replacements overlap.
Return the resulting string after performing all replacement operations on s.
A substring is a contiguous sequence of characters in a string.
Example 1:
Input: s = "abcd", indices = [0, 2], sources = ["a", "cd"], targets = ["eee", "ffff"]
Output: "eeebffff"
Explanation:
"a" occurs at index 0 in s, so we replace it with "eee".
"cd" occurs at index 2 in s, so we replace it with "ffff".
Example 2:
Input: s = "abcd", indices = [0, 2], sources = ["ab","ec"], targets = ["eee","ffff"]
Output: "eeecd"
Explanation:
"ab" occurs at index 0 in s, so we replace it with "eee".
"ec" does not occur at index 2 in s, so we do nothing.
Constraints:
1 <= s.length <= 1000
k == indices.length == sources.length == targets.length
1 <= k <= 100
0 <= indexes[i] < s.length
1 <= sources[i].length, targets[i].length <= 50
s consists of only lowercase English letters.
sources[i] and targets[i] consist of only lowercase English letters.
| Medium | [
"array",
"string",
"sorting"
]
| null | []
|
834 | sum-of-distances-in-tree | []
| /**
* @param {number} n
* @param {number[][]} edges
* @return {number[]}
*/
var sumOfDistancesInTree = function(n, edges) {
}; | There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges.
You are given the integer n and the array edges where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.
Return an array answer of length n where answer[i] is the sum of the distances between the ith node in the tree and all other nodes.
Example 1:
Input: n = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]]
Output: [8,12,6,10,10,10]
Explanation: The tree is shown above.
We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5)
equals 1 + 1 + 2 + 2 + 2 = 8.
Hence, answer[0] = 8, and so on.
Example 2:
Input: n = 1, edges = []
Output: [0]
Example 3:
Input: n = 2, edges = [[1,0]]
Output: [1,1]
Constraints:
1 <= n <= 3 * 104
edges.length == n - 1
edges[i].length == 2
0 <= ai, bi < n
ai != bi
The given input represents a valid tree.
| Hard | [
"dynamic-programming",
"tree",
"depth-first-search",
"graph"
]
| [
"const sumOfDistancesInTree = function (N, edges) {\n const graph = createGraph(N, edges)\n const counts = new Array(N).fill(0)\n const dists = new Array(N).fill(0)\n dists[0] = getCount(graph, 0, -1, counts).sum\n return transferDist(N, graph, 0, -1, counts, dists)\n}\n\nfunction transferDist(N, graph, u, pre, counts, dists) {\n if (pre >= 0) {\n const nRight = counts[u]\n const nLeft = N - nRight\n dists[u] = dists[pre] - nRight + nLeft\n }\n for (const v of graph[u]) {\n if (v !== pre) {\n transferDist(N, graph, v, u, counts, dists)\n }\n }\n return dists\n}\n\nfunction getCount(graph, u, pre, counts) {\n const output = { nNodes: 0, sum: 0 }\n for (const v of graph[u]) {\n if (v !== pre) {\n const result = getCount(graph, v, u, counts)\n output.nNodes += result.nNodes\n output.sum += result.nNodes + result.sum\n }\n }\n output.nNodes += 1\n counts[u] = output.nNodes\n return output\n}\n\nfunction createGraph(N, edges) {\n const graph = new Array(N).fill(null).map(() => [])\n for (const [u, v] of edges) {\n graph[u].push(v)\n graph[v].push(u)\n }\n return graph\n}"
]
|
|
835 | image-overlap | []
| /**
* @param {number[][]} img1
* @param {number[][]} img2
* @return {number}
*/
var largestOverlap = function(img1, img2) {
}; | You are given two images, img1 and img2, represented as binary, square matrices of size n x n. A binary matrix has only 0s and 1s as values.
We translate one image however we choose by sliding all the 1 bits left, right, up, and/or down any number of units. We then place it on top of the other image. We can then calculate the overlap by counting the number of positions that have a 1 in both images.
Note also that a translation does not include any kind of rotation. Any 1 bits that are translated outside of the matrix borders are erased.
Return the largest possible overlap.
Example 1:
Input: img1 = [[1,1,0],[0,1,0],[0,1,0]], img2 = [[0,0,0],[0,1,1],[0,0,1]]
Output: 3
Explanation: We translate img1 to right by 1 unit and down by 1 unit.
The number of positions that have a 1 in both images is 3 (shown in red).
Example 2:
Input: img1 = [[1]], img2 = [[1]]
Output: 1
Example 3:
Input: img1 = [[0]], img2 = [[0]]
Output: 0
Constraints:
n == img1.length == img1[i].length
n == img2.length == img2[i].length
1 <= n <= 30
img1[i][j] is either 0 or 1.
img2[i][j] is either 0 or 1.
| Medium | [
"array",
"matrix"
]
| [
"const largestOverlap = function(A, B) {\n const N = A.length\n const count = constructMatrix(2*N, 2*N, 0)\n for (let i = 0; i < N; i++) {\n for (let j = 0; j < N; j++) {\n if (A[i][j] === 1) {\n for(let ii = 0; ii < N; ii++) {\n for(let jj = 0; jj < N; jj++) {\n if(B[ii][jj] === 1) {\n count[i-ii+N][j-jj+N] += 1\n }\n }\n }\n }\n }\n }\n let ans = 0\n\n for(let row of count) {\n for(let v of row) {\n ans = Math.max(ans, v)\n }\n }\n return ans\n};\n\nfunction constructMatrix(row, col, init = 0) {\n const matrix = []\n for(let i = 0; i < row; i++) {\n matrix[i] = []\n for(let j = 0; j < col; j++) {\n matrix[i][j] = init\n }\n }\n return matrix\n}\n\nconsole.log(largestOverlap([[1,1,0],\n [0,1,0],\n [0,1,0]],[[0,0,0],\n [0,1,1],\n [0,0,1]]))"
]
|
|
836 | rectangle-overlap | []
| /**
* @param {number[]} rec1
* @param {number[]} rec2
* @return {boolean}
*/
var isRectangleOverlap = function(rec1, rec2) {
}; | An axis-aligned rectangle is represented as a list [x1, y1, x2, y2], where (x1, y1) is the coordinate of its bottom-left corner, and (x2, y2) is the coordinate of its top-right corner. Its top and bottom edges are parallel to the X-axis, and its left and right edges are parallel to the Y-axis.
Two rectangles overlap if the area of their intersection is positive. To be clear, two rectangles that only touch at the corner or edges do not overlap.
Given two axis-aligned rectangles rec1 and rec2, return true if they overlap, otherwise return false.
Example 1:
Input: rec1 = [0,0,2,2], rec2 = [1,1,3,3]
Output: true
Example 2:
Input: rec1 = [0,0,1,1], rec2 = [1,0,2,1]
Output: false
Example 3:
Input: rec1 = [0,0,1,1], rec2 = [2,2,3,3]
Output: false
Constraints:
rec1.length == 4
rec2.length == 4
-109 <= rec1[i], rec2[i] <= 109
rec1 and rec2 represent a valid rectangle with a non-zero area.
| Easy | [
"math",
"geometry"
]
| [
"const isRectangleOverlap = function(rec1, rec2) {\n return !(\n chkOverlap(rec1, rec2) === false || chkOverlap(rec2, rec1) === false\n );\n};\nfunction chkOverlap(r1, r2) {\n if (r1[2] <= r2[0] || r1[3] <= r2[1]) {\n return false;\n } else {\n return true;\n }\n}\n\nconsole.log(isRectangleOverlap([0, 0, 2, 2], [1, 1, 3, 3]));\nconsole.log(isRectangleOverlap([0, 0, 1, 1], [1, 0, 2, 1]));"
]
|
|
837 | new-21-game | []
| /**
* @param {number} n
* @param {number} k
* @param {number} maxPts
* @return {number}
*/
var new21Game = function(n, k, maxPts) {
}; | Alice plays the following game, loosely based on the card game "21".
Alice starts with 0 points and draws numbers while she has less than k points. During each draw, she gains an integer number of points randomly from the range [1, maxPts], where maxPts is an integer. Each draw is independent and the outcomes have equal probabilities.
Alice stops drawing numbers when she gets k or more points.
Return the probability that Alice has n or fewer points.
Answers within 10-5 of the actual answer are considered accepted.
Example 1:
Input: n = 10, k = 1, maxPts = 10
Output: 1.00000
Explanation: Alice gets a single card, then stops.
Example 2:
Input: n = 6, k = 1, maxPts = 10
Output: 0.60000
Explanation: Alice gets a single card, then stops.
In 6 out of 10 possibilities, she is at or below 6 points.
Example 3:
Input: n = 21, k = 17, maxPts = 10
Output: 0.73278
Constraints:
0 <= k <= n <= 104
1 <= maxPts <= 104
| Medium | [
"math",
"dynamic-programming",
"sliding-window",
"probability-and-statistics"
]
| [
"const new21Game = function(N, K, W) {\n if (K === 0 || N >= K + W) {\n return 1;\n }\n const dp = [];\n let Wsum = 1;\n let res = 0;\n dp[0] = 1;\n for (let i = 1; i <= N; i++) {\n dp[i] = Wsum / W;\n if (i < K) {\n Wsum += dp[i];\n } else {\n res += dp[i];\n }\n if (i - W >= 0) {\n Wsum -= dp[i - W];\n }\n }\n return res;\n};\n\nconsole.log(new21Game(6, 1, 10));\nconsole.log(new21Game(10, 1, 10));\nconsole.log(new21Game(21, 17, 10));"
]
|
|
838 | push-dominoes | []
| /**
* @param {string} dominoes
* @return {string}
*/
var pushDominoes = function(dominoes) {
}; | There are n dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right.
After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right.
When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces.
For the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino.
You are given a string dominoes representing the initial state where:
dominoes[i] = 'L', if the ith domino has been pushed to the left,
dominoes[i] = 'R', if the ith domino has been pushed to the right, and
dominoes[i] = '.', if the ith domino has not been pushed.
Return a string representing the final state.
Example 1:
Input: dominoes = "RR.L"
Output: "RR.L"
Explanation: The first domino expends no additional force on the second domino.
Example 2:
Input: dominoes = ".L.R...LR..L.."
Output: "LL.RR.LLRRLL.."
Constraints:
n == dominoes.length
1 <= n <= 105
dominoes[i] is either 'L', 'R', or '.'.
| Medium | [
"two-pointers",
"string",
"dynamic-programming"
]
| null | []
|
839 | similar-string-groups | []
| /**
* @param {string[]} strs
* @return {number}
*/
var numSimilarGroups = function(strs) {
}; | Two strings, X and Y, are considered similar if either they are identical or we can make them equivalent by swapping at most two letters (in distinct positions) within the string X.
For example, "tars" and "rats" are similar (swapping at positions 0 and 2), and "rats" and "arts" are similar, but "star" is not similar to "tars", "rats", or "arts".
Together, these form two connected groups by similarity: {"tars", "rats", "arts"} and {"star"}. Notice that "tars" and "arts" are in the same group even though they are not similar. Formally, each group is such that a word is in the group if and only if it is similar to at least one other word in the group.
We are given a list strs of strings where every string in strs is an anagram of every other string in strs. How many groups are there?
Example 1:
Input: strs = ["tars","rats","arts","star"]
Output: 2
Example 2:
Input: strs = ["omv","ovm"]
Output: 1
Constraints:
1 <= strs.length <= 300
1 <= strs[i].length <= 300
strs[i] consists of lowercase letters only.
All words in strs have the same length and are anagrams of each other.
| Hard | [
"array",
"hash-table",
"string",
"depth-first-search",
"breadth-first-search",
"union-find"
]
| [
"const numSimilarGroups = function (A) {\n const all = new Set(A)\n const isSimilar = function (w1, w2) {\n if (w1 === w2) return true\n let misMatch = 0\n for (let i = 0; i < w1.length; i++) {\n if (w1[i] !== w2[i]) misMatch++\n if (misMatch > 2) return false\n }\n return true\n }\n const recur = function (s) {\n all.delete(s)\n for (let n of all) {\n if (isSimilar(s, n)) {\n recur(n)\n }\n }\n }\n let ans = 0\n while (all.size) {\n const current = all.values().next().value\n recur(current)\n ans++\n }\n return ans\n}"
]
|
|
840 | magic-squares-in-grid | []
| /**
* @param {number[][]} grid
* @return {number}
*/
var numMagicSquaresInside = function(grid) {
}; | A 3 x 3 magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row, column, and both diagonals all have the same sum.
Given a row x col grid of integers, how many 3 x 3 "magic square" subgrids are there? (Each subgrid is contiguous).
Example 1:
Input: grid = [[4,3,8,4],[9,5,1,9],[2,7,6,2]]
Output: 1
Explanation:
The following subgrid is a 3 x 3 magic square:
while this one is not:
In total, there is only one magic square inside the given grid.
Example 2:
Input: grid = [[8]]
Output: 0
Constraints:
row == grid.length
col == grid[i].length
1 <= row, col <= 10
0 <= grid[i][j] <= 15
| Medium | [
"array",
"math",
"matrix"
]
| null | []
|
841 | keys-and-rooms | []
| /**
* @param {number[][]} rooms
* @return {boolean}
*/
var canVisitAllRooms = function(rooms) {
}; | There are n rooms labeled from 0 to n - 1 and all the rooms are locked except for room 0. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key.
When you visit a room, you may find a set of distinct keys in it. Each key has a number on it, denoting which room it unlocks, and you can take all of them with you to unlock the other rooms.
Given an array rooms where rooms[i] is the set of keys that you can obtain if you visited room i, return true if you can visit all the rooms, or false otherwise.
Example 1:
Input: rooms = [[1],[2],[3],[]]
Output: true
Explanation:
We visit room 0 and pick up key 1.
We then visit room 1 and pick up key 2.
We then visit room 2 and pick up key 3.
We then visit room 3.
Since we were able to visit every room, we return true.
Example 2:
Input: rooms = [[1,3],[3,0,1],[2],[0]]
Output: false
Explanation: We can not enter room number 2 since the only key that unlocks it is in that room.
Constraints:
n == rooms.length
2 <= n <= 1000
0 <= rooms[i].length <= 1000
1 <= sum(rooms[i].length) <= 3000
0 <= rooms[i][j] < n
All the values of rooms[i] are unique.
| Medium | [
"depth-first-search",
"breadth-first-search",
"graph"
]
| [
"const canVisitAllRooms = function(rooms) {\n const stack = [];\n const seen = [];\n for (let i = 0; i < rooms.length; i++) {\n seen[i] = false;\n }\n seen[0] = true;\n stack.push(0);\n while (stack.length) {\n let node = stack.pop();\n for (let el of rooms[node]) {\n if (!seen[el]) {\n seen[el] = true;\n stack.push(el);\n }\n }\n }\n for (let el of seen) {\n if (!el) return false;\n }\n return true;\n};"
]
|
|
842 | split-array-into-fibonacci-sequence | []
| /**
* @param {string} num
* @return {number[]}
*/
var splitIntoFibonacci = function(num) {
}; | You are given a string of digits num, such as "123456579". We can split it into a Fibonacci-like sequence [123, 456, 579].
Formally, a Fibonacci-like sequence is a list f of non-negative integers such that:
0 <= f[i] < 231, (that is, each integer fits in a 32-bit signed integer type),
f.length >= 3, and
f[i] + f[i + 1] == f[i + 2] for all 0 <= i < f.length - 2.
Note that when splitting the string into pieces, each piece must not have extra leading zeroes, except if the piece is the number 0 itself.
Return any Fibonacci-like sequence split from num, or return [] if it cannot be done.
Example 1:
Input: num = "1101111"
Output: [11,0,11,11]
Explanation: The output [110, 1, 111] would also be accepted.
Example 2:
Input: num = "112358130"
Output: []
Explanation: The task is impossible.
Example 3:
Input: num = "0123"
Output: []
Explanation: Leading zeroes are not allowed, so "01", "2", "3" is not valid.
Constraints:
1 <= num.length <= 200
num contains only digits.
| Medium | [
"string",
"backtracking"
]
| null | []
|
843 | guess-the-word | []
| /**
* // This is the master's API interface.
* // You should not implement it, or speculate about its implementation
* function Master() {
*
* @param {string} word
* @return {integer}
* this.guess = function(word) {
* ...
* };
* };
*/
/**
* @param {string[]} words
* @param {Master} master
* @return {void}
*/
var findSecretWord = function(words, master) {
}; | You are given an array of unique strings words where words[i] is six letters long. One word of words was chosen as a secret word.
You are also given the helper object Master. You may call Master.guess(word) where word is a six-letter-long string, and it must be from words. Master.guess(word) returns:
-1 if word is not from words, or
an integer representing the number of exact matches (value and position) of your guess to the secret word.
There is a parameter allowedGuesses for each test case where allowedGuesses is the maximum number of times you can call Master.guess(word).
For each test case, you should call Master.guess with the secret word without exceeding the maximum number of allowed guesses. You will get:
"Either you took too many guesses, or you did not find the secret word." if you called Master.guess more than allowedGuesses times or if you did not call Master.guess with the secret word, or
"You guessed the secret word correctly." if you called Master.guess with the secret word with the number of calls to Master.guess less than or equal to allowedGuesses.
The test cases are generated such that you can guess the secret word with a reasonable strategy (other than using the bruteforce method).
Example 1:
Input: secret = "acckzz", words = ["acckzz","ccbazz","eiowzz","abcczz"], allowedGuesses = 10
Output: You guessed the secret word correctly.
Explanation:
master.guess("aaaaaa") returns -1, because "aaaaaa" is not in wordlist.
master.guess("acckzz") returns 6, because "acckzz" is secret and has all 6 matches.
master.guess("ccbazz") returns 3, because "ccbazz" has 3 matches.
master.guess("eiowzz") returns 2, because "eiowzz" has 2 matches.
master.guess("abcczz") returns 4, because "abcczz" has 4 matches.
We made 5 calls to master.guess, and one of them was the secret, so we pass the test case.
Example 2:
Input: secret = "hamada", words = ["hamada","khaled"], allowedGuesses = 10
Output: You guessed the secret word correctly.
Explanation: Since there are two words, you can guess both.
Constraints:
1 <= words.length <= 100
words[i].length == 6
words[i] consist of lowercase English letters.
All the strings of wordlist are unique.
secret exists in words.
10 <= allowedGuesses <= 30
| Hard | [
"array",
"math",
"string",
"interactive",
"game-theory"
]
| [
"const findSecretWord = function (wordlist, master) {\n let group = wordlist\n for (let i = 0; i < 10; i++) {\n let currentGuess = findTheTypical(group)\n let res = master.guess(currentGuess)\n if (res === 6) return\n let tmp = []\n for (let j = 0; j < group.length; j++) {\n if (diff(group[j], currentGuess) === 6 - res) tmp.push(group[j])\n }\n group = tmp\n }\n}\nfunction findTheTypical(wordlist) {\n const count = Array.from({ length: 6 }, (x) => new Object())\n for (let i = 0; i < wordlist.length; i++) {\n for (let j = 0; j < 6; j++) {\n const cur = wordlist[i][j]\n if (count[j][cur] === undefined) count[j][cur] = 1\n else count[j][cur]++\n }\n }\n let maxPos = 0,\n maxCount = 0,\n maxAlp = ''\n for (let i = 0; i < 6; i++) {\n for (let k of Object.keys(count[i])) {\n if (count[i][k] > maxCount) {\n maxCount = count[i][k]\n maxPos = i\n maxAlp = k\n }\n }\n }\n for (let i = 0; i < wordlist.length; i++) {\n if (wordlist[i][maxPos] === maxAlp) return wordlist[i]\n }\n}\nfunction diff(a, b) {\n let count = 0\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) count++\n }\n return count\n}"
]
|
|
844 | backspace-string-compare | []
| /**
* @param {string} s
* @param {string} t
* @return {boolean}
*/
var backspaceCompare = function(s, t) {
}; | Given two strings s and t, return true if they are equal when both are typed into empty text editors. '#' means a backspace character.
Note that after backspacing an empty text, the text will continue empty.
Example 1:
Input: s = "ab#c", t = "ad#c"
Output: true
Explanation: Both s and t become "ac".
Example 2:
Input: s = "ab##", t = "c#d#"
Output: true
Explanation: Both s and t become "".
Example 3:
Input: s = "a#c", t = "b"
Output: false
Explanation: s becomes "c" while t becomes "b".
Constraints:
1 <= s.length, t.length <= 200
s and t only contain lowercase letters and '#' characters.
Follow up: Can you solve it in O(n) time and O(1) space?
| Easy | [
"two-pointers",
"string",
"stack",
"simulation"
]
| [
"const backspaceCompare = function(S, T) {\n return chk(S) === chk(T)\n};\n\nfunction chk(str) {\n const s = []\n for(let i = 0, len = str.length; i < len; i++) {\n if(str[i] === '#') s.pop()\n else s.push(str[i])\n }\n return s.join('')\n}"
]
|
|
845 | longest-mountain-in-array | []
| /**
* @param {number[]} arr
* @return {number}
*/
var longestMountain = function(arr) {
}; | You may recall that an array arr is a mountain array if and only if:
arr.length >= 3
There exists some index i (0-indexed) with 0 < i < arr.length - 1 such that:
arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
Given an integer array arr, return the length of the longest subarray, which is a mountain. Return 0 if there is no mountain subarray.
Example 1:
Input: arr = [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: arr = [2,2,2]
Output: 0
Explanation: There is no mountain.
Constraints:
1 <= arr.length <= 104
0 <= arr[i] <= 104
Follow up:
Can you solve it using only one pass?
Can you solve it in O(1) space?
| Medium | [
"array",
"two-pointers",
"dynamic-programming",
"enumeration"
]
| [
"const longestMountain = function(A) {\n const N = A.length;\n let ans = 0, base = 0;\n while (base < N) {\n let end = base;\n // if base is a left-boundary\n if (end + 1 < N && A[end] < A[end + 1]) {\n // set end to the peak of this potential mountain\n while (end + 1 < N && A[end] < A[end + 1]) end++;\n\n // if end is really a peak..\n if (end + 1 < N && A[end] > A[end + 1]) {\n // set end to the right-boundary of mountain\n while (end + 1 < N && A[end] > A[end + 1]) end++;\n // record candidate answer\n ans = Math.max(ans, end - base + 1);\n }\n }\n\n base = Math.max(end, base + 1);\n }\n\n return ans;\n};"
]
|
|
846 | hand-of-straights | []
| /**
* @param {number[]} hand
* @param {number} groupSize
* @return {boolean}
*/
var isNStraightHand = function(hand, groupSize) {
}; | Alice has some number of cards and she wants to rearrange the cards into groups so that each group is of size groupSize, and consists of groupSize consecutive cards.
Given an integer array hand where hand[i] is the value written on the ith card and an integer groupSize, return true if she can rearrange the cards, or false otherwise.
Example 1:
Input: hand = [1,2,3,6,2,3,4,7,8], groupSize = 3
Output: true
Explanation: Alice's hand can be rearranged as [1,2,3],[2,3,4],[6,7,8]
Example 2:
Input: hand = [1,2,3,4,5], groupSize = 4
Output: false
Explanation: Alice's hand can not be rearranged into groups of 4.
Constraints:
1 <= hand.length <= 104
0 <= hand[i] <= 109
1 <= groupSize <= hand.length
Note: This question is the same as 1296: https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/
| Medium | [
"array",
"hash-table",
"greedy",
"sorting"
]
| null | []
|
847 | shortest-path-visiting-all-nodes | []
| /**
* @param {number[][]} graph
* @return {number}
*/
var shortestPathLength = function(graph) {
}; | You have an undirected, connected graph of n nodes labeled from 0 to n - 1. You are given an array graph where graph[i] is a list of all the nodes connected with node i by an edge.
Return the length of the shortest path that visits every node. You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges.
Example 1:
Input: graph = [[1,2,3],[0],[0],[0]]
Output: 4
Explanation: One possible path is [1,0,2,0,3]
Example 2:
Input: graph = [[1],[0,2,4],[1,3,4],[2],[1,2]]
Output: 4
Explanation: One possible path is [0,1,4,2,3]
Constraints:
n == graph.length
1 <= n <= 12
0 <= graph[i].length < n
graph[i] does not contain i.
If graph[a] contains b, then graph[b] contains a.
The input graph is always connected.
| Hard | [
"dynamic-programming",
"bit-manipulation",
"breadth-first-search",
"graph",
"bitmask"
]
| [
"const shortestPathLength = function(graph) {\n const N = graph.length\n const dist = Array.from({ length: 1 << N }, () => new Array(N).fill(N * N))\n for (let x = 0; x < N; x++) dist[1 << x][x] = 0\n for (let cover = 0; cover < 1 << N; cover++) {\n let repeat = true\n while (repeat) {\n repeat = false\n for (let head = 0; head < N; head++) {\n let d = dist[cover][head]\n for (let next of graph[head]) {\n let cover2 = cover | (1 << next)\n if (d + 1 < dist[cover2][next]) {\n dist[cover2][next] = d + 1\n if (cover == cover2) repeat = true\n }\n }\n }\n }\n }\n let ans = N * N\n for (let cand of dist[(1 << N) - 1]) ans = Math.min(cand, ans)\n return ans\n}"
]
|
|
848 | shifting-letters | []
| /**
* @param {string} s
* @param {number[]} shifts
* @return {string}
*/
var shiftingLetters = function(s, shifts) {
}; | You are given a string s of lowercase English letters and an integer array shifts of the same length.
Call the shift() of a letter, the next letter in the alphabet, (wrapping around so that 'z' becomes 'a').
For example, shift('a') = 'b', shift('t') = 'u', and shift('z') = 'a'.
Now for each shifts[i] = x, we want to shift the first i + 1 letters of s, x times.
Return the final string after all such shifts to s are applied.
Example 1:
Input: s = "abc", shifts = [3,5,9]
Output: "rpl"
Explanation: We start with "abc".
After shifting the first 1 letters of s by 3, we have "dbc".
After shifting the first 2 letters of s by 5, we have "igc".
After shifting the first 3 letters of s by 9, we have "rpl", the answer.
Example 2:
Input: s = "aaa", shifts = [1,2,3]
Output: "gfd"
Constraints:
1 <= s.length <= 105
s consists of lowercase English letters.
shifts.length == s.length
0 <= shifts[i] <= 109
| Medium | [
"array",
"string"
]
| [
"const shiftingLetters = function(S, shifts) {\n let suffixSum = 0,\n result = \"\";\n for (let i = S.length - 1; i >= 0; i--) {\n suffixSum += shifts[i];\n let ascii = S[i].charCodeAt() - 97;\n result = String.fromCharCode(97 + ((ascii + suffixSum) % 26)) + result;\n }\n return result;\n};"
]
|
|
849 | maximize-distance-to-closest-person | []
| /**
* @param {number[]} seats
* @return {number}
*/
var maxDistToClosest = function(seats) {
}; | You are given an array representing a row of seats where seats[i] = 1 represents a person sitting in the ith seat, and seats[i] = 0 represents that the ith seat is empty (0-indexed).
There is at least one empty seat, and at least one person sitting.
Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized.
Return that maximum distance to the closest person.
Example 1:
Input: seats = [1,0,0,0,1,0,1]
Output: 2
Explanation:
If Alex sits in the second open seat (i.e. seats[2]), then the closest person has distance 2.
If Alex sits in any other open seat, the closest person has distance 1.
Thus, the maximum distance to the closest person is 2.
Example 2:
Input: seats = [1,0,0,0]
Output: 3
Explanation:
If Alex sits in the last seat (i.e. seats[3]), the closest person is 3 seats away.
This is the maximum distance possible, so the answer is 3.
Example 3:
Input: seats = [0,1]
Output: 1
Constraints:
2 <= seats.length <= 2 * 104
seats[i] is 0 or 1.
At least one seat is empty.
At least one seat is occupied.
| Medium | [
"array"
]
| [
"const maxDistToClosest = function(seats) {\n let left, right, res = 0, n = seats.length;\n for (left = right = 0; right < n; ++right)\n if (seats[right] === 1) {\n if (left === 0) res = Math.max(res, right - left);\n else res = Math.max(res, Math.floor((right - left + 1) / 2));\n left = right + 1;\n }\n res = Math.max(res, n - left);\n return res;\n};"
]
|
|
850 | rectangle-area-ii | []
| /**
* @param {number[][]} rectangles
* @return {number}
*/
var rectangleArea = function(rectangles) {
}; | You are given a 2D array of axis-aligned rectangles. Each rectangle[i] = [xi1, yi1, xi2, yi2] denotes the ith rectangle where (xi1, yi1) are the coordinates of the bottom-left corner, and (xi2, yi2) are the coordinates of the top-right corner.
Calculate the total area covered by all rectangles in the plane. Any area covered by two or more rectangles should only be counted once.
Return the total area. Since the answer may be too large, return it modulo 109 + 7.
Example 1:
Input: rectangles = [[0,0,2,2],[1,0,2,3],[1,0,3,1]]
Output: 6
Explanation: A total area of 6 is covered by all three rectangles, as illustrated in the picture.
From (1,1) to (2,2), the green and red rectangles overlap.
From (1,0) to (2,3), all three rectangles overlap.
Example 2:
Input: rectangles = [[0,0,1000000000,1000000000]]
Output: 49
Explanation: The answer is 1018 modulo (109 + 7), which is 49.
Constraints:
1 <= rectangles.length <= 200
rectanges[i].length == 4
0 <= xi1, yi1, xi2, yi2 <= 109
xi1 <= xi2
yi1 <= yi2
| Hard | [
"array",
"segment-tree",
"line-sweep",
"ordered-set"
]
| [
"const rectangleArea = function(rectangles) {\n let xnodes = rectangles.reduce((arr, rect) => {\n arr.push(rect[0], rect[2])\n return arr\n }, [])\n xnodes = [...new Set(xnodes)].sort((a, b) => a - b)\n let res = 0n\n let overlay\n let ynodes\n let ysum\n for (let i = 1; i < xnodes.length; i++) {\n overlay = []\n rectangles.forEach(rect => {\n if (rect[0] <= xnodes[i - 1] && rect[2] >= xnodes[i]) overlay.push(rect)\n })\n ynodes = overlay.reduce((set, rect) => {\n set.add(rect[1])\n set.add(rect[3])\n return set\n }, new Set())\n ynodes = [...ynodes].sort((a, b) => a - b)\n ysum = 0n\n for (let i = 1; i < ynodes.length; i++) {\n for (let j = 0; j < overlay.length; j++) {\n if (overlay[j][1] <= ynodes[i - 1] && overlay[j][3] >= ynodes[i]) {\n ysum += BigInt(ynodes[i] - ynodes[i - 1])\n break\n }\n }\n }\n res += ysum * BigInt(xnodes[i] - xnodes[i - 1])\n }\n return Number(res % BigInt(Math.pow(10, 9) + 7))\n}"
]
|
|
851 | loud-and-rich | []
| /**
* @param {number[][]} richer
* @param {number[]} quiet
* @return {number[]}
*/
var loudAndRich = function(richer, quiet) {
}; | There is a group of n people labeled from 0 to n - 1 where each person has a different amount of money and a different level of quietness.
You are given an array richer where richer[i] = [ai, bi] indicates that ai has more money than bi and an integer array quiet where quiet[i] is the quietness of the ith person. All the given data in richer are logically correct (i.e., the data will not lead you to a situation where x is richer than y and y is richer than x at the same time).
Return an integer array answer where answer[x] = y if y is the least quiet person (that is, the person y with the smallest value of quiet[y]) among all people who definitely have equal to or more money than the person x.
Example 1:
Input: richer = [[1,0],[2,1],[3,1],[3,7],[4,3],[5,3],[6,3]], quiet = [3,2,5,4,6,1,7,0]
Output: [5,5,2,5,4,5,6,7]
Explanation:
answer[0] = 5.
Person 5 has more money than 3, which has more money than 1, which has more money than 0.
The only person who is quieter (has lower quiet[x]) is person 7, but it is not clear if they have more money than person 0.
answer[7] = 7.
Among all people that definitely have equal to or more money than person 7 (which could be persons 3, 4, 5, 6, or 7), the person who is the quietest (has lower quiet[x]) is person 7.
The other answers can be filled out with similar reasoning.
Example 2:
Input: richer = [], quiet = [0]
Output: [0]
Constraints:
n == quiet.length
1 <= n <= 500
0 <= quiet[i] < n
All the values of quiet are unique.
0 <= richer.length <= n * (n - 1) / 2
0 <= ai, bi < n
ai != bi
All the pairs of richer are unique.
The observations in richer are all logically consistent.
| Medium | [
"array",
"depth-first-search",
"graph",
"topological-sort"
]
| null | []
|
852 | peak-index-in-a-mountain-array | []
| /**
* @param {number[]} arr
* @return {number}
*/
var peakIndexInMountainArray = function(arr) {
}; | An array arr is a mountain if the following properties hold:
arr.length >= 3
There exists some i with 0 < i < arr.length - 1 such that:
arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
Given a mountain array arr, return the index i such that arr[0] < arr[1] < ... < arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1].
You must solve it in O(log(arr.length)) time complexity.
Example 1:
Input: arr = [0,1,0]
Output: 1
Example 2:
Input: arr = [0,2,1,0]
Output: 1
Example 3:
Input: arr = [0,10,5,2]
Output: 1
Constraints:
3 <= arr.length <= 105
0 <= arr[i] <= 106
arr is guaranteed to be a mountain array.
| Medium | [
"array",
"binary-search"
]
| null | []
|
853 | car-fleet | []
| /**
* @param {number} target
* @param {number[]} position
* @param {number[]} speed
* @return {number}
*/
var carFleet = function(target, position, speed) {
}; | There are n cars going to the same destination along a one-lane road. The destination is target miles away.
You are given two integer array position and speed, both of length n, where position[i] is the position of the ith car and speed[i] is the speed of the ith car (in miles per hour).
A car can never pass another car ahead of it, but it can catch up to it and drive bumper to bumper at the same speed. The faster car will slow down to match the slower car's speed. The distance between these two cars is ignored (i.e., they are assumed to have the same position).
A car fleet is some non-empty set of cars driving at the same position and same speed. Note that a single car is also a car fleet.
If a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet.
Return the number of car fleets that will arrive at the destination.
Example 1:
Input: target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3]
Output: 3
Explanation:
The cars starting at 10 (speed 2) and 8 (speed 4) become a fleet, meeting each other at 12.
The car starting at 0 does not catch up to any other car, so it is a fleet by itself.
The cars starting at 5 (speed 1) and 3 (speed 3) become a fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target.
Note that no other cars meet these fleets before the destination, so the answer is 3.
Example 2:
Input: target = 10, position = [3], speed = [3]
Output: 1
Explanation: There is only one car, hence there is only one fleet.
Example 3:
Input: target = 100, position = [0,2,4], speed = [4,2,1]
Output: 1
Explanation:
The cars starting at 0 (speed 4) and 2 (speed 2) become a fleet, meeting each other at 4. The fleet moves at speed 2.
Then, the fleet (speed 2) and the car starting at 4 (speed 1) become one fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target.
Constraints:
n == position.length == speed.length
1 <= n <= 105
0 < target <= 106
0 <= position[i] < target
All the values of position are unique.
0 < speed[i] <= 106
| Medium | [
"array",
"stack",
"sorting",
"monotonic-stack"
]
| null | []
|
854 | k-similar-strings | []
| /**
* @param {string} s1
* @param {string} s2
* @return {number}
*/
var kSimilarity = function(s1, s2) {
}; | Strings s1 and s2 are k-similar (for some non-negative integer k) if we can swap the positions of two letters in s1 exactly k times so that the resulting string equals s2.
Given two anagrams s1 and s2, return the smallest k for which s1 and s2 are k-similar.
Example 1:
Input: s1 = "ab", s2 = "ba"
Output: 1
Explanation: The two string are 1-similar because we can use one swap to change s1 to s2: "ab" --> "ba".
Example 2:
Input: s1 = "abc", s2 = "bca"
Output: 2
Explanation: The two strings are 2-similar because we can use two swaps to change s1 to s2: "abc" --> "bac" --> "bca".
Constraints:
1 <= s1.length <= 20
s2.length == s1.length
s1 and s2 contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'}.
s2 is an anagram of s1.
| Hard | [
"string",
"breadth-first-search"
]
| [
"const kSimilarity = function(A, B) {\n if (A === B) return 0\n let arr = [[B, 0]]\n while (arr.length > 0) {\n let len = arr.length\n for (let i = 0; i < len; i++) {\n let [cur, step] = arr.shift()\n for (let i = 0; i < cur.length; i++) {\n if (cur[i] === A[i]) continue\n for (let j = i + 1; j < cur.length; j++) {\n if (cur[j] !== A[i]) continue\n let newStr =\n cur.substring(0, i) +\n cur[j] +\n cur.substring(i + 1, j) +\n cur[i] +\n cur.substring(j + 1)\n if (newStr === A) return step + 1\n if (cur[i] === A[j]) arr.unshift([newStr, step + 1])\n else arr.push([newStr, step + 1])\n }\n break\n }\n }\n }\n}"
]
|
|
855 | exam-room | []
| /**
* @param {number} n
*/
var ExamRoom = function(n) {
};
/**
* @return {number}
*/
ExamRoom.prototype.seat = function() {
};
/**
* @param {number} p
* @return {void}
*/
ExamRoom.prototype.leave = function(p) {
};
/**
* Your ExamRoom object will be instantiated and called as such:
* var obj = new ExamRoom(n)
* var param_1 = obj.seat()
* obj.leave(p)
*/ | There is an exam room with n seats in a single row labeled from 0 to n - 1.
When a student enters the room, they must sit in the seat that maximizes the distance to the closest person. If there are multiple such seats, they sit in the seat with the lowest number. If no one is in the room, then the student sits at seat number 0.
Design a class that simulates the mentioned exam room.
Implement the ExamRoom class:
ExamRoom(int n) Initializes the object of the exam room with the number of the seats n.
int seat() Returns the label of the seat at which the next student will set.
void leave(int p) Indicates that the student sitting at seat p will leave the room. It is guaranteed that there will be a student sitting at seat p.
Example 1:
Input
["ExamRoom", "seat", "seat", "seat", "seat", "leave", "seat"]
[[10], [], [], [], [], [4], []]
Output
[null, 0, 9, 4, 2, null, 5]
Explanation
ExamRoom examRoom = new ExamRoom(10);
examRoom.seat(); // return 0, no one is in the room, then the student sits at seat number 0.
examRoom.seat(); // return 9, the student sits at the last seat number 9.
examRoom.seat(); // return 4, the student sits at the last seat number 4.
examRoom.seat(); // return 2, the student sits at the last seat number 2.
examRoom.leave(4);
examRoom.seat(); // return 5, the student sits at the last seat number 5.
Constraints:
1 <= n <= 109
It is guaranteed that there is a student sitting at seat p.
At most 104 calls will be made to seat and leave.
| Medium | [
"design",
"heap-priority-queue",
"ordered-set"
]
| [
"const ExamRoom = function(n) {\n let a = [];\n return { seat, leave }\n function seat() {\n if (a.length == 0) {\n a.push(0);\n return 0;\n }\n let dis = Math.max(a[0], n - 1 - a[a.length - 1]);\n for (let i = 1; i < a.length; i++) dis = Math.max(dis, a[i] - a[i - 1] >> 1);\n if (a[0] == dis) {\n a.unshift(0);\n return 0;\n }\n for (let i = 1; i < a.length; i++) {\n if (a[i] - a[i - 1] >> 1 == dis) {\n a.splice(i, 0, a[i] + a[i - 1] >> 1);\n return a[i];\n }\n }\n a.push(n - 1);\n return n - 1;\n }\n function leave(p) {\n for (let i = 0; i < a.length; i++) {\n if (a[i] == p) {\n a.splice(i, 1);\n break;\n }\n }\n }\n};"
]
|
|
856 | score-of-parentheses | []
| /**
* @param {string} s
* @return {number}
*/
var scoreOfParentheses = function(s) {
}; | Given a balanced parentheses string s, return the score of the string.
The score of a balanced parentheses string is based on the following rule:
"()" has score 1.
AB has score A + B, where A and B are balanced parentheses strings.
(A) has score 2 * A, where A is a balanced parentheses string.
Example 1:
Input: s = "()"
Output: 1
Example 2:
Input: s = "(())"
Output: 2
Example 3:
Input: s = "()()"
Output: 2
Constraints:
2 <= s.length <= 50
s consists of only '(' and ')'.
s is a balanced parentheses string.
| Medium | [
"string",
"stack"
]
| [
"const scoreOfParentheses = function(S) {\n let res = 0,\n bal = 0;\n for (let i = 0; i < S.length; i++) {\n if (S.charAt(i) === \"(\") {\n bal += 1;\n } else {\n bal -= 1;\n if (S.charAt(i - 1) === \"(\") {\n res += 1 << bal;\n }\n }\n }\n return res;\n};"
]
|
|
857 | minimum-cost-to-hire-k-workers | []
| /**
* @param {number[]} quality
* @param {number[]} wage
* @param {number} k
* @return {number}
*/
var mincostToHireWorkers = function(quality, wage, k) {
}; | There are n workers. You are given two integer arrays quality and wage where quality[i] is the quality of the ith worker and wage[i] is the minimum wage expectation for the ith worker.
We want to hire exactly k workers to form a paid group. To hire a group of k workers, we must pay them according to the following rules:
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.
Given the integer k, return the least amount of money needed to form a paid group satisfying the above conditions. Answers within 10-5 of the actual answer will be accepted.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], k = 2
Output: 105.00000
Explanation: We pay 70 to 0th worker and 35 to 2nd worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], k = 3
Output: 30.66667
Explanation: We pay 4 to 0th worker, 13.33333 to 2nd and 3rd workers separately.
Constraints:
n == quality.length == wage.length
1 <= k <= n <= 104
1 <= quality[i], wage[i] <= 104
| Hard | [
"array",
"greedy",
"sorting",
"heap-priority-queue"
]
| [
"const mincostToHireWorkers = function(quality, wage, K) {\n const workers = [], n = quality.length;\n for (let i = 0; i < n; i++) {\n workers[i] = { ratio: wage[i] / quality[i], quality: quality[i] }\n }\n workers.sort((a, b) => a.ratio - b.ratio);\n const heap = new MaxPriorityQueue({ priority: x => x.quality });\n let totalQuality = 0, res = Infinity;\n while (workers.length) {\n const curWorker = workers.shift();\n totalQuality += curWorker.quality;\n heap.enqueue(curWorker);\n \n if (heap.size() > K) {\n totalQuality -= heap.dequeue().element.quality;\n }\n if (heap.size() === K) {\n res = Math.min(res, curWorker.ratio * totalQuality)\n }\n }\n return res;\n};",
"const mincostToHireWorkers = function(quality, wage, K) {\n const workers = Array.from({length: quality.length}, () => new Array(2));\n for (let i = 0; i < quality.length; ++i) workers[i] = [wage[i] / quality[i], quality[i]];\n workers.sort((a, b) => a[0] - b[0])\n let res = Number.MAX_VALUE, qsum = 0;\n const queue = []\n for (let worker of workers) {\n qsum += worker[1];\n insert(queue, -worker[1])\n if (queue.length > K) qsum += queue.shift();\n if (queue.length === K) res = Math.min(res, qsum * worker[0]);\n }\n return res;\n};\n\nfunction insert(arr, el) {\n for(let i = 0; i < arr.length; i++) {\n if(arr[i] > el) {\n arr.splice(i, 0, el)\n return\n }\n }\n arr.push(el)\n}",
"const mincostToHireWorkers = function(quality, wage, K) {\n const workers = [], n = wage.length\n for(let i = 0; i < n; i++) {\n workers.push([wage[i] / quality[i], quality[i]])\n }\n // wage[i] / wage[j] = quality[i] / quality[j]\n // wage[i] * quality[j] = wage[j] * quality[i]\n // wage[i] / quality[i] = wage[j] / quality[j]\n workers.sort((a, b) => a[0] - b[0])\n const pq = new MaxPriorityQueue({ priority: (w) => w.quality })\n let res = Infinity, qualitySum = 0\n for(const worker of workers) {\n const [ratio, quality] = worker\n qualitySum += quality\n pq.enqueue({ quality })\n \n if(pq.size() > K) {\n qualitySum -= pq.dequeue().element.quality\n }\n if(pq.size() === K) res = Math.min(res, qualitySum * ratio)\n }\n \n return res\n};"
]
|
|
858 | mirror-reflection | []
| /**
* @param {number} p
* @param {number} q
* @return {number}
*/
var mirrorReflection = function(p, q) {
}; | There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered 0, 1, and 2.
The square room has walls of length p and a laser ray from the southwest corner first meets the east wall at a distance q from the 0th receptor.
Given the two integers p and q, return the number of the receptor that the ray meets first.
The test cases are guaranteed so that the ray will meet a receptor eventually.
Example 1:
Input: p = 2, q = 1
Output: 2
Explanation: The ray meets receptor 2 the first time it gets reflected back to the left wall.
Example 2:
Input: p = 3, q = 1
Output: 1
Constraints:
1 <= q <= p <= 1000
| Medium | [
"math",
"geometry",
"number-theory"
]
| [
"const mirrorReflection = function(p, q) {\n while (p % 2 === 0 && q % 2 === 0) {\n p /= 2;\n q /= 2;\n }\n\n if (p % 2 === 0) {\n return 2;\n } else if (q % 2 === 0) {\n return 0;\n } else {\n return 1;\n }\n};"
]
|
|
859 | buddy-strings | []
| /**
* @param {string} s
* @param {string} goal
* @return {boolean}
*/
var buddyStrings = function(s, goal) {
}; | Given two strings s and goal, return true if you can swap two letters in s so the result is equal to goal, otherwise, return false.
Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at s[i] and s[j].
For example, swapping at indices 0 and 2 in "abcd" results in "cbad".
Example 1:
Input: s = "ab", goal = "ba"
Output: true
Explanation: You can swap s[0] = 'a' and s[1] = 'b' to get "ba", which is equal to goal.
Example 2:
Input: s = "ab", goal = "ab"
Output: false
Explanation: The only letters you can swap are s[0] = 'a' and s[1] = 'b', which results in "ba" != goal.
Example 3:
Input: s = "aa", goal = "aa"
Output: true
Explanation: You can swap s[0] = 'a' and s[1] = 'a' to get "aa", which is equal to goal.
Constraints:
1 <= s.length, goal.length <= 2 * 104
s and goal consist of lowercase letters.
| Easy | [
"hash-table",
"string"
]
| [
"const buddyStrings = function(A, B) {\n if(A.length !== B.length) return false\n const aCode = ('a').charCodeAt(0)\n if(A === B) {\n const count = new Array(26).fill(0)\n for(let i = 0; i < A.length; i++) {\n count[A.charCodeAt(i) - aCode]++\n }\n for(let el of count) {\n if(el > 1) return true\n }\n return false\n } else {\n const arr = []\n for(let i = 0; i < A.length; i++) {\n if(A[i] !== B[i]) {\n arr.push(i)\n if(arr.length > 2) return false\n }\n }\n if(arr.length !== 2) return false\n return A[arr[0]] === B[arr[1]] && A[arr[1]] === B[arr[0]]\n }\n};"
]
|
|
860 | lemonade-change | []
| /**
* @param {number[]} bills
* @return {boolean}
*/
var lemonadeChange = function(bills) {
}; | At a lemonade stand, each lemonade costs $5. Customers are standing in a queue to buy from you and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a $5, $10, or $20 bill. You must provide the correct change to each customer so that the net transaction is that the customer pays $5.
Note that you do not have any change in hand at first.
Given an integer array bills where bills[i] is the bill the ith customer pays, return true if you can provide every customer with the correct change, or false otherwise.
Example 1:
Input: bills = [5,5,5,10,20]
Output: true
Explanation:
From the first 3 customers, we collect three $5 bills in order.
From the fourth customer, we collect a $10 bill and give back a $5.
From the fifth customer, we give a $10 bill and a $5 bill.
Since all customers got correct change, we output true.
Example 2:
Input: bills = [5,5,10,10,20]
Output: false
Explanation:
From the first two customers in order, we collect two $5 bills.
For the next two customers in order, we collect a $10 bill and give back a $5 bill.
For the last customer, we can not give the change of $15 back because we only have two $10 bills.
Since not every customer received the correct change, the answer is false.
Constraints:
1 <= bills.length <= 105
bills[i] is either 5, 10, or 20.
| Easy | [
"array",
"greedy"
]
| [
"const lemonadeChange = function(bills) {\n let five = 0;\n let ten = 0;\n for (let el of bills) {\n if (el === 5) {\n five += 1;\n } else if (el === 10) {\n if (five < 1) return false;\n five -= 1;\n ten += 1;\n } else {\n if (five > 0 && ten > 0) {\n five -= 1;\n ten -= 1;\n } else if (five >= 3) {\n five -= 3;\n } else {\n return false;\n }\n }\n }\n\n return true;\n};"
]
|
|
861 | score-after-flipping-matrix | []
| /**
* @param {number[][]} grid
* @return {number}
*/
var matrixScore = function(grid) {
}; | You are given an m x n binary matrix grid.
A move consists of choosing any row or column and toggling each value in that row or column (i.e., changing all 0's to 1's, and all 1's to 0's).
Every row of the matrix is interpreted as a binary number, and the score of the matrix is the sum of these numbers.
Return the highest possible score after making any number of moves (including zero moves).
Example 1:
Input: grid = [[0,0,1,1],[1,0,1,0],[1,1,0,0]]
Output: 39
Explanation: 0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39
Example 2:
Input: grid = [[0]]
Output: 1
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 20
grid[i][j] is either 0 or 1.
| Medium | [
"array",
"greedy",
"bit-manipulation",
"matrix"
]
| [
"const matrixScore = function(grid) {\n const m = grid.length, n = grid[0].length\n let res = 0\n res += m * (1 << (n - 1))\n for(let j = 1; j < n; j++) {\n let same = 0\n for(let i = 0; i < m; i++) {\n if(grid[i][0] === grid[i][j]) same++\n }\n res += Math.max(same, m - same) * (1 << (n - 1 - j))\n }\n \n return res\n};",
"const matrixScore = function(grid) {\n const m = grid.length, n = grid[0].length\n for(let i = 0; i < m; i++) {\n if(grid[i][0] === 0) flipRow(i)\n }\n \n for(let i = 0; i < n; i++) {\n if(cntCol(i, 0) > cntCol(i, 1)) flipCol(i)\n }\n \n let res = 0\n // console.log(grid)\n for(const row of grid) {\n res += parseInt(row.join(''), 2)\n }\n \n return res\n \n \n function flipRow(idx) {\n for(let i = 0; i < n; i++) {\n if(grid[idx][i] === 0) grid[idx][i] = 1\n else grid[idx][i] = 0\n }\n }\n \n function cntCol(idx, target) {\n let res = 0\n for(let i = 0; i < m; i++) {\n if(grid[i][idx] === target) res++\n }\n // console.log(res)\n return res\n }\n \n function flipCol(idx) {\n for(let i = 0; i < m; i++) {\n if(grid[i][idx] === 0) grid[i][idx] = 1\n else grid[i][idx] = 0\n }\n }\n};"
]
|
|
862 | shortest-subarray-with-sum-at-least-k | []
| /**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var shortestSubarray = function(nums, k) {
}; | Given an integer array nums and an integer k, return the length of the shortest non-empty subarray of nums with a sum of at least k. If there is no such subarray, return -1.
A subarray is a contiguous part of an array.
Example 1:
Input: nums = [1], k = 1
Output: 1
Example 2:
Input: nums = [1,2], k = 4
Output: -1
Example 3:
Input: nums = [2,-1,2], k = 3
Output: 3
Constraints:
1 <= nums.length <= 105
-105 <= nums[i] <= 105
1 <= k <= 109
| Hard | [
"array",
"binary-search",
"queue",
"sliding-window",
"heap-priority-queue",
"prefix-sum",
"monotonic-queue"
]
| [
"const shortestSubarray = function(nums, k) {\n const q = [], n = nums.length\n let res = Infinity, sum = 0\n const prefix = []\n for(let i = 0; i < n; i++) {\n sum += nums[i]\n prefix.push(sum)\n if(sum >= k) res = Math.min(res, i + 1)\n }\n\n for(let i = 0; i < n; i++) {\n while(q.length && prefix[i] <= prefix[q[q.length - 1]]) q.pop()\n while(q.length && prefix[i] - prefix[q[0]] >= k) {\n res = Math.min(res, i - q[0])\n q.shift()\n }\n\n q.push(i)\n }\n \n return res === Infinity ? -1 : res\n};",
"const shortestSubarray = function(A, K) {\n const N = A.length\n const P = new Array(N+1).fill(0)\n \n for(let i = 0; i < N; i++) {\n P[i+1] = P[i] + A[i]\n }\n\n let ans = N + 1\n const monoq = []\n for(let y = 0; y < P.length; y++) {\n while(monoq.length > 0 && P[y] <= P[monoq[monoq.length - 1]] ) {\n monoq.pop()\n }\n while(monoq.length > 0 && P[y] >= P[monoq[0]] + K ) {\n ans = Math.min(ans, y - monoq.shift())\n }\n monoq.push(y)\n }\n\n return ans < N + 1 ? ans : -1\n};"
]
|
|
863 | all-nodes-distance-k-in-binary-tree | []
| /**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @param {TreeNode} target
* @param {number} k
* @return {number[]}
*/
var distanceK = function(root, target, k) {
}; | Given the root of a binary tree, the value of a target node target, and an integer k, return an array of the values of all nodes that have a distance k from the target node.
You can return the answer in any order.
Example 1:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, k = 2
Output: [7,4,1]
Explanation: The nodes that are a distance 2 from the target node (with value 5) have values 7, 4, and 1.
Example 2:
Input: root = [1], target = 1, k = 3
Output: []
Constraints:
The number of nodes in the tree is in the range [1, 500].
0 <= Node.val <= 500
All the values Node.val are unique.
target is the value of one of the nodes in the tree.
0 <= k <= 1000
| Medium | [
"tree",
"depth-first-search",
"breadth-first-search",
"binary-tree"
]
| /**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/ | [
"const distanceK = function(root, target, K) {\n const map = new Map();\n const res = [];\n if (target == null || K < 0 || root == null) return res;\n buildGraph(root, null);\n const visited = new Set();\n const q = [];\n visited.add(target);\n q.push(target);\n while (q.length) {\n const len = q.length;\n if (K === 0) {\n for (let i = 0; i < len; i++) res.push(q.shift().val);\n return res;\n }\n for (let i = 0; i < len; i++) {\n const el = q.shift();\n for (let e of map.get(el)) {\n if (visited.has(e)) continue;\n visited.add(e);\n q.push(e);\n }\n }\n K--;\n }\n return res;\n\n function buildGraph(node, parent) {\n if (node === null) return;\n if (!map.has(node)) {\n map.set(node, []);\n if (parent !== null) {\n map.get(node).push(parent);\n if (!map.has(parent)) map.set(parent, []);\n map.get(parent).push(node);\n }\n buildGraph(node.left, node);\n buildGraph(node.right, node);\n }\n }\n};",
"const distanceK = function(root, target, K) {\n let res = []\n dfs(root, target, K, res)\n return res\n}\n\nfunction dfs(node, target, k, res) {\n if (node === null) return -1\n if (node === target) {\n getRes(node, 0, k, res)\n return 1\n }\n let left = dfs(node.left, target, k, res)\n let right = dfs(node.right, target, k, res)\n if (left !== -1) {\n if (left === k) res.push(node.val)\n getRes(node.right, left + 1, k, res)\n return left + 1\n }\n if (right !== -1) {\n if (right === k) res.push(node.val)\n getRes(node.left, right + 1, k, res)\n return right + 1\n }\n return -1\n}\n\nfunction getRes(node, dist, k, res) {\n if (node === null) return\n if (dist === k) return res.push(node.val)\n getRes(node.left, dist + 1, k, res)\n getRes(node.right, dist + 1, k, res)\n}"
]
|
864 | shortest-path-to-get-all-keys | []
| /**
* @param {string[]} grid
* @return {number}
*/
var shortestPathAllKeys = function(grid) {
}; | You are given an m x n grid grid where:
'.' is an empty cell.
'#' is a wall.
'@' is the starting point.
Lowercase letters represent keys.
Uppercase letters represent locks.
You start at the starting point and one move consists of walking one space in one of the four cardinal directions. You cannot walk outside the grid, or walk into a wall.
If you walk over a key, you can pick it up and you cannot walk over a lock unless you have its corresponding key.
For some 1 <= k <= 6, there is exactly one lowercase and one uppercase letter of the first k letters of the English alphabet in the grid. This means that there is exactly one key for each lock, and one lock for each key; and also that the letters used to represent the keys and locks were chosen in the same order as the English alphabet.
Return the lowest number of moves to acquire all keys. If it is impossible, return -1.
Example 1:
Input: grid = ["@.a..","###.#","b.A.B"]
Output: 8
Explanation: Note that the goal is to obtain all the keys not to open all the locks.
Example 2:
Input: grid = ["@..aA","..B#.","....b"]
Output: 6
Example 3:
Input: grid = ["@Aa"]
Output: -1
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 30
grid[i][j] is either an English letter, '.', '#', or '@'.
There is exactly one '@' in the grid.
The number of keys in the grid is in the range [1, 6].
Each key in the grid is unique.
Each key in the grid has a matching lock.
| Hard | [
"array",
"bit-manipulation",
"breadth-first-search",
"matrix"
]
| [
"const shortestPathAllKeys = function(grid) {\n let r = grid.length,\n c = grid[0].length\n let moves = [[-1, 0], [1, 0], [0, 1], [0, -1]]\n let finalState = 0,\n startPoint = null\n for (let i = 0; i < r; i++) {\n for (let j = 0; j < c; j++) {\n let code = grid[i].charCodeAt(j) - 97\n if (code >= 0 && code <= 5) {\n finalState = finalState | (1 << code)\n } else if (grid[i][j] === '@') {\n startPoint = [i, j]\n }\n }\n }\n let visited = Array(finalState + 1)\n .fill()\n .map(() =>\n Array(r)\n .fill()\n .map(() => Array(c).fill(false))\n )\n let step = 0\n let arr = [[startPoint[0], startPoint[1], 0]]\n while (arr.length > 0) {\n let len = arr.length\n for (let i = 0; i < len; i++) {\n let [x, y, keysState] = arr.shift()\n for (let [dx, dy] of moves) {\n let newx = x + dx,\n newy = y + dy\n if (newx < 0 || newy < 0 || newx >= r || newy >= c) continue\n let curstr = grid[newx][newy]\n if (curstr === '#') continue\n let code = grid[newx].charCodeAt(newy)\n if (visited[keysState][newx][newy]) continue\n visited[keysState][newx][newy] = true\n if (code >= 65 && code <= 72 && ((1 << (code - 65)) & keysState) === 0)\n continue\n let newState = keysState\n if (\n code >= 97 &&\n code <= 102 &&\n ((1 << (code - 97)) & keysState) === 0\n ) {\n newState = newState | (1 << (code - 97))\n if (newState === finalState) return step + 1\n }\n arr.push([newx, newy, newState])\n }\n }\n step++\n }\n return -1\n}"
]
|
|
865 | smallest-subtree-with-all-the-deepest-nodes | []
| /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
var subtreeWithAllDeepest = function(root) {
}; | Given the root of a binary tree, the depth of each node is the shortest distance to the root.
Return the smallest subtree such that it contains all the deepest nodes in the original tree.
A node is called the deepest if it has the largest depth possible among any node in the entire tree.
The subtree of a node is a tree consisting of that node, plus the set of all descendants of that node.
Example 1:
Input: root = [3,5,1,6,2,0,8,null,null,7,4]
Output: [2,7,4]
Explanation: We return the node with value 2, colored in yellow in the diagram.
The nodes coloured in blue are the deepest nodes of the tree.
Notice that nodes 5, 3 and 2 contain the deepest nodes in the tree but node 2 is the smallest subtree among them, so we return it.
Example 2:
Input: root = [1]
Output: [1]
Explanation: The root is the deepest node in the tree.
Example 3:
Input: root = [0,1,3,null,2]
Output: [2]
Explanation: The deepest node in the tree is 2, the valid subtrees are the subtrees of nodes 2, 1 and 0 but the subtree of node 2 is the smallest.
Constraints:
The number of nodes in the tree will be in the range [1, 500].
0 <= Node.val <= 500
The values of the nodes in the tree are unique.
Note: This question is the same as 1123: https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/
| Medium | [
"hash-table",
"tree",
"depth-first-search",
"breadth-first-search",
"binary-tree"
]
| /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/ | [
"const subtreeWithAllDeepest = function(root) {\n return dfs(root).node;\n};\n\nfunction dfs(node) {\n if (node == null) return new result(null, 0);\n const l = dfs(node.left);\n const r = dfs(node.right);\n if (l.dist > r.dist) return new result(l.node, l.dist + 1);\n if (l.dist < r.dist) return new result(r.node, r.dist + 1);\n return new result(node, l.dist + 1);\n}\n\nfunction result(node, dist) {\n this.node = node;\n this.dist = dist;\n}",
"const subtreeWithAllDeepest = function(root) {\n let res = null, maxDepth = 0\n dfs(root, 0)\n \n return res\n \n function dfs(node, depth) {\n if(node == null) return depth - 1\n \n const left = dfs(node.left, depth + 1)\n const right = dfs(node.right, depth + 1)\n maxDepth = Math.max(maxDepth, left, right)\n \n if(left === maxDepth && right === maxDepth) {\n res = node\n }\n return Math.max(left, right)\n }\n};"
]
|
866 | prime-palindrome | []
| /**
* @param {number} n
* @return {number}
*/
var primePalindrome = function(n) {
}; | Given an integer n, return the smallest prime palindrome greater than or equal to n.
An integer is prime if it has exactly two divisors: 1 and itself. Note that 1 is not a prime number.
For example, 2, 3, 5, 7, 11, and 13 are all primes.
An integer is a palindrome if it reads the same from left to right as it does from right to left.
For example, 101 and 12321 are palindromes.
The test cases are generated so that the answer always exists and is in the range [2, 2 * 108].
Example 1:
Input: n = 6
Output: 7
Example 2:
Input: n = 8
Output: 11
Example 3:
Input: n = 13
Output: 101
Constraints:
1 <= n <= 108
| Medium | [
"math"
]
| [
"const primePalindrome = function(n) {\n if(n >= 8 && n <= 11) return 11\n const rev = str => str.split('').reverse().join('')\n for (let i = 1; i < 1e5; i++) {\n let left = `${i}`, right = rev(left).slice(1)\n let num = +(left + right)\n if (num >= n && isPrime(num)) return num\n }\n return -1\n\n function isPrime(num) {\n if(num < 2 || num % 2 === 0) return num === 2\n for(let i = 3; i * i <= num; i += 2) {\n if(num % i === 0) return false\n }\n return true\n }\n};",
"const primePalindrome = function(N) {\n if(N >= 8 && N <= 11) return 11\n for(let x = 1; x < 100000; x++) {\n let s = '' + x, r = s.split('').reverse().join('')\n let y = +(s + r.slice(1))\n if(y >= N && isPrime(y)) return y\n }\n return -1\n};\n\nfunction isPrime(x) {\n if(x < 2 || x % 2 === 0) return x === 2\n for(let i = 3; i * i <= x; i += 2) {\n if(x % i === 0) return false\n }\n return true\n}",
"const primePalindrome = function(n) {\n if(n >= 8 && n <= 11) return 11\n\n const rev = num => `${num}`.split('').reverse().join('')\n for(let i = 1; i < 1e5; i++) {\n let left = i, right = rev(left).slice(1)\n const tmp = +(left + right)\n if(tmp >= n && isPrime(tmp)) return tmp\n }\n\n function isPrime(num) {\n if(num <= 2) return num === 2\n if(num % 2 === 0) return false\n for(let i = 3; i ** 2 <= num; i += 2) {\n if(num % i === 0) return false\n }\n return true\n }\n};"
]
|
|
867 | transpose-matrix | [
"We don't need any special algorithms to do this. You just need to know what the transpose of a matrix looks like. Rows become columns and vice versa!"
]
| /**
* @param {number[][]} matrix
* @return {number[][]}
*/
var transpose = function(matrix) {
}; | Given a 2D integer array matrix, return the transpose of matrix.
The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices.
Example 1:
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[1,4,7],[2,5,8],[3,6,9]]
Example 2:
Input: matrix = [[1,2,3],[4,5,6]]
Output: [[1,4],[2,5],[3,6]]
Constraints:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 1000
1 <= m * n <= 105
-109 <= matrix[i][j] <= 109
| Easy | [
"array",
"matrix",
"simulation"
]
| null | []
|
868 | binary-gap | []
| /**
* @param {number} n
* @return {number}
*/
var binaryGap = function(n) {
}; | Given a positive integer n, find and return the longest distance between any two adjacent 1's in the binary representation of n. If there are no two adjacent 1's, return 0.
Two 1's are adjacent if there are only 0's separating them (possibly no 0's). The distance between two 1's is the absolute difference between their bit positions. For example, the two 1's in "1001" have a distance of 3.
Example 1:
Input: n = 22
Output: 2
Explanation: 22 in binary is "10110".
The first adjacent pair of 1's is "10110" with a distance of 2.
The second adjacent pair of 1's is "10110" with a distance of 1.
The answer is the largest of these two distances, which is 2.
Note that "10110" is not a valid pair since there is a 1 separating the two 1's underlined.
Example 2:
Input: n = 8
Output: 0
Explanation: 8 in binary is "1000".
There are not any adjacent pairs of 1's in the binary representation of 8, so we return 0.
Example 3:
Input: n = 5
Output: 2
Explanation: 5 in binary is "101".
Constraints:
1 <= n <= 109
| Easy | [
"bit-manipulation"
]
| [
"const binaryGap = function(N) {\n const bin = (N >>> 0).toString(2);\n const idxArr = [];\n for (let i = 0; i < bin.length; i++) {\n const num = bin.charAt(i);\n if (num === \"1\") {\n idxArr.push(i);\n }\n }\n let maxConLen = 0;\n for (let idx = 0; idx < idxArr.length - 1; idx++) {\n if (idxArr[idx + 1] - idxArr[idx] > maxConLen) {\n maxConLen = idxArr[idx + 1] - idxArr[idx];\n }\n }\n\n return maxConLen;\n};"
]
|
|
869 | reordered-power-of-2 | []
| /**
* @param {number} n
* @return {boolean}
*/
var reorderedPowerOf2 = function(n) {
}; | You are given an integer n. We reorder the digits in any order (including the original order) such that the leading digit is not zero.
Return true if and only if we can do this so that the resulting number is a power of two.
Example 1:
Input: n = 1
Output: true
Example 2:
Input: n = 10
Output: false
Constraints:
1 <= n <= 109
| Medium | [
"math",
"sorting",
"counting",
"enumeration"
]
| [
"const reorderedPowerOf2 = function(N) {\n const A = count(N);\n for (let i = 0; i < 31; i++) {\n if (arrayEqual(A, count(1 << i))) return true;\n }\n return false;\n};\n\nfunction count(num) {\n const res = [];\n while (num > 0) {\n addOne(res, num % 10);\n num = parseInt(num / 10);\n }\n return res;\n}\nfunction addOne(arr, idx) {\n if (arr[idx]) {\n arr[idx] += 1;\n return;\n }\n arr[idx] = 1;\n}\nfunction arrayEqual(a1, a2) {\n return JSON.stringify(a1) === JSON.stringify(a2);\n}\n\nconsole.log(reorderedPowerOf2(1));\nconsole.log(reorderedPowerOf2(10));\nconsole.log(reorderedPowerOf2(16));\nconsole.log(reorderedPowerOf2(24));\nconsole.log(reorderedPowerOf2(46));"
]
|
|
870 | advantage-shuffle | []
| /**
* @param {number[]} nums1
* @param {number[]} nums2
* @return {number[]}
*/
var advantageCount = function(nums1, nums2) {
}; | You are given two integer arrays nums1 and nums2 both of the same length. The advantage of nums1 with respect to nums2 is the number of indices i for which nums1[i] > nums2[i].
Return any permutation of nums1 that maximizes its advantage with respect to nums2.
Example 1:
Input: nums1 = [2,7,11,15], nums2 = [1,10,4,11]
Output: [2,11,7,15]
Example 2:
Input: nums1 = [12,24,8,32], nums2 = [13,25,32,11]
Output: [24,32,8,12]
Constraints:
1 <= nums1.length <= 105
nums2.length == nums1.length
0 <= nums1[i], nums2[i] <= 109
| Medium | [
"array",
"two-pointers",
"greedy",
"sorting"
]
| [
"function advantageCount(aArr, B) {\n const A = aArr.sort((a, b) => a - b)\n const n = A.length\n const res = []\n let pq = []\n for(let i = 0; i < n; i++) {\n pq.push([B[i], i])\n }\n pq.sort((a, b) => b[0] - a[0])\n let lo = 0\n let hi = n - 1\n while(pq.length > 0) {\n let cur = pq.shift()\n let idx = cur[1]\n let val = cur[0]\n if (A[hi] > val) {\n res[idx] = A[hi--]\n } else {\n res[idx] = A[lo++]\n }\n }\n return res\n}"
]
|
|
871 | minimum-number-of-refueling-stops | []
| /**
* @param {number} target
* @param {number} startFuel
* @param {number[][]} stations
* @return {number}
*/
var minRefuelStops = function(target, startFuel, stations) {
}; | A car travels from a starting position to a destination which is target miles east of the starting position.
There are gas stations along the way. The gas stations are represented as an array stations where stations[i] = [positioni, fueli] indicates that the ith gas station is positioni miles east of the starting position and has fueli liters of gas.
The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses one liter of gas per one mile that it drives. When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
Return the minimum number of refueling stops the car must make in order to reach its destination. If it cannot reach the destination, return -1.
Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.
Example 1:
Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: We can reach the target without refueling.
Example 2:
Input: target = 100, startFuel = 1, stations = [[10,100]]
Output: -1
Explanation: We can not reach the target (or even the first gas station).
Example 3:
Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2
Explanation: We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.
Constraints:
1 <= target, startFuel <= 109
0 <= stations.length <= 500
1 <= positioni < positioni+1 < target
1 <= fueli < 109
| Hard | [
"array",
"dynamic-programming",
"greedy",
"heap-priority-queue"
]
| [
"const minRefuelStops = function (target, startFuel, stations) {\n const dp = Array(stations.length + 1).fill(0)\n dp[0] = startFuel\n for (let i = 0; i < stations.length; ++i) {\n for (let t = i; t >= 0 && dp[t] >= stations[i][0]; --t) {\n dp[t + 1] = Math.max(dp[t + 1], dp[t] + stations[i][1])\n }\n }\n for (let t = 0; t <= stations.length; ++t) {\n if (dp[t] >= target) return t\n }\n return -1\n}"
]
|
|
872 | leaf-similar-trees | []
| /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root1
* @param {TreeNode} root2
* @return {boolean}
*/
var leafSimilar = function(root1, root2) {
}; | Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a leaf value sequence.
For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8).
Two binary trees are considered leaf-similar if their leaf value sequence is the same.
Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar.
Example 1:
Input: root1 = [3,5,1,6,2,9,8,null,null,7,4], root2 = [3,5,1,6,7,4,2,null,null,null,null,null,null,9,8]
Output: true
Example 2:
Input: root1 = [1,2,3], root2 = [1,3,2]
Output: false
Constraints:
The number of nodes in each tree will be in the range [1, 200].
Both of the given trees will have values in the range [0, 200].
| Easy | [
"tree",
"depth-first-search",
"binary-tree"
]
| null | []
|
873 | length-of-longest-fibonacci-subsequence | []
| /**
* @param {number[]} arr
* @return {number}
*/
var lenLongestFibSubseq = function(arr) {
}; | A sequence x1, x2, ..., xn is Fibonacci-like if:
n >= 3
xi + xi+1 == xi+2 for all i + 2 <= n
Given a strictly increasing array arr of positive integers forming a sequence, return the length of the longest Fibonacci-like subsequence of arr. If one does not exist, return 0.
A subsequence is derived from another sequence arr by deleting any number of elements (including none) from arr, without changing the order of the remaining elements. For example, [3, 5, 8] is a subsequence of [3, 4, 5, 6, 7, 8].
Example 1:
Input: arr = [1,2,3,4,5,6,7,8]
Output: 5
Explanation: The longest subsequence that is fibonacci-like: [1,2,3,5,8].
Example 2:
Input: arr = [1,3,7,11,12,14,18]
Output: 3
Explanation: The longest subsequence that is fibonacci-like: [1,11,12], [3,11,14] or [7,11,18].
Constraints:
3 <= arr.length <= 1000
1 <= arr[i] < arr[i + 1] <= 109
| Medium | [
"array",
"hash-table",
"dynamic-programming"
]
| [
"const lenLongestFibSubseq = function(A) {\n const n = A.length;\n let max = 0;\n const dp = Array(n).map(el => Array(n).fill(0));\n for (let i = 1; i < n; i++) {\n let l = 0,\n r = i - 1;\n while (l < r) {\n let sum = A[l] + A[r];\n if (sum > A[i]) {\n r--;\n } else if (sum < A[i]) {\n l++;\n } else {\n dp[r][i] = dp[l][r] + 1;\n max = Math.max(max, dp[r][i]);\n r--;\n l++;\n }\n }\n }\n return max == 0 ? 0 : max + 2;\n};"
]
|
|
874 | walking-robot-simulation | []
| /**
* @param {number[]} commands
* @param {number[][]} obstacles
* @return {number}
*/
var robotSim = function(commands, obstacles) {
}; | A robot on an infinite XY-plane starts at point (0, 0) facing north. The robot can receive a sequence of these three possible types of commands:
-2: Turn left 90 degrees.
-1: Turn right 90 degrees.
1 <= k <= 9: Move forward k units, one unit at a time.
Some of the grid squares are obstacles. The ith obstacle is at grid point obstacles[i] = (xi, yi). If the robot runs into an obstacle, then it will instead stay in its current location and move on to the next command.
Return the maximum Euclidean distance that the robot ever gets from the origin squared (i.e. if the distance is 5, return 25).
Note:
North means +Y direction.
East means +X direction.
South means -Y direction.
West means -X direction.
There can be obstacle in [0,0].
Example 1:
Input: commands = [4,-1,3], obstacles = []
Output: 25
Explanation: The robot starts at (0, 0):
1. Move north 4 units to (0, 4).
2. Turn right.
3. Move east 3 units to (3, 4).
The furthest point the robot ever gets from the origin is (3, 4), which squared is 32 + 42 = 25 units away.
Example 2:
Input: commands = [4,-1,4,-2,4], obstacles = [[2,4]]
Output: 65
Explanation: The robot starts at (0, 0):
1. Move north 4 units to (0, 4).
2. Turn right.
3. Move east 1 unit and get blocked by the obstacle at (2, 4), robot is at (1, 4).
4. Turn left.
5. Move north 4 units to (1, 8).
The furthest point the robot ever gets from the origin is (1, 8), which squared is 12 + 82 = 65 units away.
Example 3:
Input: commands = [6,-1,-1,6], obstacles = []
Output: 36
Explanation: The robot starts at (0, 0):
1. Move north 6 units to (0, 6).
2. Turn right.
3. Turn right.
4. Move south 6 units to (0, 0).
The furthest point the robot ever gets from the origin is (0, 6), which squared is 62 = 36 units away.
Constraints:
1 <= commands.length <= 104
commands[i] is either -2, -1, or an integer in the range [1, 9].
0 <= obstacles.length <= 104
-3 * 104 <= xi, yi <= 3 * 104
The answer is guaranteed to be less than 231.
| Medium | [
"array",
"simulation"
]
| [
"const robotSim = function(commands, obstacles) {\n const dirs = [[1, 0], [0, -1], [-1, 0], [0, 1]] // east, south, west, north\n const set = new Set()\n obstacles.forEach(([x, y]) => set.add(`${x},${y}`))\n let idx = 3, x = 0, y = 0, res = 0\n for(let e of commands) {\n if(e === -2) idx = (3 + idx) % 4\n else if(e === -1) idx = (1 + idx) % 4\n else {\n const [dx, dy] = dirs[idx]\n let dis = 0\n while(dis < e) {\n const nx = x + dx, ny = y + dy\n const k = `${nx},${ny}`\n if(set.has(k)) break\n x = nx\n y = ny\n dis++\n res = Math.max(res, x * x + y * y)\n }\n }\n }\n \n return res\n};"
]
|
|
875 | koko-eating-bananas | []
| /**
* @param {number[]} piles
* @param {number} h
* @return {number}
*/
var minEatingSpeed = function(piles, h) {
}; | Koko loves to eat bananas. There are n piles of bananas, the ith pile has piles[i] bananas. The guards have gone and will come back in h hours.
Koko can decide her bananas-per-hour eating speed of k. Each hour, she chooses some pile of bananas and eats k bananas from that pile. If the pile has less than k bananas, she eats all of them instead and will not eat any more bananas during this hour.
Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return.
Return the minimum integer k such that she can eat all the bananas within h hours.
Example 1:
Input: piles = [3,6,7,11], h = 8
Output: 4
Example 2:
Input: piles = [30,11,23,4,20], h = 5
Output: 30
Example 3:
Input: piles = [30,11,23,4,20], h = 6
Output: 23
Constraints:
1 <= piles.length <= 104
piles.length <= h <= 109
1 <= piles[i] <= 109
| Medium | [
"array",
"binary-search"
]
| [
"const minEatingSpeed = function(piles, h) {\n let ma = -1\n for(const e of piles) {\n if(e > ma) ma = e\n }\n \n let l = 1, r = ma\n \n while(l < r) {\n const mid = Math.floor((l + r) / 2)\n if(valid(mid)) {\n r = mid\n } else {\n l = mid + 1\n }\n }\n \n return l\n \n function valid(val) {\n let res = 0\n for(const e of piles) {\n res += Math.ceil(e / val)\n }\n \n return res <= h\n }\n};"
]
|
|
876 | middle-of-the-linked-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 middleNode = function(head) {
}; | Given the head of a singly linked list, return the middle node of the linked list.
If there are two middle nodes, return the second middle node.
Example 1:
Input: head = [1,2,3,4,5]
Output: [3,4,5]
Explanation: The middle node of the list is node 3.
Example 2:
Input: head = [1,2,3,4,5,6]
Output: [4,5,6]
Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one.
Constraints:
The number of nodes in the list is in the range [1, 100].
1 <= Node.val <= 100
| Easy | [
"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 middleNode = function (head) {\n if (head == null) return null\n let count = 1\n let iter = head\n while (iter.next) {\n iter = iter.next\n count++\n }\n count = (count / 2) >> 0\n while (count) {\n head = head.next\n count--\n }\n return head\n}"
]
|
877 | stone-game | []
| /**
* @param {number[]} piles
* @return {boolean}
*/
var stoneGame = function(piles) {
}; | Alice and Bob play a game with piles of stones. There are an even number of piles arranged in a row, and each pile has a positive integer number of stones piles[i].
The objective of the game is to end with the most stones. The total number of stones across all the piles is odd, so there are no ties.
Alice and Bob take turns, with Alice starting first. Each turn, a player takes the entire pile of stones either from the beginning or from the end of the row. This continues until there are no more piles left, at which point the person with the most stones wins.
Assuming Alice and Bob play optimally, return true if Alice wins the game, or false if Bob wins.
Example 1:
Input: piles = [5,3,4,5]
Output: true
Explanation:
Alice starts first, and can only take the first 5 or the last 5.
Say she takes the first 5, so that the row becomes [3, 4, 5].
If Bob takes 3, then the board is [4, 5], and Alice takes 5 to win with 10 points.
If Bob takes the last 5, then the board is [3, 4], and Alice takes 4 to win with 9 points.
This demonstrated that taking the first 5 was a winning move for Alice, so we return true.
Example 2:
Input: piles = [3,7,2,3]
Output: true
Constraints:
2 <= piles.length <= 500
piles.length is even.
1 <= piles[i] <= 500
sum(piles[i]) is odd.
| Medium | [
"array",
"math",
"dynamic-programming",
"game-theory"
]
| null | []
|
878 | nth-magical-number | []
| /**
* @param {number} n
* @param {number} a
* @param {number} b
* @return {number}
*/
var nthMagicalNumber = function(n, a, b) {
}; | A positive integer is magical if it is divisible by either a or b.
Given the three integers n, a, and b, return the nth magical number. Since the answer may be very large, return it modulo 109 + 7.
Example 1:
Input: n = 1, a = 2, b = 3
Output: 2
Example 2:
Input: n = 4, a = 2, b = 3
Output: 6
Constraints:
1 <= n <= 109
2 <= a, b <= 4 * 104
| Hard | [
"math",
"binary-search"
]
| [
"const gcd = (x, y) => {\n while (y > 0) [x, y] = [y, x % y]\n return x\n}\nconst lcm = (x, y) => (x * y) / gcd(x, y)\nconst nthMagicalNumber = function(N, A, B) {\n let l = lcm(A, B)\n const seq = {}\n for (let i = 1; i < Math.floor(l / A) + 1; i++) seq[i * A] = 1\n for (let i = 1; i < Math.floor(l / B) + 1; i++) seq[i * B] = 1\n const arr = Object.keys(seq)\n .sort((a, b) => a - b)\n .map(el => +el)\n let idx = N % arr.length === 0 ? arr.length - 1 : (N % arr.length) - 1\n let res = Math.floor((N - 1) / arr.length) * arr[arr.length - 1] + arr[idx]\n return res % (1e9 + 7)\n}",
"const nthMagicalNumber = function(N, A, B) {\n const gcd = (x, y) => {\n if (x == 0) return y\n return gcd(y % x, x)\n }\n const MOD = 1e9 + 7\n const L = (A / gcd(A, B)) * B\n let lo = 0\n let hi = 1e15\n while (lo < hi) {\n let mi = lo + Math.trunc((hi - lo) / 2)\n if (Math.trunc(mi / A) + Math.trunc(mi / B) - Math.trunc(mi / L) < N) lo = mi + 1\n else hi = mi\n }\n return lo % MOD\n}"
]
|
|
879 | profitable-schemes | []
| /**
* @param {number} n
* @param {number} minProfit
* @param {number[]} group
* @param {number[]} profit
* @return {number}
*/
var profitableSchemes = function(n, minProfit, group, profit) {
}; | There is a group of n members, and a list of various crimes they could commit. The ith crime generates a profit[i] and requires group[i] members to participate in it. If a member participates in one crime, that member can't participate in another crime.
Let's call a profitable scheme any subset of these crimes that generates at least minProfit profit, and the total number of members participating in that subset of crimes is at most n.
Return the number of schemes that can be chosen. Since the answer may be very large, return it modulo 109 + 7.
Example 1:
Input: n = 5, minProfit = 3, group = [2,2], profit = [2,3]
Output: 2
Explanation: To make a profit of at least 3, the group could either commit crimes 0 and 1, or just crime 1.
In total, there are 2 schemes.
Example 2:
Input: n = 10, minProfit = 5, group = [2,3,5], profit = [6,7,8]
Output: 7
Explanation: To make a profit of at least 5, the group could commit any crimes, as long as they commit one.
There are 7 possible schemes: (0), (1), (2), (0,1), (0,2), (1,2), and (0,1,2).
Constraints:
1 <= n <= 100
0 <= minProfit <= 100
1 <= group.length <= 100
1 <= group[i] <= 100
profit.length == group.length
0 <= profit[i] <= 100
| Hard | [
"array",
"dynamic-programming"
]
| [
"const profitableSchemes = function(G, P, group, profit) {\n const dp = Array.from({ length: P + 1 }, () => new Array(G + 1).fill(0))\n dp[0][0] = 1\n let res = 0,\n mod = 10 ** 9 + 7\n for (let k = 0; k < group.length; k++) {\n let g = group[k],\n p = profit[k]\n for (let i = P; i >= 0; i--)\n for (let j = G - g; j >= 0; j--)\n dp[Math.min(i + p, P)][j + g] =\n (dp[Math.min(i + p, P)][j + g] + dp[i][j]) % mod\n }\n for (let x of dp[P]) res = (res + x) % mod\n return res\n}"
]
|
|
880 | decoded-string-at-index | []
| /**
* @param {string} s
* @param {number} k
* @return {string}
*/
var decodeAtIndex = function(s, k) {
}; | You are given an encoded string s. To decode the string to a tape, the encoded string is read one character at a time and the following steps are taken:
If the character read is a letter, that letter is written onto the tape.
If the character read is a digit d, the entire current tape is repeatedly written d - 1 more times in total.
Given an integer k, return the kth letter (1-indexed) in the decoded string.
Example 1:
Input: s = "leet2code3", k = 10
Output: "o"
Explanation: The decoded string is "leetleetcodeleetleetcodeleetleetcode".
The 10th letter in the string is "o".
Example 2:
Input: s = "ha22", k = 5
Output: "h"
Explanation: The decoded string is "hahahaha".
The 5th letter is "h".
Example 3:
Input: s = "a2345678999999999999999", k = 1
Output: "a"
Explanation: The decoded string is "a" repeated 8301530446056247680 times.
The 1st letter is "a".
Constraints:
2 <= s.length <= 100
s consists of lowercase English letters and digits 2 through 9.
s starts with a letter.
1 <= k <= 109
It is guaranteed that k is less than or equal to the length of the decoded string.
The decoded string is guaranteed to have less than 263 letters.
| Medium | [
"string",
"stack"
]
| [
"const decodeAtIndex = function(S, K) {\n let n = S.length;\n let dp = Array(n + 1).fill(0);\n for (let i = 0; i < n; i++) {\n if (S[i] >= \"2\" && S[i] <= \"9\") {\n dp[i + 1] = dp[i] * (S[i] - \"0\");\n } else {\n dp[i + 1] = dp[i] + 1;\n }\n }\n K--;\n for (let i = n - 1; i >= 0; i--) {\n K %= dp[i + 1];\n if (K + 1 == dp[i + 1] && !(S[i] >= \"2\" && S[i] <= \"9\")) {\n return \"\" + S[i];\n }\n }\n return null;\n};"
]
|
|
881 | boats-to-save-people | []
| /**
* @param {number[]} people
* @param {number} limit
* @return {number}
*/
var numRescueBoats = function(people, limit) {
}; | You are given an array people where people[i] is the weight of the ith person, and an infinite number of boats where each boat can carry a maximum weight of limit. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most limit.
Return the minimum number of boats to carry every given person.
Example 1:
Input: people = [1,2], limit = 3
Output: 1
Explanation: 1 boat (1, 2)
Example 2:
Input: people = [3,2,2,1], limit = 3
Output: 3
Explanation: 3 boats (1, 2), (2) and (3)
Example 3:
Input: people = [3,5,3,4], limit = 5
Output: 4
Explanation: 4 boats (3), (3), (4), (5)
Constraints:
1 <= people.length <= 5 * 104
1 <= people[i] <= limit <= 3 * 104
| Medium | [
"array",
"two-pointers",
"greedy",
"sorting"
]
| [
"const numRescueBoats = function(people, limit) {\n if(people.length === 0) return 0\n const arr = people.sort((a, b) => a - b)\n let count = 0\n let i = 0\n let j = arr.length - 1\n while(i <= j) {\n count++\n if(arr[i] + arr[j] <= limit) {\n i++\n }\n j--\n }\n\n return count\n};"
]
|
|
882 | reachable-nodes-in-subdivided-graph | []
| /**
* @param {number[][]} edges
* @param {number} maxMoves
* @param {number} n
* @return {number}
*/
var reachableNodes = function(edges, maxMoves, n) {
}; | You are given an undirected graph (the "original graph") with n nodes labeled from 0 to n - 1. You decide to subdivide each edge in the graph into a chain of nodes, with the number of new nodes varying between each edge.
The graph is given as a 2D array of edges where edges[i] = [ui, vi, cnti] indicates that there is an edge between nodes ui and vi in the original graph, and cnti is the total number of new nodes that you will subdivide the edge into. Note that cnti == 0 means you will not subdivide the edge.
To subdivide the edge [ui, vi], replace it with (cnti + 1) new edges and cnti new nodes. The new nodes are x1, x2, ..., xcnti, and the new edges are [ui, x1], [x1, x2], [x2, x3], ..., [xcnti-1, xcnti], [xcnti, vi].
In this new graph, you want to know how many nodes are reachable from the node 0, where a node is reachable if the distance is maxMoves or less.
Given the original graph and maxMoves, return the number of nodes that are reachable from node 0 in the new graph.
Example 1:
Input: edges = [[0,1,10],[0,2,1],[1,2,2]], maxMoves = 6, n = 3
Output: 13
Explanation: The edge subdivisions are shown in the image above.
The nodes that are reachable are highlighted in yellow.
Example 2:
Input: edges = [[0,1,4],[1,2,6],[0,2,8],[1,3,1]], maxMoves = 10, n = 4
Output: 23
Example 3:
Input: edges = [[1,2,4],[1,4,5],[1,3,1],[2,3,4],[3,4,5]], maxMoves = 17, n = 5
Output: 1
Explanation: Node 0 is disconnected from the rest of the graph, so only node 0 is reachable.
Constraints:
0 <= edges.length <= min(n * (n - 1) / 2, 104)
edges[i].length == 3
0 <= ui < vi < n
There are no multiple edges in the graph.
0 <= cnti <= 104
0 <= maxMoves <= 109
1 <= n <= 3000
| Hard | [
"graph",
"heap-priority-queue",
"shortest-path"
]
| [
"const reachableNodes = function(edges, maxMoves, n) {\n let res = 0,\n heap = new Heap(),\n state = new Array(n).fill(0),\n graph = Array.from(new Array(n), () => []),\n distance = new Array(n).fill(Number.MAX_SAFE_INTEGER);\n for (let [u, v, d] of edges) {\n graph[u].push([v, d]);\n graph[v].push([u, d]);\n }\n distance[0] = 0;\n heap.insert([0, distance[0]]);\n while (heap.length != 0) {\n let t = heap.remove();\n if (state[t[0]] === 1) continue;\n if (distance[t[0]] <= maxMoves) res++;\n state[t[0]] = 1;\n for (let i of graph[t[0]]) {\n if (distance[i[0]] > distance[t[0]] + i[1] + 1) {\n distance[i[0]] = distance[t[0]] + i[1] + 1;\n heap.insert([i[0], distance[i[0]]]);\n }\n }\n }\n for (let [u, v, d] of edges) {\n let a = maxMoves - distance[u] >= 0 ? maxMoves - distance[u] : 0,\n b = maxMoves - distance[v] >= 0 ? maxMoves - distance[v] : 0;\n res += Math.min(d, a + b);\n }\n return res;\n};\n\nclass Heap {\n constructor() {\n this.heap = [];\n }\n\n get length() {\n return this.heap.length;\n }\n\n compare(i, j) {\n if (!this.heap[j]) return false;\n return this.heap[i][1] > this.heap[j][1];\n }\n\n swap(i, j) {\n const temp = this.heap[i];\n this.heap[i] = this.heap[j];\n this.heap[j] = temp;\n }\n\n insert(num) {\n this.heap.push(num);\n let idx = this.length - 1;\n let parent = (idx - 1) >> 1;\n while (idx !== 0 && this.compare(parent, idx)) {\n this.swap(parent, idx);\n idx = parent;\n parent = (idx - 1) >> 1;\n }\n }\n\n remove() {\n if (this.length === 1) return this.heap.pop();\n let res = this.heap[0],\n idx = 0,\n left = 1 | (idx << 1),\n right = (1 + idx) << 1;\n this.heap[0] = this.heap.pop();\n while (this.compare(idx, left) || this.compare(idx, right)) {\n if (this.compare(left, right)) {\n this.swap(idx, right);\n idx = right;\n } else {\n this.swap(idx, left);\n idx = left;\n }\n left = 1 | (idx << 1);\n right = (1 + idx) << 1;\n }\n return res;\n }\n}",
"const reachableNodes = function (edges, M, N) {\n const graph = Array.from({ length: N }, () => Array(N).fill(-1))\n for (let edge of edges) {\n graph[edge[0]][edge[1]] = edge[2]\n graph[edge[1]][edge[0]] = edge[2]\n }\n let result = 0\n const pq = new PriorityQueue((a, b) => a[1] > b[1])\n const visited = new Array(N).fill(false)\n pq.push([0, M])\n while (!pq.isEmpty()) {\n const cur = pq.pop()\n const start = cur[0]\n const move = cur[1]\n if (visited[start]) {\n continue\n }\n visited[start] = true\n result++\n for (let i = 0; i < N; i++) {\n if (graph[start][i] > -1) {\n if (move > graph[start][i] && !visited[i]) {\n pq.push([i, move - graph[start][i] - 1])\n }\n graph[i][start] -= Math.min(move, graph[start][i])\n result += Math.min(move, graph[start][i])\n }\n }\n }\n return result\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}",
"// time complexity: \n// Dijkstra + Heap is O(E log E)\n// worst case: O(N ^ 2 * log (N ^ 2))\n\nconst reachableNodes = function(edges, M, N) {\n const graph = {}\n for(const [u,v,c] of edges) {\n if(graph[u] == null) graph[u] = {}\n if(graph[v] == null) graph[v] = {}\n graph[u][v] = c\n graph[v][u] = c\n }\n const pq = new PriorityQueue((a, b) => a[0] > b[0])\n pq.push([M, 0])\n const visited = {}\n while(!pq.isEmpty()) {\n const [moves, i] = pq.pop()\n if(visited[i] == null) {\n visited[i] = moves\n for(const k of Object.keys(graph[i] || {})) {\n const remain = moves - graph[i][k] - 1\n if(visited[k] == null && remain >= 0) {\n pq.push([remain, k])\n }\n }\n }\n }\n let res = 0\n res += Object.keys(visited).length\n for(const [u, v, c] of edges) {\n const a = visited[u] || 0, b = visited[v] || 0\n res += Math.min(a + b, c)\n }\n\n return res\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}"
]
|
|
883 | projection-area-of-3d-shapes | []
| /**
* @param {number[][]} grid
* @return {number}
*/
var projectionArea = function(grid) {
}; | You are given an n x n grid where we place some 1 x 1 x 1 cubes that are axis-aligned with the x, y, and z axes.
Each value v = grid[i][j] represents a tower of v cubes placed on top of the cell (i, j).
We view the projection of these cubes onto the xy, yz, and zx planes.
A projection is like a shadow, that maps our 3-dimensional figure to a 2-dimensional plane. We are viewing the "shadow" when looking at the cubes from the top, the front, and the side.
Return the total area of all three projections.
Example 1:
Input: grid = [[1,2],[3,4]]
Output: 17
Explanation: Here are the three projections ("shadows") of the shape made with each axis-aligned plane.
Example 2:
Input: grid = [[2]]
Output: 5
Example 3:
Input: grid = [[1,0],[0,2]]
Output: 8
Constraints:
n == grid.length == grid[i].length
1 <= n <= 50
0 <= grid[i][j] <= 50
| Easy | [
"array",
"math",
"geometry",
"matrix"
]
| [
"const projectionArea = function(grid) {\n let xy = 0, xz = 0, yz = 0\n const m = grid.length, n = grid[0].length\n for (let i = 0; i < m; i++) {\n for(let j = 0; j < n; j++) {\n if(grid[i][j]) xy++\n }\n }\n \n for (let i = 0; i < m; i++) {\n let tmp = 0\n for(let j = 0; j < n; j++) {\n tmp = Math.max(tmp, grid[i][j])\n }\n xz += tmp\n }\n for (let j = 0; j < n; j++) {\n let tmp = 0\n for(let i = 0; i < m; i++) {\n tmp = Math.max(tmp, grid[i][j]) \n }\n yz += tmp\n }\n \n return xy + yz + xz\n};"
]
|
|
884 | uncommon-words-from-two-sentences | []
| /**
* @param {string} s1
* @param {string} s2
* @return {string[]}
*/
var uncommonFromSentences = function(s1, s2) {
}; | A sentence is a string of single-space separated words where each word consists only of lowercase letters.
A word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence.
Given two sentences s1 and s2, return a list of all the uncommon words. You may return the answer in any order.
Example 1:
Input: s1 = "this apple is sweet", s2 = "this apple is sour"
Output: ["sweet","sour"]
Example 2:
Input: s1 = "apple apple", s2 = "banana"
Output: ["banana"]
Constraints:
1 <= s1.length, s2.length <= 200
s1 and s2 consist of lowercase English letters and spaces.
s1 and s2 do not have leading or trailing spaces.
All the words in s1 and s2 are separated by a single space.
| Easy | [
"hash-table",
"string"
]
| [
"const uncommonFromSentences = function(s1, s2) {\n const hash = {}\n const a1 = s1.split(' '), a2 = s2.split(' ')\n for(let e of a1) {\n if(hash[e] == null) hash[e] = 0\n hash[e]++\n }\n const res = []\n for(let e of a2) {\n if(hash[e] == null) hash[e] = 0\n hash[e]++\n }\n Object.keys(hash).forEach(k => {\n if(hash[k] === 1) res.push(k)\n })\n \n return res\n};"
]
|
|
885 | spiral-matrix-iii | []
| /**
* @param {number} rows
* @param {number} cols
* @param {number} rStart
* @param {number} cStart
* @return {number[][]}
*/
var spiralMatrixIII = function(rows, cols, rStart, cStart) {
}; | You start at the cell (rStart, cStart) of an rows x cols grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column.
You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid's boundary, we continue our walk outside the grid (but may return to the grid boundary later.). Eventually, we reach all rows * cols spaces of the grid.
Return an array of coordinates representing the positions of the grid in the order you visited them.
Example 1:
Input: rows = 1, cols = 4, rStart = 0, cStart = 0
Output: [[0,0],[0,1],[0,2],[0,3]]
Example 2:
Input: rows = 5, cols = 6, rStart = 1, cStart = 4
Output: [[1,4],[1,5],[2,5],[2,4],[2,3],[1,3],[0,3],[0,4],[0,5],[3,5],[3,4],[3,3],[3,2],[2,2],[1,2],[0,2],[4,5],[4,4],[4,3],[4,2],[4,1],[3,1],[2,1],[1,1],[0,1],[4,0],[3,0],[2,0],[1,0],[0,0]]
Constraints:
1 <= rows, cols <= 100
0 <= rStart < rows
0 <= cStart < cols
| Medium | [
"array",
"matrix",
"simulation"
]
| null | []
|
886 | possible-bipartition | []
| /**
* @param {number} n
* @param {number[][]} dislikes
* @return {boolean}
*/
var possibleBipartition = function(n, dislikes) {
}; | We want to split a group of n people (labeled from 1 to n) into two groups of any size. Each person may dislike some other people, and they should not go into the same group.
Given the integer n and the array dislikes where dislikes[i] = [ai, bi] indicates that the person labeled ai does not like the person labeled bi, return true if it is possible to split everyone into two groups in this way.
Example 1:
Input: n = 4, dislikes = [[1,2],[1,3],[2,4]]
Output: true
Explanation: The first group has [1,4], and the second group has [2,3].
Example 2:
Input: n = 3, dislikes = [[1,2],[1,3],[2,3]]
Output: false
Explanation: We need at least 3 groups to divide them. We cannot put them in two groups.
Constraints:
1 <= n <= 2000
0 <= dislikes.length <= 104
dislikes[i].length == 2
1 <= ai < bi <= n
All the pairs of dislikes are unique.
| Medium | [
"depth-first-search",
"breadth-first-search",
"union-find",
"graph"
]
| [
"const possibleBipartition = function (N, dislikes) {\n const graph = []\n for (let i = 0; i <= N; i++) {\n graph[i] = []\n }\n for (let el of dislikes) {\n graph[el[0]].push(el[1])\n graph[el[1]].push(el[0])\n }\n const color = new Array(N + 1).fill(0)\n for (let i = 1; i <= N; i++) {\n if (color[i] == 0) {\n color[i] = 1\n const q = []\n q.push(i)\n while (q.length > 0) {\n let cur = q.shift()\n for (let j of graph[cur]) {\n if (color[j] == 0) {\n color[j] = color[cur] == 1 ? 2 : 1\n q.push(j)\n } else {\n if (color[j] == color[cur]) return false\n }\n }\n }\n }\n }\n return true\n}",
"const possibleBipartition = function (N, dislikes) {\n const graph = new Array(N + 1)\n for (const [a, b] of dislikes) {\n if (!graph[a]) graph[a] = []\n graph[a].push(b)\n if (!graph[b]) graph[b] = []\n graph[b].push(a)\n }\n\n const colors = new Array(N + 1)\n const dfs = (node, color = 0) => {\n colors[node] = color\n const nextColor = color ^ 1\n const children = graph[node] || []\n for (const child of children) {\n if (colors[child] !== undefined) {\n if (colors[child] !== nextColor) return false\n } else {\n if (!dfs(child, nextColor)) return false\n }\n }\n return true\n }\n for (let i = 1; i <= N; i++) {\n if (colors[i] === undefined && !dfs(i)) return false\n }\n return true\n}"
]
|
|
887 | super-egg-drop | []
| /**
* @param {number} k
* @param {number} n
* @return {number}
*/
var superEggDrop = function(k, n) {
}; | You are given k identical eggs and you have access to a building with n floors labeled from 1 to n.
You know that there exists a floor f where 0 <= f <= n such that any egg dropped at a floor higher than f will break, and any egg dropped at or below floor f will not break.
Each move, you may take an unbroken egg and drop it from any floor x (where 1 <= x <= n). If the egg breaks, you can no longer use it. However, if the egg does not break, you may reuse it in future moves.
Return the minimum number of moves that you need to determine with certainty what the value of f is.
Example 1:
Input: k = 1, n = 2
Output: 2
Explanation:
Drop the egg from floor 1. If it breaks, we know that f = 0.
Otherwise, drop the egg from floor 2. If it breaks, we know that f = 1.
If it does not break, then we know f = 2.
Hence, we need at minimum 2 moves to determine with certainty what the value of f is.
Example 2:
Input: k = 2, n = 6
Output: 3
Example 3:
Input: k = 3, n = 14
Output: 4
Constraints:
1 <= k <= 100
1 <= n <= 104
| Hard | [
"math",
"binary-search",
"dynamic-programming"
]
| [
"const superEggDrop = function(K, N) {\n let lo = 1,\n hi = N,\n mi\n while (lo < hi) {\n mi = ((lo + hi) / 2) >> 0\n if (f(mi, K, N) < N) lo = mi + 1\n else hi = mi\n }\n return lo\n}\n\nfunction f(x, K, N) {\n let ans = 0,\n r = 1,\n i = 1\n for (let i = 1; i <= K; ++i) {\n r = ((r * (x - i + 1)) / i) >> 0\n ans += r\n if (ans >= N) break\n }\n return ans\n}",
"const superEggDrop = function(K, N) {\n const dp = Array.from({ length: K + 1 }, () => new Array(N + 1).fill(0))\n return helper(K, N, dp)\n}\nfunction helper(K, N, memo) {\n if (N <= 1) {\n return N\n }\n if (K === 1) {\n return N\n }\n if (memo[K][N] > 0) {\n return memo[K][N]\n }\n\n let low = 1,\n high = N,\n result = N\n while (low < high) {\n let mid = Math.floor(low + (high - low) / 2)\n let left = helper(K - 1, mid - 1, memo)\n let right = helper(K, N - mid, memo)\n result = Math.min(result, Math.max(left, right) + 1)\n if (left === right) {\n break\n } else if (left < right) {\n low = mid + 1\n } else {\n high = mid\n }\n }\n memo[K][N] = result\n return result\n}"
]
|
|
888 | fair-candy-swap | []
| /**
* @param {number[]} aliceSizes
* @param {number[]} bobSizes
* @return {number[]}
*/
var fairCandySwap = function(aliceSizes, bobSizes) {
}; | Alice and Bob have a different total number of candies. You are given two integer arrays aliceSizes and bobSizes where aliceSizes[i] is the number of candies of the ith box of candy that Alice has and bobSizes[j] is the number of candies of the jth box of candy that Bob has.
Since they are friends, they would like to exchange one candy box each so that after the exchange, they both have the same total amount of candy. The total amount of candy a person has is the sum of the number of candies in each box they have.
Return an integer array answer where answer[0] is the number of candies in the box that Alice must exchange, and answer[1] is the number of candies in the box that Bob must exchange. If there are multiple answers, you may return any one of them. It is guaranteed that at least one answer exists.
Example 1:
Input: aliceSizes = [1,1], bobSizes = [2,2]
Output: [1,2]
Example 2:
Input: aliceSizes = [1,2], bobSizes = [2,3]
Output: [1,2]
Example 3:
Input: aliceSizes = [2], bobSizes = [1,3]
Output: [2,3]
Constraints:
1 <= aliceSizes.length, bobSizes.length <= 104
1 <= aliceSizes[i], bobSizes[j] <= 105
Alice and Bob have a different total number of candies.
There will be at least one valid answer for the given input.
| Easy | [
"array",
"hash-table",
"binary-search",
"sorting"
]
| [
"const fairCandySwap = function(aliceSizes, bobSizes) {\n let sum = 0\n for(let e of aliceSizes) sum += e\n for(let e of bobSizes) sum -= e\n // sum > 0, alice > bob\n // sum < 0, alice < bob\n sum /= 2\n const set = new Set()\n for(let e of aliceSizes) set.add(e)\n for(let e of bobSizes) {\n if(set.has(e + sum)) return [e + sum, e]\n }\n return [0]\n};"
]
|
|
889 | construct-binary-tree-from-preorder-and-postorder-traversal | []
| /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {number[]} preorder
* @param {number[]} postorder
* @return {TreeNode}
*/
var constructFromPrePost = function(preorder, postorder) {
}; | Given two integer arrays, preorder and postorder where preorder is the preorder traversal of a binary tree of distinct values and postorder is the postorder traversal of the same tree, reconstruct and return the binary tree.
If there exist multiple answers, you can return any of them.
Example 1:
Input: preorder = [1,2,4,5,3,6,7], postorder = [4,5,2,6,7,3,1]
Output: [1,2,3,4,5,6,7]
Example 2:
Input: preorder = [1], postorder = [1]
Output: [1]
Constraints:
1 <= preorder.length <= 30
1 <= preorder[i] <= preorder.length
All the values of preorder are unique.
postorder.length == preorder.length
1 <= postorder[i] <= postorder.length
All the values of postorder are unique.
It is guaranteed that preorder and postorder are the preorder traversal and postorder traversal of the same binary tree.
| Medium | [
"array",
"hash-table",
"divide-and-conquer",
"tree",
"binary-tree"
]
| /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/ | [
"const constructFromPrePost = function(pre, post) {\n let i = 0,\n j = 0\n return (function dfs() {\n let val = pre[i++]\n let node = new TreeNode(val)\n if (val !== post[j]) node.left = dfs()\n if (val !== post[j]) node.right = dfs()\n j++\n return node\n })()\n}"
]
|
890 | find-and-replace-pattern | []
| /**
* @param {string[]} words
* @param {string} pattern
* @return {string[]}
*/
var findAndReplacePattern = function(words, pattern) {
}; | Given a list of strings words and a string pattern, return a list of words[i] that match pattern. You may return the answer in any order.
A word matches the pattern if there exists a permutation of letters p so that after replacing every letter x in the pattern with p(x), we get the desired word.
Recall that a permutation of letters is a bijection from letters to letters: every letter maps to another letter, and no two letters map to the same letter.
Example 1:
Input: words = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb"
Output: ["mee","aqq"]
Explanation: "mee" matches the pattern because there is a permutation {a -> m, b -> e, ...}.
"ccc" does not match the pattern because {a -> c, b -> c, ...} is not a permutation, since a and b map to the same letter.
Example 2:
Input: words = ["a","b","c"], pattern = "a"
Output: ["a","b","c"]
Constraints:
1 <= pattern.length <= 20
1 <= words.length <= 50
words[i].length == pattern.length
pattern and words[i] are lowercase English letters.
| Medium | [
"array",
"hash-table",
"string"
]
| [
"const findAndReplacePattern = (words, pattern) => {\n return words.reduce((acc, item, index) => {\n if (compose(words[index], pattern)) acc.push(words[index]);\n return acc;\n }, []);\n\n function compose(element, pattern) {\n const s = new Set();\n const m = new Map();\n for (let i = 0; i < element.length; i++) {\n const e = element[i];\n const p = pattern[i];\n s.add(e);\n if (m.get(p) === undefined) {\n m.set(p, e);\n } else if (m.get(p) !== e) {\n return false;\n }\n }\n return m.size === s.size;\n }\n};\n\n// anoother\n\n\nconst findAndReplacePattern = function(words, pattern) {\n const p = helper(pattern);\n const res = [];\n for (let w of words) {\n if (arrEqual(helper(w), p)) res.push(w);\n }\n return res;\n};\n\nfunction arrEqual(a, b) {\n if (a.length !== b.length) return false;\n for (let i = 0, len = a.length; i < len; i++) {\n if (a[i] !== b[i]) return false;\n }\n return true;\n}\n\nfunction helper(w) {\n const m = new Map();\n const n = w.length;\n const res = new Array(n).fill(0);\n for (let i = 0; i < n; i++) {\n if (!m.has(w[i])) m.set(w[i], m.size);\n res[i] = m.get(w[i]);\n }\n return res;\n}"
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.