From a570fd0bebf2fa64f83f9c49d6c1a94fcd87cb1d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 17 Dec 2019 23:28:58 -0500 Subject: [PATCH 001/919] Initial commit --- README.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 00000000..d5dc0a35 --- /dev/null +++ b/README.md @@ -0,0 +1,9 @@ +# LeetCode solutions in JavaScript + +[https://leetcode.com/](https://leetcode.com/) + +## License + +[MIT License](https://opensource.org/licenses/MIT) + +Copyright (c) 2019 [Josh Crozier](https://joshcrozier.com) From 371c40b07410ce10bc2e662c7503a750e43c0880 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 17 Dec 2019 23:35:19 -0500 Subject: [PATCH 002/919] Add solution #1290 --- ...nary-number-in-a-linked-list-to-integer.js | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 1290-convert-binary-number-in-a-linked-list-to-integer.js diff --git a/1290-convert-binary-number-in-a-linked-list-to-integer.js b/1290-convert-binary-number-in-a-linked-list-to-integer.js new file mode 100644 index 00000000..da99bb95 --- /dev/null +++ b/1290-convert-binary-number-in-a-linked-list-to-integer.js @@ -0,0 +1,32 @@ +/** + * 1290. Convert Binary Number in a Linked List to Integer + * https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/ + * Difficulty: Easy + * + * Given `head` which is a reference node to a singly-linked list. + * The value of each node in the linked list is either 0 or 1. + * The linked list holds the binary representation of a number. + * Return the decimal value of the number in the linked list. + */ + +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ +/** + * @param {ListNode} head + * @return {number} + */ +var getDecimalValue = function(head) { + let binary = String(head.val); + + while (head.next !== null) { + head = head.next; + binary += head.val; + } + + return parseInt(binary, 2); +}; From c15f416f0995e91472f493b670643711d1a31891 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 17 Dec 2019 23:39:34 -0500 Subject: [PATCH 003/919] Add solution #1291 --- 1291-sequential-digits.js | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 1291-sequential-digits.js diff --git a/1291-sequential-digits.js b/1291-sequential-digits.js new file mode 100644 index 00000000..077d6a45 --- /dev/null +++ b/1291-sequential-digits.js @@ -0,0 +1,29 @@ +/** + * 1291. Sequential Digits + * https://leetcode.com/problems/sequential-digits/ + * Difficulty: Medium + * + * An integer has sequential digits if and only if each digit in the number is one more than the previous digit. + * Return a sorted list of all the integers in the range [low, high] inclusive that have sequential digits. + */ + +/** + * @param {number} low + * @param {number} high + * @return {number[]} + */ +var sequentialDigits = function(low, high) { + return getSequentialNumbers().filter(n => n >= low && n <= high); +}; + +function getSequentialNumbers() { + const numbers = new Set([]); + + for (let i = 0; i < 10; i++) { + for (let j = 9; j > 0 && j > i + 1; j--) { + numbers.add(+'123456789'.slice(i, j)); + } + } + + return [...numbers].sort((a, b) => a - b); +} From d23bc2d5f2bf920cb3f55b61f8b422ef6e4b02b0 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 17 Dec 2019 23:45:57 -0500 Subject: [PATCH 004/919] Add solution #1292 --- ...ith-sum-less-than-or-equal-to-threshold.js | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 1292-maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold.js diff --git a/1292-maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold.js b/1292-maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold.js new file mode 100644 index 00000000..67723550 --- /dev/null +++ b/1292-maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold.js @@ -0,0 +1,37 @@ +/** + * 1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold + * https://leetcode.com/problems/maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/ + * Difficulty: Medium + * + * Given a `m x n` matrix `mat` and an integer `threshold`. + * Return the maximum side-length of a square with a sum less than or equal to `threshold` or return 0 if there is no such square. + */ + +/** + * @param {number[][]} mat + * @param {number} threshold + * @return {number} + */ +var maxSideLength = function(mat, threshold) { + let max = 0; + + loop1: for (let i = 0; i < mat[0].length; i++) { + loop2: for (let j = 0; j < mat.length; j++) { + if (!mat[j + 1] || !mat[j][i + 1]) { break loop2; } + loop3: for (let s = 1; s < 1000; s++) { + if (!mat[j + s] || !mat[j][i + s] || getSquareSum(mat, i, j, s + 1) > threshold) { break loop3; } + max = Math.max(s + 1, max); + } + } + } + + return max; +}; + +function getSquareSum(mat, i, j, size) { + let sum = 0; + for (let s = 0; s < size; s++) { + mat[j + s].slice(i, i + size).forEach(v => sum += v); + } + return sum; +} From 1bf733e5cd5ed730381b522e07e1bfb057db61e8 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 4 Jan 2020 23:14:34 -0500 Subject: [PATCH 005/919] Add solution #1287 --- ...-appearing-more-than-25-in-sorted-array.js | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 1287-element-appearing-more-than-25-in-sorted-array.js diff --git a/1287-element-appearing-more-than-25-in-sorted-array.js b/1287-element-appearing-more-than-25-in-sorted-array.js new file mode 100644 index 00000000..4d9bd3e2 --- /dev/null +++ b/1287-element-appearing-more-than-25-in-sorted-array.js @@ -0,0 +1,25 @@ +/** + * 1287. Element Appearing More Than 25% In Sorted Array + * https://leetcode.com/problems/element-appearing-more-than-25-in-sorted-array/ + * Difficulty: Easy + * + * Given an integer array sorted in non-decreasing order, + * there is exactly one integer in the array that occurs more than 25% of the time. + * + * Return that integer. + */ + +/** + * @param {number[]} arr + * @return {number} + */ +var findSpecialInteger = function(arr) { + const limit = arr.length * 0.25; + const offset = limit % 1 === 0 ? limit : Math.ceil(limit) - 1; + + for (let i = 0; i < arr.length; i++) { + if (arr[i] === arr[i + offset]) { + return arr[i]; + } + } +}; \ No newline at end of file From d8ee22d87850c4f6e5d9382fd0cddaf24b29d6f3 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 5 Jan 2020 00:28:35 -0500 Subject: [PATCH 006/919] Add solution #1252 --- 1252-cells-with-odd-values-in-a-matrix.js | 34 +++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 1252-cells-with-odd-values-in-a-matrix.js diff --git a/1252-cells-with-odd-values-in-a-matrix.js b/1252-cells-with-odd-values-in-a-matrix.js new file mode 100644 index 00000000..cbbffc45 --- /dev/null +++ b/1252-cells-with-odd-values-in-a-matrix.js @@ -0,0 +1,34 @@ +/** + * 1252. Cells with Odd Values in a Matrix + * https://leetcode.com/problems/cells-with-odd-values-in-a-matrix/ + * Difficulty: Easy + * + * Given `n` and `m` which are the dimensions of a matrix + * initialized by zeros and given an array `indices` + * where `indices[i] = [ri, ci]`. + * For each pair of `[ri, ci]` you have to increment all + * cells in row `ri` and column `ci` by 1. + * + * Return the number of cells with odd values in the + * matrix after applying the increment to all `indices`. + */ + +/** + * @param {number} n + * @param {number} m + * @param {number[][]} indices + * @return {number} + */ +var oddCells = function(n, m, indices) { + const matrix = new Array(n).fill().map(_ => new Array(m).fill(0)); + + indices.forEach(indice => { + const [row, column] = indice; + matrix[row].forEach((value, index) => matrix[row][index] = value + 1); + matrix.forEach(row => row[column] = row[column] + 1); + }); + + return matrix.reduce((count, row) => { + return count + row.filter(value => value % 2 !== 0).length; + }, 0); +}; From f89f104f62cfd64fefb4c448247a127da6f4ebc7 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 5 Jan 2020 23:11:12 -0500 Subject: [PATCH 007/919] Add solution #58 --- 0058-length-of-last-word.js | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 0058-length-of-last-word.js diff --git a/0058-length-of-last-word.js b/0058-length-of-last-word.js new file mode 100644 index 00000000..db2632c8 --- /dev/null +++ b/0058-length-of-last-word.js @@ -0,0 +1,23 @@ +/** + * 58. Length of Last Word + * https://leetcode.com/problems/length-of-last-word/ + * Difficulty: Easy + * + * Given a string `s` consists of upper/lower-case alphabets + * and empty space characters ' ', return the length of last + * word (last word means the last appearing word if we loop + * from left to right) in the string. + * + * If the last word does not exist, return 0. + * + * Note: A word is defined as a maximal substring consisting + * of non-space characters only. + */ + +/** + * @param {string} s + * @return {number} + */ +var lengthOfLastWord = function(s) { + return s.trim().split(/\s+/).pop().length; +}; From 072f2983e3905b4637359c0ce6f4811b05b071e5 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 5 Jan 2020 23:26:09 -0500 Subject: [PATCH 008/919] Add solution #1232 --- 1232-check-if-it-is-a-straight-line.js | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 1232-check-if-it-is-a-straight-line.js diff --git a/1232-check-if-it-is-a-straight-line.js b/1232-check-if-it-is-a-straight-line.js new file mode 100644 index 00000000..691780d0 --- /dev/null +++ b/1232-check-if-it-is-a-straight-line.js @@ -0,0 +1,21 @@ +/** + * 1232. Check If It Is a Straight Line + * https://leetcode.com/problems/check-if-it-is-a-straight-line/ + * Difficulty: Easy + * + * You are given an array `coordinates`, `coordinates[i] = [x, y]`, + * where `[x, y] represents the coordinate of a point. + * + * Check if these points make a straight line in the XY plane. + */ + +/** + * @param {number[][]} coordinates + * @return {boolean} + */ +var checkStraightLine = function(coords) { + const m = (coords[0][1] - coords[1][1]) / (coords[0][0] - coords[1][0]); + const b = coords[0][1] - m * coords[0][0]; + + return coords.every(coord => coord[1] === m * coord[0] + b); +}; From ab7ac000521f91f21cc3e43cfeb79a6f2e78b7c7 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 6 Jan 2020 23:16:36 -0500 Subject: [PATCH 009/919] Add solution #1103 --- 1103-distribute-candies-to-people.js | 38 ++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 1103-distribute-candies-to-people.js diff --git a/1103-distribute-candies-to-people.js b/1103-distribute-candies-to-people.js new file mode 100644 index 00000000..b808b80a --- /dev/null +++ b/1103-distribute-candies-to-people.js @@ -0,0 +1,38 @@ +/** + * 1103. Distribute Candies to People + * https://leetcode.com/problems/distribute-candies-to-people/ + * Difficulty: Easy + * + * We distribute some number of `candies`, to a row of `n = num_people` + * people in the following way: + * + * We then give 1 candy to the first person, 2 candies to the second + * person, and so on until we give `n` candies to the last person. + * + * Then, we go back to the start of the row, giving `n + 1` candies to + * the first person, `n + 2` candies to the second person, and so on + * until we give `2 * n` candies to the last person. + * + * This process repeats (with us giving one more candy each time, + * and moving to the start of the row after we reach the end) until + * we run out of candies. The last person will receive all of our + * remaining candies (not necessarily one more than the previous gift). + * + * Return an array (of length `num_people` and sum `candies`) that + * represents the final distribution of candies. + */ + +/** + * @param {number} candies + * @param {number} num_people + * @return {number[]} + */ +var distributeCandies = function(candies, num_people) { + const answer = new Array(num_people).fill(0); + + for (let amount = 0; candies > 0; candies -= amount) { + answer[amount % num_people] += Math.min(candies, ++amount); + } + + return answer; +}; From 83420010d77adb9a55c19100fb3607015b6136c2 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 6 Jan 2020 23:49:19 -0500 Subject: [PATCH 010/919] Add solution #1009 --- 1009-complement-of-base-10-integer.js | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 1009-complement-of-base-10-integer.js diff --git a/1009-complement-of-base-10-integer.js b/1009-complement-of-base-10-integer.js new file mode 100644 index 00000000..8b48eef1 --- /dev/null +++ b/1009-complement-of-base-10-integer.js @@ -0,0 +1,25 @@ +/** + * 1009. Complement of Base 10 Integer + * https://leetcode.com/problems/complement-of-base-10-integer/ + * Difficulty: Easy + * + * Every non-negative integer N has a binary representation. + * For example, 5 can be represented as "101" in binary, + * 11 as "1011" in binary, and so on. Note that except for + * N = 0, there are no leading zeroes in any binary representation. + * + * The complement of a binary representation is the number in binary + * you get when changing every 1 to a 0 and 0 to a 1. For example, + * the complement of "101" in binary is "010" in binary. + * + * For a given number N in base-10, return the complement of it's + * binary representation as a base-10 integer. + */ + +/** + * @param {number} N + * @return {number} + */ +var bitwiseComplement = function(N) { + return parseInt(N.toString(2).split('').map(n => n ^ 1).join(''), 2); +}; From f9edab224a7178ae6898ad06ace0794a37efb296 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 7 Jan 2020 22:07:03 -0500 Subject: [PATCH 011/919] Add solution #989 --- 0989-add-to-arrayform-of-integer.js | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 0989-add-to-arrayform-of-integer.js diff --git a/0989-add-to-arrayform-of-integer.js b/0989-add-to-arrayform-of-integer.js new file mode 100644 index 00000000..715e131e --- /dev/null +++ b/0989-add-to-arrayform-of-integer.js @@ -0,0 +1,21 @@ +/** + * 989. Add to Array-Form of Integer + * https://leetcode.com/problems/add-to-array-form-of-integer/ + * Difficulty: Easy + * + * For a non-negative integer X, the array-form of X is + * an array of its digits in left to right order. + * For example, if X = 1231, then the array form is [1,2,3,1]. + * + * Given the array-form A of a non-negative integer X, + * return the array-form of the integer X+K. + */ + +/** + * @param {number[]} A + * @param {number} K + * @return {number[]} + */ +var addToArrayForm = function(A, K) { + return String(BigInt(A.join('')) + BigInt(K)).split(''); +}; From 2ddd3d6e9b2a954af4bcac40d1af92f2f859d8fe Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 7 Jan 2020 22:31:34 -0500 Subject: [PATCH 012/919] Add solution #977 --- 0977-squares-of-a-sorted-array.js | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 0977-squares-of-a-sorted-array.js diff --git a/0977-squares-of-a-sorted-array.js b/0977-squares-of-a-sorted-array.js new file mode 100644 index 00000000..e1a37507 --- /dev/null +++ b/0977-squares-of-a-sorted-array.js @@ -0,0 +1,17 @@ +/** + * 977. Squares of a Sorted Array + * https://leetcode.com/problems/squares-of-a-sorted-array/ + * Difficulty: Easy + * + * Given an array of integers A sorted in non-decreasing order, + * return an array of the squares of each number, + * also in sorted non-decreasing order. + */ + +/** + * @param {number[]} A + * @return {number[]} + */ +var sortedSquares = function(A) { + return A.map(n => Math.pow(n, 2)).sort((a, b) => a - b); +}; From 6baa71b5f4d8a5e30961e88471175b9d69fe2a63 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 8 Jan 2020 22:28:40 -0500 Subject: [PATCH 013/919] Add solution #976 --- 0976-largest-perimeter-triangle.js | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 0976-largest-perimeter-triangle.js diff --git a/0976-largest-perimeter-triangle.js b/0976-largest-perimeter-triangle.js new file mode 100644 index 00000000..ec9c72c2 --- /dev/null +++ b/0976-largest-perimeter-triangle.js @@ -0,0 +1,28 @@ +/** + * 976. Largest Perimeter Triangle + * https://leetcode.com/problems/largest-perimeter-triangle/ + * Difficulty: Easy + * + * Given an array A of positive lengths, return the largest + * perimeter of a triangle with non-zero area, formed from 3 + * of these lengths. + * + * If it is impossible to form any triangle of non-zero + * area, return 0. + */ + +/** + * @param {number[]} A + * @return {number} + */ +var largestPerimeter = function(A) { + A.sort((a, b) => a - b); + + for (let i = A.length - 1; i > 1; --i) { + if (A[i] < A[i - 1] + A[i - 2]) { + return A[i] + A[i - 1] + A[i - 2]; + } + } + + return 0; +}; From 35c876077de0fe910a4cc850c3955a37d55a2a0a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 8 Jan 2020 22:52:46 -0500 Subject: [PATCH 014/919] Add solution #970 --- 0970-powerful-integers.js | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 0970-powerful-integers.js diff --git a/0970-powerful-integers.js b/0970-powerful-integers.js new file mode 100644 index 00000000..327dc660 --- /dev/null +++ b/0970-powerful-integers.js @@ -0,0 +1,37 @@ +/** + * 970. Powerful Integers + * https://leetcode.com/problems/powerful-integers/ + * Difficulty: Easy + * + * Given two positive integers x and y, an integer + * is powerful if it is equal to x^i + y^j for some + * integers i >= 0 and j >= 0. + * + * Return a list of all powerful integers that have + * value less than or equal to bound. + * + * You may return the answer in any order. In your + * answer, each value should occur at most once. + */ + +/** + * @param {number} x + * @param {number} y + * @param {number} bound + * @return {number[]} + */ +var powerfulIntegers = function(x, y, bound) { + const result = new Set(); + + for (let i = 1; i < bound; i *= x) { + for (let j = 1; i + j <= bound; j *= y) { + result.add(i + j); + + if (y === 1) { break }; + } + + if (x === 1) { break }; + } + + return Array.from(result); +}; From f2b3b8593ddf0a28d1d23c97a116052c169d40aa Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 8 Jan 2020 23:04:20 -0500 Subject: [PATCH 015/919] Add solution #985 --- 0985-sum-of-even-numbers-after-queries.js | 29 +++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 0985-sum-of-even-numbers-after-queries.js diff --git a/0985-sum-of-even-numbers-after-queries.js b/0985-sum-of-even-numbers-after-queries.js new file mode 100644 index 00000000..2f75f8d8 --- /dev/null +++ b/0985-sum-of-even-numbers-after-queries.js @@ -0,0 +1,29 @@ +/** + * 985. Sum of Even Numbers After Queries + * https://leetcode.com/problems/sum-of-even-numbers-after-queries/ + * Difficulty: Easy + * + * We have an array A of integers, and an array queries of queries. + * + * For the i-th query val = queries[i][0], index = queries[i][1], + * we add val to A[index]. Then, the answer to the i-th query + * is the sum of the even values of A. + * + * (Here, the given index = queries[i][1] is a 0-based index, and + * each query permanently modifies the array A.) + * + * Return the answer to all queries. Your answer array should + * have answer[i] as the answer to the i-th query. + */ + +/** + * @param {number[]} A + * @param {number[][]} queries + * @return {number[]} + */ +var sumEvenAfterQueries = function(A, queries) { + return queries.reduce((sums, query) => { + A[query[1]] += query[0]; + return [...sums, A.reduce((sum, n) => sum + (n % 2 === 0 ? n : 0), 0)]; + }, []); +}; From 87055ab10bf564f758ef41ee58109035f9916f3a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 9 Jan 2020 23:15:40 -0500 Subject: [PATCH 016/919] Add solution #985 --- 0985-sum-of-even-numbers-after-queries.js | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/0985-sum-of-even-numbers-after-queries.js b/0985-sum-of-even-numbers-after-queries.js index 2f75f8d8..fcb6468a 100644 --- a/0985-sum-of-even-numbers-after-queries.js +++ b/0985-sum-of-even-numbers-after-queries.js @@ -27,3 +27,20 @@ var sumEvenAfterQueries = function(A, queries) { return [...sums, A.reduce((sum, n) => sum + (n % 2 === 0 ? n : 0), 0)]; }, []); }; + +// Significantly faster, less elegant approach: +/** + * @param {number[]} A + * @param {number[][]} queries + * @return {number[]} + */ +var sumEvenAfterQueries = function(A, queries) { + return queries.reduce((sums, query) => { + const [v, i] = query; + const prev = A[i]; + const lastSum = sums.length ? sums[sums.length - 1] : A.reduce((sum, n) => sum + (n % 2 === 0 ? n : 0), 0); + A[i] += v; + sums.push(lastSum - (prev % 2 === 0 ? prev : 0) + (A[i] % 2 === 0 ? A[i] : 0)); + return sums; + }, []); +}; From fc767976337c492154ac177926523359598f5101 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 9 Jan 2020 23:37:23 -0500 Subject: [PATCH 017/919] Add solution #929 --- 0929-unique-email-addresses.js | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 0929-unique-email-addresses.js diff --git a/0929-unique-email-addresses.js b/0929-unique-email-addresses.js new file mode 100644 index 00000000..fc3a29e5 --- /dev/null +++ b/0929-unique-email-addresses.js @@ -0,0 +1,33 @@ +/** + * 929. Unique Email Addresses + * https://leetcode.com/problems/unique-email-addresses/ + * Difficulty: Easy + * + * Every email consists of a local name and a domain name, separated by the @ sign. + * + * For example, in alice@leetcode.com, alice is the local name, and leetcode.com is the domain name. + * + * Besides lowercase letters, these emails may contain '.'s or '+'s. + * + * If you add periods ('.') between some characters in the local name part of an email address, mail + * sent there will be forwarded to the same address without dots in the local name. + * For example, "alice.z@leetcode.com" and "alicez@leetcode.com" forward to the same email address. + * (Note that this rule does not apply for domain names.) + * + * If you add a plus ('+') in the local name, everything after the first plus sign will be ignored. + * This allows certain emails to be filtered, for example m.y+name@email.com will be forwarded to + * my@email.com. (Again, this rule does not apply for domain names.) + * + * It is possible to use both of these rules at the same time. + * + * Given a list of emails, we send one email to each address in the list. + * How many different addresses actually receive mails? + */ + +/** + * @param {string[]} emails + * @return {number} + */ +var numUniqueEmails = function(emails) { + return new Set(emails.map(e => e.replace(/\.(?=[\w\.+]+@)|\+[\w.+]+(?=@)/g, ''))).size; +}; From 6c9333535ce1f56f3621124cb8538beb003774c5 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 11 Jan 2020 14:10:54 -0500 Subject: [PATCH 018/919] Add solution #387 --- 0387-first-unique-character-in-a-string.js | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 0387-first-unique-character-in-a-string.js diff --git a/0387-first-unique-character-in-a-string.js b/0387-first-unique-character-in-a-string.js new file mode 100644 index 00000000..4004b60b --- /dev/null +++ b/0387-first-unique-character-in-a-string.js @@ -0,0 +1,22 @@ +/** + * 387. First Unique Character in a String + * https://leetcode.com/problems/first-unique-character-in-a-string/ + * Difficulty: Easy + * + * Given a string, find the first non-repeating character in + * it and return it's index. If it doesn't exist, return -1. + */ + +/** + * @param {string} s + * @return {number} + */ +var firstUniqChar = function(s) { + for (let i = 0; i < s.length; i++) { + if (s.indexOf(s.charAt(i)) === s.lastIndexOf(s.charAt(i))) { + return i; + } + } + + return -1; +}; From 169b717afd065a6c51a8ee9971cc382e63478b4f Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 11 Jan 2020 19:37:08 -0500 Subject: [PATCH 019/919] Add solution #451 --- 0451-sort-characters-by-frequency.js | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 0451-sort-characters-by-frequency.js diff --git a/0451-sort-characters-by-frequency.js b/0451-sort-characters-by-frequency.js new file mode 100644 index 00000000..4c29eed3 --- /dev/null +++ b/0451-sort-characters-by-frequency.js @@ -0,0 +1,24 @@ +/** + * 451. Sort Characters By Frequency + * https://leetcode.com/problems/sort-characters-by-frequency/ + * Difficulty: Medium + * + * Given a string, sort it in decreasing order + * based on the frequency of characters. + */ + +/** + * @param {string} s + * @return {string} + */ +var frequencySort = function(s) { + const map = new Map(); + s.split('').forEach(char => { + map.set(char, map.has(char) ? map.get(char) + 1 : 1); + }); + + return [...map] + .sort((a, b) => b[1] - a[1]) + .map(entry => entry[0].repeat(entry[1])) + .join(''); +}; From ac8b4e56111e14bc044877b8915cb2f3ee57f0c2 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 11 Jan 2020 19:55:03 -0500 Subject: [PATCH 020/919] Add solution #739 --- 0739-daily-temperatures.js | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 0739-daily-temperatures.js diff --git a/0739-daily-temperatures.js b/0739-daily-temperatures.js new file mode 100644 index 00000000..1e73f855 --- /dev/null +++ b/0739-daily-temperatures.js @@ -0,0 +1,36 @@ +/** + * 739. Daily Temperatures + * https://leetcode.com/problems/daily-temperatures/ + * Difficulty: Medium + * + * Given a list of daily temperatures T, return a list such that, for + * each day in the input, tells you how many days you would have to + * wait until a warmer temperature. If there is no future day for + * which this is possible, put 0 instead. + * + * For example, given the list of temperatures + * T = [73, 74, 75, 71, 69, 72, 76, 73], your output + * should be [1, 1, 4, 2, 1, 1, 0, 0]. + * + * Note: The length of temperatures will be in the range [1, 30000]. + * Each temperature will be an integer in the range [30, 100]. + */ + +/** + * @param {number[]} T + * @return {number[]} + */ +var dailyTemperatures = function(T) { + const result = new Array(T.length).fill(0); + const stack = []; + + for (let i = 0; i < T.length; i++) { + while (stack.length && T[stack[stack.length - 1]] < T[i]) { + const topIndex = stack.pop(); + result[topIndex] = i - topIndex; + } + stack.push(i); + } + + return result; +}; From 39ead0bb5f5fb4b6a9a2d660c2f5259a98883201 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 11 Jan 2020 21:21:34 -0500 Subject: [PATCH 021/919] Add solution #1304 --- 1304-find-n-unique-integers-sum-up-to-zero.js | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 1304-find-n-unique-integers-sum-up-to-zero.js diff --git a/1304-find-n-unique-integers-sum-up-to-zero.js b/1304-find-n-unique-integers-sum-up-to-zero.js new file mode 100644 index 00000000..f019e9ae --- /dev/null +++ b/1304-find-n-unique-integers-sum-up-to-zero.js @@ -0,0 +1,20 @@ +/** + * 1304. Find N Unique Integers Sum up to Zero + * https://leetcode.com/problems/find-n-unique-integers-sum-up-to-zero/ + * Difficulty: Easy + * + * Given an integer n, return any array containing + * n unique integers such that they add up to 0. + */ + +/** + * @param {number} n + * @return {number[]} + */ +var sumZero = function(n) { + const result = n % 2 !== 0 ? [0] : []; + while (result.length < n) { + result.push(result.length + 1, (result.length + 1) * -1); + } + return result; +}; From df4dd7f18394757c6f1cc7bbc42f2bbf4cc17490 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 11 Jan 2020 21:26:12 -0500 Subject: [PATCH 022/919] Add solution #989 --- ...rrayform-of-integer.js => 0989-add-to-array-form-of-integer.js | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename 0989-add-to-arrayform-of-integer.js => 0989-add-to-array-form-of-integer.js (100%) diff --git a/0989-add-to-arrayform-of-integer.js b/0989-add-to-array-form-of-integer.js similarity index 100% rename from 0989-add-to-arrayform-of-integer.js rename to 0989-add-to-array-form-of-integer.js From 7cf07777e32d913a5f26a173fc467ab7befdfcf6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 12 Jan 2020 19:11:52 -0500 Subject: [PATCH 023/919] Add solution #1317 --- ...eger-to-the-sum-of-two-no-zero-integers.js | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 1317-convert-integer-to-the-sum-of-two-no-zero-integers.js diff --git a/1317-convert-integer-to-the-sum-of-two-no-zero-integers.js b/1317-convert-integer-to-the-sum-of-two-no-zero-integers.js new file mode 100644 index 00000000..dbdfd608 --- /dev/null +++ b/1317-convert-integer-to-the-sum-of-two-no-zero-integers.js @@ -0,0 +1,29 @@ +/** + * 1317. Convert Integer to the Sum of Two No-Zero Integers + * https://leetcode.com/problems/convert-integer-to-the-sum-of-two-no-zero-integers/ + * Difficulty: Easy + * + * Given an integer n. No-Zero integer is a positive integer which + * doesn't contain any 0 in its decimal representation. + * + * Return a list of two integers [A, B] where: + * + * - A and B are No-Zero integers. + * - A + B = n + * + * It's guarateed that there is at least one valid solution. + * If there are many valid solutions you can return any of them. + */ + +/** + * @param {number} n + * @return {number[]} + */ +var getNoZeroIntegers = function(n) { + const hasNoZero = n => String(n).indexOf('0') === -1; + for (let i = n; i; --i) { + if (hasNoZero(i) && hasNoZero(n - i)) { + return [i, n - i]; + } + } +}; From de8f5720663fc39482b53a133e67ef54b139c15c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 12 Jan 2020 23:05:32 -0500 Subject: [PATCH 024/919] Add solution #226 --- 0226-invert-binary-tree.js | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 0226-invert-binary-tree.js diff --git a/0226-invert-binary-tree.js b/0226-invert-binary-tree.js new file mode 100644 index 00000000..8ca433ef --- /dev/null +++ b/0226-invert-binary-tree.js @@ -0,0 +1,23 @@ +/** + * 226. Invert Binary Tree + * https://leetcode.com/problems/invert-binary-tree/ + * Difficulty: Easy + * + * Invert a binary tree. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ +/** + * @param {TreeNode} node + * @return {TreeNode} + */ +var invertTree = function(node) { + if (node) [node.left, node.right] = [invertTree(node.right), invertTree(node.left)]; + return node; +}; From 7fa1871deafaa2bf63d47edf700b109e71a9ecee Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 12 Jan 2020 23:20:54 -0500 Subject: [PATCH 025/919] Add solution #1318 --- ...minimum-flips-to-make-a-or-b-equal-to-c.js | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 1318-minimum-flips-to-make-a-or-b-equal-to-c.js diff --git a/1318-minimum-flips-to-make-a-or-b-equal-to-c.js b/1318-minimum-flips-to-make-a-or-b-equal-to-c.js new file mode 100644 index 00000000..5b48e885 --- /dev/null +++ b/1318-minimum-flips-to-make-a-or-b-equal-to-c.js @@ -0,0 +1,31 @@ +/** + * 1318. Minimum Flips to Make a OR b Equal to c + * https://leetcode.com/problems/minimum-flips-to-make-a-or-b-equal-to-c/ + * Difficulty: Medium + * + * Given 3 positives numbers a, b and c. + * Return the minimum flips required in some bits of a and b + * to make ( a OR b == c ). (bitwise OR operation). + * + * Flip operation consists of change any single bit 1 to 0 + * or change the bit 0 to 1 in their binary representation. + */ + +/** + * @param {number} a + * @param {number} b + * @param {number} c + * @return {number} + */ +var minFlips = function(a, b, c, flips = 0) { + [a, b, c] = [a, b, c].map(x => x.toString(2).padStart(32, 0)); + + for (let i = 0; i < c.length; i++) { + if ((+a[i] | +b[i]) !== +c[i]) { + if (((+a[i] ^ 1) | +b[i]) === +c[i] || (+a[i] | (+b[i] ^ 1)) === +c[i]) flips++; + else if (((+a[i] ^ 1) | (+b[i] ^ 1)) === +c[i]) flips += 2; + } + } + + return flips; +}; From 18ebfdd38255dd52e0dfa175e68e5b7e263021d1 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 13 Jan 2020 22:41:36 -0500 Subject: [PATCH 026/919] Add solution #617 --- 0617-merge-two-binary-trees.js | 38 ++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 0617-merge-two-binary-trees.js diff --git a/0617-merge-two-binary-trees.js b/0617-merge-two-binary-trees.js new file mode 100644 index 00000000..2e518f7b --- /dev/null +++ b/0617-merge-two-binary-trees.js @@ -0,0 +1,38 @@ +/** + * 617. Merge Two Binary Trees + * https://leetcode.com/problems/merge-two-binary-trees/ + * Difficulty: Easy + * + * Given two binary trees and imagine that when you put one + * of them to cover the other, some nodes of the two trees + * are overlapped while the others are not. + * + * You need to merge them into a new binary tree. + * The merge rule is that if two nodes overlap, then sum + * node values up as the new value of the merged node. + * Otherwise, the NOT null node will be used as the + * node of new tree. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ +/** + * @param {TreeNode} t1 + * @param {TreeNode} t2 + * @return {TreeNode} + */ +var mergeTrees = function(t1, t2) { + if (!t1) return t2; + if (!t2) return t1; + + t1.val += t2.val; + t1.left = mergeTrees(t1.left, t2.left); + t1.right = mergeTrees(t1.right, t2.right); + + return t1; +}; From b31597915aa2436162a6fbf3ff0e1f9ee08ab732 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 13 Jan 2020 23:00:06 -0500 Subject: [PATCH 027/919] Add solution #1207 --- 1207-unique-number-of-occurrences.js | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 1207-unique-number-of-occurrences.js diff --git a/1207-unique-number-of-occurrences.js b/1207-unique-number-of-occurrences.js new file mode 100644 index 00000000..35b8cacf --- /dev/null +++ b/1207-unique-number-of-occurrences.js @@ -0,0 +1,21 @@ +/** + * 1207. Unique Number of Occurrences + * https://leetcode.com/problems/unique-number-of-occurrences/ + * Difficulty: Easy + * + * Given an array of integers arr, write a + * function that returns true if and only + * if the number of occurrences of each + * value in the array is unique. + */ + +/** + * @param {number[]} numbers + * @return {boolean} + */ +var uniqueOccurrences = function(numbers) { + const map = new Map(); + numbers.forEach(n => map.set(n, map.has(n) ? map.get(n) + 1 : 1)); + const occurrences = Array.from(map.values()); + return new Set(occurrences).size === occurrences.length +}; From b1f2bd1789348f177a3db2b9fc9f0dc6b57aa7ff Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 13 Jan 2020 23:59:22 -0500 Subject: [PATCH 028/919] Add solution #804 --- 0804-unique-morse-code-words.js | 39 +++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 0804-unique-morse-code-words.js diff --git a/0804-unique-morse-code-words.js b/0804-unique-morse-code-words.js new file mode 100644 index 00000000..40a0e44d --- /dev/null +++ b/0804-unique-morse-code-words.js @@ -0,0 +1,39 @@ +/** + * 804. Unique Morse Code Words + * https://leetcode.com/problems/unique-morse-code-words/ + * Difficulty: Easy + * + * 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: + * + * [".-","-...","-.-.","-..",".","..-.","--.","....","..", + * ".---","-.-",".-..","--","-.","---",".--.","--.-",".-.", + * "...","-","..-","...-",".--","-..-","-.--","--.."] + * + * Now, given a list of words, each word can be written as a + * concatenation of the Morse code of each letter. + * For example, "cba" can be written as "-.-..--...", + * (which is the concatenation "-.-." + "-..." + ".-"). + * We'll call such a concatenation, the transformation of a word. + * + * Return the number of different transformations + * among all words we have. + */ + +/** + * @param {string[]} words + * @return {number} + */ +var uniqueMorseRepresentations = function(words) { + const codes = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---", + "-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-", + "..-","...-",".--","-..-","-.--","--.."]; + const map = new Map(codes.map((v, i) => [String.fromCharCode(97 + i), v])); + const transformed = words.map(word => word.split('').map(c => map.get(c)).join('')); + return new Set(transformed).size; +}; From 6dcc72c29ff40d9d187990448b7fddddf82cf629 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 14 Jan 2020 20:53:23 -0500 Subject: [PATCH 029/919] Add solution #36 --- 0036-valid-sudoku.js | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 0036-valid-sudoku.js diff --git a/0036-valid-sudoku.js b/0036-valid-sudoku.js new file mode 100644 index 00000000..bb000b2e --- /dev/null +++ b/0036-valid-sudoku.js @@ -0,0 +1,38 @@ +/** + * 36. Valid Sudoku + * https://leetcode.com/problems/valid-sudoku/ + * Difficulty: Medium + * + * Determine if a 9x9 Sudoku board is valid. + * Only the filled cells need to be validated according to the following rules: + * + * - Each row must contain the digits 1-9 without repetition. + * - Each column must contain the digits 1-9 without repetition. + * - Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without repetition. + * + * The Sudoku board could be partially filled, where empty cells are filled with the character '.'. + */ + +/** + * @param {character[][]} board + * @return {boolean} + */ +var isValidSudoku = function(board) { + const rows = new Array(9).fill().map(() => new Set()); + const columns = new Array(9).fill().map(() => new Set()); + const boxes = new Array(9).fill().map(() => new Set()); + + for (let i = 0; i < 9; i++) { + for (let j = 0; j < 9; j++) { + const value = board[i][j]; + const k = Math.floor(i / 3) * 3 + Math.floor(j / 3); + const options = [rows[i], columns[j], boxes[k]]; + + if (options.some(option => option.has(value))) return false; + if (value === '.') continue; + options.forEach(option => option.add(value)); + } + } + + return true; +}; From 7e45b25921bbd117b046e60c9421a418fa23dd38 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 14 Jan 2020 21:37:05 -0500 Subject: [PATCH 030/919] Add solution #1309 --- ...string-from-alphabet-to-integer-mapping.js | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 1309-decrypt-string-from-alphabet-to-integer-mapping.js diff --git a/1309-decrypt-string-from-alphabet-to-integer-mapping.js b/1309-decrypt-string-from-alphabet-to-integer-mapping.js new file mode 100644 index 00000000..153dd6ae --- /dev/null +++ b/1309-decrypt-string-from-alphabet-to-integer-mapping.js @@ -0,0 +1,25 @@ +/** + * 1309. Decrypt String from Alphabet to Integer Mapping + * https://leetcode.com/problems/decrypt-string-from-alphabet-to-integer-mapping/ + * Difficulty: Easy + * + * Given a string s formed by digits ('0' - '9') and '#' . + * We want to map s to English lowercase characters as follows: + * + * - Characters ('a' to 'i') are represented by ('1' to '9') respectively. + * - Characters ('j' to 'z') are represented by ('10#' to '26#') respectively. + * + * Return the string formed after mapping. + * + * It's guaranteed that a unique mapping will always exist. + */ + +/** + * @param {string} s + * @return {string} + */ +var freqAlphabets = function(s) { + return s.replace(/\d{2}#|\d/g, match => { + return String.fromCharCode('a'.charCodeAt() + parseInt(match, 10) - 1); + }); +}; From c621f3e7029be92e1064ceb72652aed20456ee82 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 14 Jan 2020 21:48:19 -0500 Subject: [PATCH 031/919] Add solution #819 --- 0819-most-common-word.js | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 0819-most-common-word.js diff --git a/0819-most-common-word.js b/0819-most-common-word.js new file mode 100644 index 00000000..44d2db32 --- /dev/null +++ b/0819-most-common-word.js @@ -0,0 +1,27 @@ +/** + * 819. Most Common Word + * https://leetcode.com/problems/most-common-word/ + * Difficulty: Easy + * + * Given a paragraph and a list of banned words, return the most frequent word that + * is not in the list of banned words. It is guaranteed there is at least one word + * that isn't banned, and that the answer is unique. + * + * Words in the list of banned words are given in lowercase, and free of punctuation. + * Words in the paragraph are not case sensitive. The answer is in lowercase. + */ + +/** + * @param {string} paragraph + * @param {string[]} banned + * @return {string} + */ +var mostCommonWord = function(paragraph, banned) { + const occurrences = new Map(); + paragraph.toLowerCase().replace(/[^\w\s]/g, ' ').split(/\s+/).forEach(word => { + if (!banned.includes(word)) { + occurrences.set(word, occurrences.has(word) ? occurrences.get(word) + 1 : 1); + } + }); + return Array.from(occurrences).sort((a, b) => b[1] - a[1])[0][0]; +}; From 47a5a3f10ff143d96bfe77e6c916e6cccaab2cfd Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 14 Jan 2020 21:54:37 -0500 Subject: [PATCH 032/919] Add solution #151 --- 0151-reverse-words-in-a-string.js | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 0151-reverse-words-in-a-string.js diff --git a/0151-reverse-words-in-a-string.js b/0151-reverse-words-in-a-string.js new file mode 100644 index 00000000..0b25efa6 --- /dev/null +++ b/0151-reverse-words-in-a-string.js @@ -0,0 +1,15 @@ +/** + * 151. Reverse Words in a String + * https://leetcode.com/problems/reverse-words-in-a-string/ + * Difficulty: Medium + * + * Given an input string, reverse the string word by word. + */ + +/** + * @param {string} s + * @return {string} + */ +var reverseWords = function(s) { + return s.trim().replace(/\s+/g, ' ').split(/\s/).reverse().join(' '); +}; From 770201c1d700045ed7757361fd5d56082a0abe5b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 15 Jan 2020 21:40:27 -0500 Subject: [PATCH 033/919] Add solution #1297 --- ...um-number-of-occurrences-of-a-substring.js | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 1297-maximum-number-of-occurrences-of-a-substring.js diff --git a/1297-maximum-number-of-occurrences-of-a-substring.js b/1297-maximum-number-of-occurrences-of-a-substring.js new file mode 100644 index 00000000..0d4d06fb --- /dev/null +++ b/1297-maximum-number-of-occurrences-of-a-substring.js @@ -0,0 +1,32 @@ +/** + * 1297. Maximum Number of Occurrences of a Substring + * https://leetcode.com/problems/maximum-number-of-occurrences-of-a-substring/ + * Difficulty: Medium + * + * Given a string s, return the maximum number of ocurrences of + * any substring under the following rules: + * + * - The number of unique characters in the substring must be less + * than or equal to maxLetters. + * - The substring size must be between minSize and maxSize inclusive. + */ + +/** + * @param {string} s + * @param {number} maxLetters + * @param {number} minSize + * @param {number} maxSize + * @return {number} + */ +var maxFreq = function(s, maxLetters, minSize, maxSize) { + const occurrences = new Map(); + + for (let i = 0; i <= s.length - minSize; i++) { + const string = s.substr(i, minSize); + if (new Set(string.split('')).size <= maxLetters) { + occurrences.set(string, occurrences.has(string) ? occurrences.get(string) + 1 : 1); + } + } + + return (Array.from(occurrences).sort((a, b) => b[1] - a[1])[0] || [])[1] || 0; +}; From 9deeb377c0afcb4e193436989757096ecb4e644a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 15 Jan 2020 23:23:54 -0500 Subject: [PATCH 034/919] Add solution #1189 --- 1189-maximum-number-of-balloons.js | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 1189-maximum-number-of-balloons.js diff --git a/1189-maximum-number-of-balloons.js b/1189-maximum-number-of-balloons.js new file mode 100644 index 00000000..8aea11b4 --- /dev/null +++ b/1189-maximum-number-of-balloons.js @@ -0,0 +1,25 @@ +/** + * 1189. Maximum Number of Balloons + * https://leetcode.com/problems/maximum-number-of-balloons/ + * Difficulty: Easy + * + * Given a string text, you want to use the characters of text + * to form as many instances of the word "balloon" as possible. + * + * You can use each character in text at most once. Return the + * maximum number of instances that can be formed. + */ + +/** + * @param {string} text + * @return {number} + */ +var maxNumberOfBalloons = function(text, word = 'balloon', i = 0, count = 0) { + const map = text.split('').reduce((o, k) => ({...o, [k]: o[k] ? ++o[k] : 1}), {}); + while (true) { + const char = word[i++ % word.length]; + if (!map[char] || map[char]-- === 0) break; + if (i % word.length === 0) count++; + } + return count; +}; From 06eef3c3b82679d909d57b146d82a0667035f0bd Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 15 Jan 2020 23:39:05 -0500 Subject: [PATCH 035/919] Add solution #1108 --- 1108-defanging-an-ip-address.js | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 1108-defanging-an-ip-address.js diff --git a/1108-defanging-an-ip-address.js b/1108-defanging-an-ip-address.js new file mode 100644 index 00000000..5d871e53 --- /dev/null +++ b/1108-defanging-an-ip-address.js @@ -0,0 +1,27 @@ +/** + * 1108. Defanging an IP Address + * https://leetcode.com/problems/defanging-an-ip-address/ + * Difficulty: Easy + * + * Given a valid (IPv4) IP address, return a defanged version of that IP address. + * + * A defanged IP address replaces every period "." with "[.]". + */ + +/** + * @param {string} address + * @return {string} + */ +var defangIPaddr = function(address) { + return address.replace(/\./g, '[.]'); +}; + +// or... + +/** + * @param {string} address + * @return {string} + */ +var defangIPaddr = function(address) { + return address.split('.').join('[.]'); +}; From e1403cefdd31379b6998aab5821d5f911b98117f Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 16 Jan 2020 00:09:08 -0500 Subject: [PATCH 036/919] Add solution #791 --- 0791-custom-sort-string.js | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 0791-custom-sort-string.js diff --git a/0791-custom-sort-string.js b/0791-custom-sort-string.js new file mode 100644 index 00000000..afb64d09 --- /dev/null +++ b/0791-custom-sort-string.js @@ -0,0 +1,26 @@ +/** + * 791. Custom Sort String + * https://leetcode.com/problems/custom-sort-string/ + * Difficulty: Medium + * + * S and T are strings composed of lowercase letters. In S, + * no letter occurs more than once. + * + * S was sorted in some custom order previously. We want to + * permute the characters of T so that they match the order + * that S was sorted. More specifically, if x occurs before + * y in S, then x should occur before y in the returned string. + * + * Return any permutation of T (as a string) that satisfies + * this property. + */ + +/** + * @param {string} S + * @param {string} T + * @return {string} + */ +var customSortString = function(S, T) { + const order = S.split('').reduce((o, k, i) => ({...o, [k]: i}), {}); + return T.split('').sort((a, b) => (order[a] || 0) - (order[b] || 0)).join(''); +}; From ea8c823a966e7739101f207f865c6a6aff048712 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 17 Jan 2020 00:46:42 -0500 Subject: [PATCH 037/919] Add solution #606 --- 0606-construct-string-from-binary-tree.js | 41 +++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 0606-construct-string-from-binary-tree.js diff --git a/0606-construct-string-from-binary-tree.js b/0606-construct-string-from-binary-tree.js new file mode 100644 index 00000000..c08594ad --- /dev/null +++ b/0606-construct-string-from-binary-tree.js @@ -0,0 +1,41 @@ +/** + * 606. Construct String from Binary Tree + * https://leetcode.com/problems/construct-string-from-binary-tree/ + * Difficulty: Easy + * + * You need to construct a string consists of parenthesis and integers + * from a binary tree with the preorder traversing way. + * + * The null node needs to be represented by empty parenthesis pair "()". + * And you need to omit all the empty parenthesis pairs that don't + * affect the one-to-one mapping relationship between the string + * and the original binary tree. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ +/** + * @param {TreeNode} t + * @return {string} + */ +var tree2str = function(t) { + return !t ? '' : `${t.val}(${tree2str(t.left)})(${tree2str(t.right)})`.replace(/(\(\)){2}|\(\)(?=$|\))/g, ''); +}; + + +// alternative, longer but faster version: +/** + * @param {TreeNode} t + * @return {string} + */ +var tree2str = function(t) { + let str = t ? `${t.val}` : ''; + if (t && t.right) str += `(${tree2str(t.left)})(${tree2str(t.right)})`; + else if (t && t.left) str += `(${tree2str(t.left)})`; + return str; +}; From aaaf3ee769f57b7681e157e2a496bbcf07d0f45e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 17 Jan 2020 23:12:06 -0500 Subject: [PATCH 038/919] Add solution #263 --- 0263-ugly-number.js | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 0263-ugly-number.js diff --git a/0263-ugly-number.js b/0263-ugly-number.js new file mode 100644 index 00000000..3fff6eee --- /dev/null +++ b/0263-ugly-number.js @@ -0,0 +1,21 @@ +/** + * 263. Ugly Number + * https://leetcode.com/problems/ugly-number/ + * Difficulty: Easy + * + * Write a program to check whether a given number is an ugly number. + * + * Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. + */ + +/** + * @param {number} num + * @return {boolean} + */ +var isUgly = function(num) { + if (num < 1) return false; + while (num % 5 === 0) num /= 5; + while (num % 3 === 0) num /= 3; + while (num % 2 === 0) num /= 2; + return num === 1; +}; From 9ea67eaed235d18cb164f5ac96c6b638ad7b774a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 17 Jan 2020 23:14:48 -0500 Subject: [PATCH 039/919] Add solution #1037 --- 1037-valid-boomerang.js | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 1037-valid-boomerang.js diff --git a/1037-valid-boomerang.js b/1037-valid-boomerang.js new file mode 100644 index 00000000..a50f5d18 --- /dev/null +++ b/1037-valid-boomerang.js @@ -0,0 +1,18 @@ +/** + * 1037. Valid Boomerang + * https://leetcode.com/problems/valid-boomerang/ + * Difficulty: Easy + * + * A boomerang is a set of 3 points that are all distinct and not in a straight line. + * + * Given a list of three points in the plane, return whether these points are a boomerang. + */ + +/** + * @param {number[][]} points + * @return {boolean} + */ +var isBoomerang = function(points) { + return (points[0][1] - points[1][1]) * (points[1][0] - points[2][0]) + !== (points[0][0] - points[1][0]) * (points[1][1] - points[2][1]); +}; From 8d27db1436743e320642fa77ac81a5d84906e622 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 18 Jan 2020 13:00:45 -0500 Subject: [PATCH 040/919] Add solution #264 --- 0264-ugly-number-ii.js | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 0264-ugly-number-ii.js diff --git a/0264-ugly-number-ii.js b/0264-ugly-number-ii.js new file mode 100644 index 00000000..f9b3780d --- /dev/null +++ b/0264-ugly-number-ii.js @@ -0,0 +1,24 @@ +/** + * 264. Ugly Number II + * https://leetcode.com/problems/ugly-number-ii/ + * Difficulty: Medium + * + * Write a program to find the n-th ugly number. + * + * Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. + */ + +/** + * @param {number} n + * @return {number} + */ +var nthUglyNumber = function(n, factors = [2, 3, 5], offsets = [0, 0, 0]) { + const numbers = [1]; + while (numbers.length < n) { + const candidates = factors.map((v, i) => numbers[offsets[i]] * v); + const target = Math.min(...candidates); + candidates.forEach((c, i) => target === c ? offsets[i]++ : null); + numbers.push(target) + } + return numbers[n - 1]; +}; From e90771bed09134c4ecea6eccefd1227f08823d74 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 19 Jan 2020 22:33:04 -0500 Subject: [PATCH 041/919] Add solution #890 --- 0890-find-and-replace-pattern.js | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 0890-find-and-replace-pattern.js diff --git a/0890-find-and-replace-pattern.js b/0890-find-and-replace-pattern.js new file mode 100644 index 00000000..cf385ebb --- /dev/null +++ b/0890-find-and-replace-pattern.js @@ -0,0 +1,27 @@ +/** + * 890. Find and Replace Pattern + * https://leetcode.com/problems/find-and-replace-pattern/ + * Difficulty: Medium + * + * You have a list of words and a pattern, and you want to know which words in words matches the pattern. + * + * 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.) + * + * Return a list of the words in words that match the given pattern. + * + * You may return the answer in any order. + */ + +/** + * @param {string[]} words + * @param {string} pattern + * @return {string[]} + */ +var findAndReplacePattern = function(words, pattern) { + const map = (p, o = {}, count = 0) => p.split('').map(c => o[c] = o[c] || String(count++)).join(''); + return words.filter(word => map(word) === map(pattern)); +}; From 46af9f0f0d76062da05ee958984a5e3dfd20b02f Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 19 Jan 2020 23:03:40 -0500 Subject: [PATCH 042/919] Add solution #1313 --- 1313-decompress-run-length-encoded-list.js | 23 ++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 1313-decompress-run-length-encoded-list.js diff --git a/1313-decompress-run-length-encoded-list.js b/1313-decompress-run-length-encoded-list.js new file mode 100644 index 00000000..b33c219c --- /dev/null +++ b/1313-decompress-run-length-encoded-list.js @@ -0,0 +1,23 @@ +/** + * 1313. Decompress Run-Length Encoded List + * https://leetcode.com/problems/decompress-run-length-encoded-list/ + * Difficulty: Easy + * + * We are given a list nums of integers representing a list compressed with run-length encoding. + * + * Consider each adjacent pair of elements [a, b] = [nums[2*i], nums[2*i+1]] (with i >= 0). + * For each such pair, there are a elements with value b in the decompressed list. + * + * Return the decompressed list. + */ + +/** + * @param {number[]} nums + * @return {number[]} + */ +var decompressRLElist = function(nums, result = []) { + for (let i = 0; i < nums.length; i += 2) { + result.push(...new Array(nums[i]).fill(nums[i + 1])); + } + return result; +}; From b635d1aebab0285f64a1fe8aa24d0fd5d0ebc2d7 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 19 Jan 2020 23:14:18 -0500 Subject: [PATCH 043/919] Add solution #263 --- 0263-ugly-number.js | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/0263-ugly-number.js b/0263-ugly-number.js index 3fff6eee..7666c7bf 100644 --- a/0263-ugly-number.js +++ b/0263-ugly-number.js @@ -13,9 +13,8 @@ * @return {boolean} */ var isUgly = function(num) { - if (num < 1) return false; - while (num % 5 === 0) num /= 5; - while (num % 3 === 0) num /= 3; - while (num % 2 === 0) num /= 2; + for (let i of [2, 3, 5]) { + while (num && num % i === 0) num /= i; + } return num === 1; }; From 04ba0c6d15c2fc81a7846a0b6793600f5b740df0 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 20 Jan 2020 00:35:49 -0500 Subject: [PATCH 044/919] Add solution #916 --- 0916-word-subsets.js | 30 +++++++++++++++++++++++++++++ README.md | 45 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 0916-word-subsets.js diff --git a/0916-word-subsets.js b/0916-word-subsets.js new file mode 100644 index 00000000..0456e435 --- /dev/null +++ b/0916-word-subsets.js @@ -0,0 +1,30 @@ +/** + * 916. Word Subsets + * https://leetcode.com/problems/word-subsets/ + * Difficulty: Medium + * + * We are given two arrays A and B of words. Each word is a string of lowercase letters. + * + * Now, say that word b is a subset of word a if every letter in b occurs in a, including + * multiplicity. For example, "wrr" is a subset of "warrior", but is not a subset of "world". + * + * Now say a word a from A is universal if for every b in B, b is a subset of a. + * + * Return a list of all universal words in A. You can return the words in any order. + */ + +/** + * @param {string[]} A + * @param {string[]} B + * @return {string[]} + */ +var wordSubsets = function(A, B) { + const count = (string, char) => string.split(char).length - 1; + const subset = Array.from(B.reduce((map, b) => { + b.split('').forEach(char => { + map.set(char, (map.get(char) || 0) > count(b, char) ? map.get(char) : count(b, char)); + }); + return map; + }, new Map())); + return A.filter(a => subset.every(match => count(a, match[0]) >= match[1])); +}; diff --git a/README.md b/README.md index d5dc0a35..93d8e6fd 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,51 @@ [https://leetcode.com/](https://leetcode.com/) +## Table of Contents: + +|#|Title|Difficulty| +|:---|:---|:---| +36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| +58|[Length of Last Word](./0058-length-of-last-word.js)|Easy| +151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| +226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy| +263|[Ugly Number](./0263-ugly-number.js)|Easy| +264|[Ugly Number II](./0264-ugly-number-ii.js)|Medium| +387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| +451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| +606|[Construct String from Binary Tree](./0606-construct-string-from-binary-tree.js)|Easy| +617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy| +739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium| +791|[Custom Sort String](./0791-custom-sort-string.js)|Medium| +804|[Unique Morse Code Words](./0804-unique-morse-code-words.js)|Easy| +819|[Most Common Word](./0819-most-common-word.js)|Easy| +890|[Find and Replace Pattern](./0890-find-and-replace-pattern.js)|Medium| +916|[Word Subsets](./0916-word-subsets.js)|Medium| +929|[Unique Email Addresses](./0929-unique-email-addresses.js)|Easy| +970|[Powerful Integers](./0970-powerful-integers.js)|Easy| +976|[Largest Perimeter Triangle](./0976-largest-perimeter-triangle.js)|Easy| +977|[Squares of a Sorted Array](./0977-squares-of-a-sorted-array.js)|Easy| +985|[Sum of Even Numbers After Queries](./0985-sum-of-even-numbers-after-queries.js)|Easy| +989|[Add to Array-Form of Integer](./0989-add-to-array-form-of-integer.js)|Easy| +1009|[Complement of Base 10 Integer](./1009-complement-of-base-10-integer.js)|Easy| +1037|[Valid Boomerang](./1037-valid-boomerang.js)|Easy| +1103|[Distribute Candies to People](./1103-distribute-candies-to-people.js)|Easy| +1108|[Defanging an IP Address](./1108-defanging-an-ip-address.js)|Easy| +1189|[Maximum Number of Balloons](./1189-maximum-number-of-balloons.js)|Easy| +1207|[Unique Number of Occurrences](./1207-unique-number-of-occurrences.js)|Easy| +1232|[Check If It Is a Straight Line](./1232-check-if-it-is-a-straight-line.js)|Easy| +1252|[Cells with Odd Values in a Matrix](./1252-cells-with-odd-values-in-a-matrix.js)|Easy| +1287|[Element Appearing More Than 25% In Sorted Array](./1287-element-appearing-more-than-25-in-sorted-array.js)|Easy| +1290|[Convert Binary Number in a Linked List to Integer](./1290-convert-binary-number-in-a-linked-list-to-integer.js)|Easy| +1291|[Sequential Digits](./1291-sequential-digits.js)|Medium| +1292|[Maximum Side Length of a Square with Sum Less than or Equal to Threshold](./1292-maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold.js)|Medium| +1297|[Maximum Number of Occurrences of a Substring](./1297-maximum-number-of-occurrences-of-a-substring.js)|Medium| +1304|[Find N Unique Integers Sum up to Zero](./1304-find-n-unique-integers-sum-up-to-zero.js)|Easy| +1309|[Decrypt String from Alphabet to Integer Mapping](./1309-decrypt-string-from-alphabet-to-integer-mapping.js)|Easy| +1313|[Decompress Run-Length Encoded List](./1313-decompress-run-length-encoded-list.js)|Easy| +1317|[Convert Integer to the Sum of Two No-Zero Integers](./1317-convert-integer-to-the-sum-of-two-no-zero-integers.js)|Easy| +1318|[Minimum Flips to Make a OR b Equal to c](./1318-minimum-flips-to-make-a-or-b-equal-to-c.js)|Medium| + ## License [MIT License](https://opensource.org/licenses/MIT) From 261b7e0598a51f9d2bc3f93a9b85ee87ccb8bd66 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 20 Jan 2020 14:00:26 -0500 Subject: [PATCH 045/919] Add solution #966 --- 0966-vowel-spellchecker.js | 44 ++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 45 insertions(+) create mode 100644 0966-vowel-spellchecker.js diff --git a/0966-vowel-spellchecker.js b/0966-vowel-spellchecker.js new file mode 100644 index 00000000..0979ed60 --- /dev/null +++ b/0966-vowel-spellchecker.js @@ -0,0 +1,44 @@ +/** + * 966. Vowel Spellchecker + * https://leetcode.com/problems/vowel-spellchecker/ + * Difficulty: Medium + * + * Given a wordlist, we want to implement a spellchecker that converts a query word into a correct word. + * For a given query word, the spell checker handles two categories of spelling mistakes: + * + * - Capitalization: If the query matches a word in the wordlist (case-insensitive), then the query word + * is returned with the same case as the case in the wordlist. + * Example: wordlist = ["yellow"], query = "YellOw": correct = "yellow" + * Example: wordlist = ["Yellow"], query = "yellow": correct = "Yellow" + * Example: wordlist = ["yellow"], query = "yellow": correct = "yellow" + * - Vowel Errors: If after replacing the vowels ('a', 'e', 'i', 'o', 'u') of the query word with any vowel + * individually, it matches a word in the wordlist (case-insensitive), then the query word is returned + * with the same case as the match in the wordlist. + * Example: wordlist = ["YellOw"], query = "yollow": correct = "YellOw" + * Example: wordlist = ["YellOw"], query = "yeellow": correct = "" (no match) + * Example: wordlist = ["YellOw"], query = "yllw": correct = "" (no match) + * + * In addition, the spell checker operates under the following precedence rules: + * - When the query exactly matches a word in the wordlist (case-sensitive), you should return the same word back. + * - When the query matches a word up to capitlization, you should return the first such match in the wordlist. + * - When the query matches a word up to vowel errors, you should return the first such match in the wordlist. + * - If the query has no matches in the wordlist, you should return the empty string. + * + * Given some queries, return a list of words answer, where answer[i] is the correct word for query = queries[i]. + */ + +/** + * @param {string[]} words + * @param {string[]} queries + * @return {string[]} + */ +var spellchecker = function(words, queries) { + const set = new Set(words); + const map = new Map(); + const format = s => s.toLowerCase().replace(/[aeiou]/g, '_'); + words.forEach(word => { + if (!map.has(word.toLowerCase())) map.set(word.toLowerCase(), word); + if (!map.has(format(word))) map.set(format(word), word); + }); + return queries.map(q => set.has(q) ? q : map.get(q.toLowerCase()) || map.get(format(q)) || ''); +}; diff --git a/README.md b/README.md index 93d8e6fd..f5729904 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ 890|[Find and Replace Pattern](./0890-find-and-replace-pattern.js)|Medium| 916|[Word Subsets](./0916-word-subsets.js)|Medium| 929|[Unique Email Addresses](./0929-unique-email-addresses.js)|Easy| +966|[Vowel Spellchecker](./0966-vowel-spellchecker.js)|Medium| 970|[Powerful Integers](./0970-powerful-integers.js)|Easy| 976|[Largest Perimeter Triangle](./0976-largest-perimeter-triangle.js)|Easy| 977|[Squares of a Sorted Array](./0977-squares-of-a-sorted-array.js)|Easy| From 0c2d49e92e86bc673670c1f9d57604208d816df4 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 20 Jan 2020 14:18:14 -0500 Subject: [PATCH 046/919] Add solution #648 --- 0648-replace-words.js | 30 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 0648-replace-words.js diff --git a/0648-replace-words.js b/0648-replace-words.js new file mode 100644 index 00000000..14179342 --- /dev/null +++ b/0648-replace-words.js @@ -0,0 +1,30 @@ +/** + * 648. Replace Words + * https://leetcode.com/problems/replace-words/ + * Difficulty: Medium + * + * In English, we have a concept called root, which can be followed by some other words + * to form another longer word - let's call this word successor. For example, the root + * an, followed by other, which can form another word another. + * + * Now, given a dictionary consisting of many roots and a sentence. You need to replace + * all the successor in the sentence with the root forming it. If a successor has many + * roots can form it, replace it with the root with the shortest length. + * + * You need to output the sentence after the replacement. + */ + +/** + * @param {string[]} dict + * @param {string} sentence + * @return {string} + */ +var replaceWords = function(dict, sentence) { + const set = new Set(dict); + return sentence.split(/\s+/).map(word => { + for (let i = 1; i <= word.length; i++) { + if (set.has(word.slice(0, i))) return word.slice(0, i); + } + return word; + }).join(' '); +}; diff --git a/README.md b/README.md index f5729904..42f28b37 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ 451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| 606|[Construct String from Binary Tree](./0606-construct-string-from-binary-tree.js)|Easy| 617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy| +648|[Replace Words](./0648-replace-words.js)|Medium| 739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium| 791|[Custom Sort String](./0791-custom-sort-string.js)|Medium| 804|[Unique Morse Code Words](./0804-unique-morse-code-words.js)|Easy| From 94f5f3e1f4ace148caa190118d9f7ec99eea55e7 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 20 Jan 2020 14:40:44 -0500 Subject: [PATCH 047/919] Add solution #459 --- 0459-repeated-substring-pattern.js | 18 ++++++++++++++++++ README.md | 1 + 2 files changed, 19 insertions(+) create mode 100644 0459-repeated-substring-pattern.js diff --git a/0459-repeated-substring-pattern.js b/0459-repeated-substring-pattern.js new file mode 100644 index 00000000..07598eb0 --- /dev/null +++ b/0459-repeated-substring-pattern.js @@ -0,0 +1,18 @@ +/** + * 459. Repeated Substring Pattern + * https://leetcode.com/problems/repeated-substring-pattern/ + * Difficulty: Easy + * + * Given a non-empty string check if it can be constructed by taking a + * substring of it and appending multiple copies of the substring + * together. You may assume the given string consists of lowercase + * English letters only and its length will not exceed 10000. + */ + +/** + * @param {string} s + * @return {boolean} + */ +var repeatedSubstringPattern = function(s) { + return (s + s).slice(1, s.length * 2 - 1).indexOf(s) !== -1; +}; diff --git a/README.md b/README.md index 42f28b37..578074f6 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,7 @@ 264|[Ugly Number II](./0264-ugly-number-ii.js)|Medium| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| 451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| +459|[Repeated Substring Pattern](./0459-repeated-substring-pattern.js)|Easy| 606|[Construct String from Binary Tree](./0606-construct-string-from-binary-tree.js)|Easy| 617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy| 648|[Replace Words](./0648-replace-words.js)|Medium| From e6178966b83847673d58841d4c4cdc17c08442cb Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 20 Jan 2020 15:44:12 -0500 Subject: [PATCH 048/919] Add solution #686 --- 0686-repeated-string-match.js | 25 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 26 insertions(+) create mode 100644 0686-repeated-string-match.js diff --git a/0686-repeated-string-match.js b/0686-repeated-string-match.js new file mode 100644 index 00000000..927a408f --- /dev/null +++ b/0686-repeated-string-match.js @@ -0,0 +1,25 @@ +/** + * 686. Repeated String Match + * https://leetcode.com/problems/repeated-string-match/ + * Difficulty: Easy + * + * Given two strings A and B, find the minimum number of times A has to be + * repeated such that B is a substring of it. If no such solution, return -1. + * + * For example, with A = "abcd" and B = "cdabcdab". + * + * Return 3, because by repeating A three times (“abcdabcdabcd”), B is a + * substring of it; and B is not a substring of A repeated two times ("abcdabcd"). + */ + +/** + * @param {string} A + * @param {string} B + * @return {number} + */ +var repeatedStringMatch = function(A, B) { + const length = Math.ceil(B.length / A.length); + if (A.repeat(length).includes(B)) return length; + if ((A.repeat(length) + A).includes(B)) return length + 1; + return -1; +}; diff --git a/README.md b/README.md index 578074f6..01df301e 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,7 @@ 606|[Construct String from Binary Tree](./0606-construct-string-from-binary-tree.js)|Easy| 617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy| 648|[Replace Words](./0648-replace-words.js)|Medium| +686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| 739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium| 791|[Custom Sort String](./0791-custom-sort-string.js)|Medium| 804|[Unique Morse Code Words](./0804-unique-morse-code-words.js)|Easy| From 62fbde463f59ec9a1ab00d08cdbc7089d21711dc Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 20 Jan 2020 22:27:45 -0500 Subject: [PATCH 049/919] Add solution #1324 --- 1324-print-words-vertically.js | 25 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 26 insertions(+) create mode 100644 1324-print-words-vertically.js diff --git a/1324-print-words-vertically.js b/1324-print-words-vertically.js new file mode 100644 index 00000000..4e29c973 --- /dev/null +++ b/1324-print-words-vertically.js @@ -0,0 +1,25 @@ +/** + * 1324. Print Words Vertically + * https://leetcode.com/problems/print-words-vertically/ + * Difficulty: Medium + * + * Given a string s. Return all the words vertically in the same + * order in which they appear in s. + * Words are returned as a list of strings, complete with spaces + * when is necessary. (Trailing spaces are not allowed). + * Each word would be put on only one column and that in one + * column there will be only one word. + */ + +/** + * @param {string} s + * @return {string[]} + */ +var printVertically = function(s) { + const result = []; + s.split(/\s+/).forEach((word, i) => word.split('').forEach((letter, j) => { + result[j] = result[j] || ''; + result[j] += letter.padStart(i - result[j].length + 1, ' '); + })); + return result; +}; diff --git a/README.md b/README.md index 01df301e..b4a2627b 100644 --- a/README.md +++ b/README.md @@ -50,6 +50,7 @@ 1313|[Decompress Run-Length Encoded List](./1313-decompress-run-length-encoded-list.js)|Easy| 1317|[Convert Integer to the Sum of Two No-Zero Integers](./1317-convert-integer-to-the-sum-of-two-no-zero-integers.js)|Easy| 1318|[Minimum Flips to Make a OR b Equal to c](./1318-minimum-flips-to-make-a-or-b-equal-to-c.js)|Medium| +1324|[Print Words Vertically](./1324-print-words-vertically.js)|Medium| ## License From a16f99cea0d9c9e40525d7343f6c0673960088de Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 21 Jan 2020 21:46:12 -0500 Subject: [PATCH 050/919] Add solution #722 --- 0722-remove-comments.js | 26 ++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 27 insertions(+) create mode 100644 0722-remove-comments.js diff --git a/0722-remove-comments.js b/0722-remove-comments.js new file mode 100644 index 00000000..069218e4 --- /dev/null +++ b/0722-remove-comments.js @@ -0,0 +1,26 @@ +/** + * 722. Remove Comments + * https://leetcode.com/problems/remove-comments/ + * Difficulty: Medium + * + * Given a C++ program, remove comments from it. The program source is an array where source[i] is the i-th + * line of the source code. This represents the result of splitting the original source code string by the + * newline character \n. + * In C++, there are two types of comments, line comments, and block comments. + * The string // denotes a line comment, which represents that it and rest of the characters to the right + * of it in the same line should be ignored. + * The string /* denotes a block comment, which represents that all characters until the next + * (non-overlapping) occurrence of should be ignored. + * It is guaranteed that every open block comment will eventually be closed, so /* outside of a line or block + * comment always starts a new comment. + * Finally, implicit newline characters can be deleted by block comments. + * After removing the comments from the source code, return the source code in the same format. + */ + +/** + * @param {string[]} source + * @return {string[]} + */ +var removeComments = function(source) { + return source.join('\n').replace(/\/\*.*?\*\/|\/\/[^\n]+/gs, '').split(/\n/).filter(Boolean); +}; diff --git a/README.md b/README.md index b4a2627b..ec8ca8d5 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,7 @@ 617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy| 648|[Replace Words](./0648-replace-words.js)|Medium| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| +722|[Remove Comments](./0722-remove-comments.js)|Medium| 739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium| 791|[Custom Sort String](./0791-custom-sort-string.js)|Medium| 804|[Unique Morse Code Words](./0804-unique-morse-code-words.js)|Easy| From 3167a9d9f8b2d1e99ef2187c90dfeb179a46cdfa Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 21 Jan 2020 22:47:36 -0500 Subject: [PATCH 051/919] Add solution #1249 --- ...inimum-remove-to-make-valid-parentheses.js | 40 +++++++++++++++++++ README.md | 1 + 2 files changed, 41 insertions(+) create mode 100644 1249-minimum-remove-to-make-valid-parentheses.js diff --git a/1249-minimum-remove-to-make-valid-parentheses.js b/1249-minimum-remove-to-make-valid-parentheses.js new file mode 100644 index 00000000..b2743c4e --- /dev/null +++ b/1249-minimum-remove-to-make-valid-parentheses.js @@ -0,0 +1,40 @@ +/** + * 1249. Minimum Remove to Make Valid Parentheses + * https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/ + * Difficulty: Medium + * + * Given a string s of '(' , ')' and lowercase English characters. + * + * Your task is to remove the minimum number of parentheses ( '(' or ')', + * in any positions ) so that the resulting parentheses string is valid + * and return any valid string. + * + * Formally, a parentheses string is valid if and only if: + * - It is the empty string, contains only lowercase characters, or + * - It can be written as AB (A concatenated with B), where A and B are valid strings, or + * - It can be written as (A), where A is a valid string. + */ + +/** + * @param {string} s + * @return {string} + */ +var minRemoveToMakeValid = function(s) { + const inputArray = s.split(''); + const stack = []; + + inputArray.forEach((letter, index) => { + if (letter === '(') { + stack.push(index); + } else if (letter === ')') { + if (stack.length) { + stack.pop(); + } else { + inputArray[index] = ''; + } + } + }); + + stack.forEach(index => inputArray[index] = ''); + return inputArray.join(''); +}; diff --git a/README.md b/README.md index ec8ca8d5..428808ae 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,7 @@ 1189|[Maximum Number of Balloons](./1189-maximum-number-of-balloons.js)|Easy| 1207|[Unique Number of Occurrences](./1207-unique-number-of-occurrences.js)|Easy| 1232|[Check If It Is a Straight Line](./1232-check-if-it-is-a-straight-line.js)|Easy| +1249|[Minimum Remove to Make Valid Parentheses](./1249-minimum-remove-to-make-valid-parentheses.js)|Medium| 1252|[Cells with Odd Values in a Matrix](./1252-cells-with-odd-values-in-a-matrix.js)|Easy| 1287|[Element Appearing More Than 25% In Sorted Array](./1287-element-appearing-more-than-25-in-sorted-array.js)|Easy| 1290|[Convert Binary Number in a Linked List to Integer](./1290-convert-binary-number-in-a-linked-list-to-integer.js)|Easy| From 9a6931d90b309756e01e7800dfce862590e64a7e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 21 Jan 2020 22:55:24 -0500 Subject: [PATCH 052/919] Add solution #1323 --- 1323-maximum-69-number.js | 18 ++++++++++++++++++ README.md | 1 + 2 files changed, 19 insertions(+) create mode 100644 1323-maximum-69-number.js diff --git a/1323-maximum-69-number.js b/1323-maximum-69-number.js new file mode 100644 index 00000000..a472a90e --- /dev/null +++ b/1323-maximum-69-number.js @@ -0,0 +1,18 @@ +/** + * 1323. Maximum 69 Number + * https://leetcode.com/problems/maximum-69-number/submissions/ + * Difficulty: Easy + * + * Given a positive integer num consisting only of digits 6 and 9. + * + * Return the maximum number you can get by changing at most + * one digit (6 becomes 9, and 9 becomes 6). + */ + +/** + * @param {number} num + * @return {number} + */ +var maximum69Number = function(num) { + return +String(num).replace(6, 9); +}; diff --git a/README.md b/README.md index 428808ae..aac75485 100644 --- a/README.md +++ b/README.md @@ -52,6 +52,7 @@ 1313|[Decompress Run-Length Encoded List](./1313-decompress-run-length-encoded-list.js)|Easy| 1317|[Convert Integer to the Sum of Two No-Zero Integers](./1317-convert-integer-to-the-sum-of-two-no-zero-integers.js)|Easy| 1318|[Minimum Flips to Make a OR b Equal to c](./1318-minimum-flips-to-make-a-or-b-equal-to-c.js)|Medium| +1323|[Maximum 69 Number](./1323-maximum-69-number.js)|Easy| 1324|[Print Words Vertically](./1324-print-words-vertically.js)|Medium| ## License From 1aaf413f5268ab4a804d14447d66b25101501115 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 21 Jan 2020 23:51:51 -0500 Subject: [PATCH 053/919] Add solution #4 --- 0004-median-of-two-sorted-arrays.js | 50 +++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 51 insertions(+) create mode 100644 0004-median-of-two-sorted-arrays.js diff --git a/0004-median-of-two-sorted-arrays.js b/0004-median-of-two-sorted-arrays.js new file mode 100644 index 00000000..ffc7d59d --- /dev/null +++ b/0004-median-of-two-sorted-arrays.js @@ -0,0 +1,50 @@ +/** + * 4. Median of Two Sorted Arrays + * https://leetcode.com/problems/median-of-two-sorted-arrays/ + * Difficulty: Hard + * + * There are two sorted arrays nums1 and nums2 of size m and n respectively. + * + * Find the median of the two sorted arrays. + * The overall run time complexity should be O(log (m+n)). + * + * You may assume nums1 and nums2 cannot be both empty. + */ + +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number} + */ +var findMedianSortedArrays = function(nums1, nums2) { + const total = nums1.length + nums2.length; + const limit = Math.floor(total / 2) + 1; + let i = 0, j = 0, prev, last + + while(i + j < limit) { + if (last !== undefined) { + prev = last; + } + if (nums1[i] < nums2[j] || j === nums2.length) { + last = nums1[i++]; + } else { + last = nums2[j++]; + } + } + + return total % 2 === 0 ? (prev + last) / 2 : last; +}; + +// shorter/readable alternative with higher time complexity: +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number} + */ +var findMedianSortedArrays = function(nums1, nums2) { + const sorted = [...nums1, ...nums2].sort((a, b) => a - b); + const index = Math.floor((sorted.length - 1) / 2); + return sorted.length % 2 === 0 + ? (sorted[index] + sorted[index + 1]) / 2 + : sorted[index]; +}; diff --git a/README.md b/README.md index aac75485..5f97d71a 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,7 @@ |#|Title|Difficulty| |:---|:---|:---| +4|[Median of Two Sorted Arrays](./0004-median-of-two-sorted-arrays.js)|Hard| 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| 58|[Length of Last Word](./0058-length-of-last-word.js)|Easy| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| From 559c21e630a1e65b0358fdac3bc86302660ca2ab Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 21 Jan 2020 23:54:30 -0500 Subject: [PATCH 054/919] Add MIT license --- LICENSE | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 LICENSE diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..779eb431 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Josh Crozier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file From 81438282b9dac8387901a847b8b2b03ab9a907ce Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 22 Jan 2020 19:58:16 -0500 Subject: [PATCH 055/919] Add solution #67 --- 0067-add-binary.js | 18 ++++++++++++++++++ README.md | 3 ++- 2 files changed, 20 insertions(+), 1 deletion(-) create mode 100644 0067-add-binary.js diff --git a/0067-add-binary.js b/0067-add-binary.js new file mode 100644 index 00000000..6e44f81c --- /dev/null +++ b/0067-add-binary.js @@ -0,0 +1,18 @@ +/** + * 67. Add Binary + * https://leetcode.com/problems/add-binary/ + * Difficulty: Easy + * + * Given two binary strings, return their sum (also a binary string). + * + * The input strings are both non-empty and contains only characters 1 or 0. + */ + +/** + * @param {string} a + * @param {string} b + * @return {string} + */ +var addBinary = function(a, b) { + return (BigInt('0b' + a) + BigInt('0b' + b)).toString(2); +}; diff --git a/README.md b/README.md index 5f97d71a..10378f71 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,7 @@ 4|[Median of Two Sorted Arrays](./0004-median-of-two-sorted-arrays.js)|Hard| 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| 58|[Length of Last Word](./0058-length-of-last-word.js)|Easy| +67|[Add Binary](./0067-add-binary.js)|Easy| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy| 263|[Ugly Number](./0263-ugly-number.js)|Easy| @@ -60,4 +61,4 @@ [MIT License](https://opensource.org/licenses/MIT) -Copyright (c) 2019 [Josh Crozier](https://joshcrozier.com) +Copyright (c) 2019-2020 [Josh Crozier](https://joshcrozier.com) From d1dc9977bce6859bb9d767e4789b1423465f0feb Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 22 Jan 2020 23:21:15 -0500 Subject: [PATCH 056/919] Add solution #43 --- 0043-multiply-strings.js | 40 ++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 41 insertions(+) create mode 100644 0043-multiply-strings.js diff --git a/0043-multiply-strings.js b/0043-multiply-strings.js new file mode 100644 index 00000000..62e3d7b7 --- /dev/null +++ b/0043-multiply-strings.js @@ -0,0 +1,40 @@ +/** + * 43. Multiply Strings + * https://leetcode.com/problems/multiply-strings/ + * Difficulty: Medium + * + * Given two non-negative integers num1 and num2 represented as strings, + * return the product of num1 and num2, also represented as a string. + * + * - The length of both num1 and num2 is < 110. + * - Both num1 and num2 contain only digits 0-9. + * - Both num1 and num2 do not contain any leading zero, except the number 0 itself. + * - You must not use any built-in BigInteger library or convert the inputs to integer directly. + */ + +/** + * @param {string} num1 + * @param {string} num2 + * @return {string} + */ +var multiply = function(num1, num2) { + const result = new Array(num1.length + num2.length).fill(0); + for (let i = num1.length - 1; i >= 0; i--) { + for (let j = num2.length - 1; j >= 0; j--) { + const sum = num1[i] * num2[j] + result[i + j + 1]; + result[i + j] += Math.floor(sum / 10); + result[i + j + 1] = sum % 10; + } + } + return result.join('').replace(/^0+(?!$)/, ''); +}; + +// one-liner alternative that breaks the rules: +/** + * @param {string} num1 + * @param {string} num2 + * @return {string} + */ +var multiply = function(num1, num2) { + return ((BigInt(num1) * BigInt(num2))).toString(); +}; diff --git a/README.md b/README.md index 10378f71..77446c83 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ |:---|:---|:---| 4|[Median of Two Sorted Arrays](./0004-median-of-two-sorted-arrays.js)|Hard| 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| +43|[Multiply Strings](./0043-multiply-strings.js)|Medium| 58|[Length of Last Word](./0058-length-of-last-word.js)|Easy| 67|[Add Binary](./0067-add-binary.js)|Easy| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| From 607826e79696d47ecf81dd0d03cb1f985f0bf786 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 22 Jan 2020 23:22:12 -0500 Subject: [PATCH 057/919] Add solution #4 --- 0004-median-of-two-sorted-arrays.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/0004-median-of-two-sorted-arrays.js b/0004-median-of-two-sorted-arrays.js index ffc7d59d..88a7613a 100644 --- a/0004-median-of-two-sorted-arrays.js +++ b/0004-median-of-two-sorted-arrays.js @@ -21,7 +21,7 @@ var findMedianSortedArrays = function(nums1, nums2) { const limit = Math.floor(total / 2) + 1; let i = 0, j = 0, prev, last - while(i + j < limit) { + while (i + j < limit) { if (last !== undefined) { prev = last; } From 34aa663cfec12b5c9941aa66f0cfc25ce8a63691 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 22 Jan 2020 23:42:43 -0500 Subject: [PATCH 058/919] Add solution #66 --- 0066-plus-one.js | 41 +++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 42 insertions(+) create mode 100644 0066-plus-one.js diff --git a/0066-plus-one.js b/0066-plus-one.js new file mode 100644 index 00000000..20987a33 --- /dev/null +++ b/0066-plus-one.js @@ -0,0 +1,41 @@ +/** + * 66. Plus One + * https://leetcode.com/problems/plus-one/ + * Difficulty: Easy + * + * Given a non-empty array of digits representing a non-negative integer, + * plus one to the integer. + * + * The digits are stored such that the most significant digit is at the + * head of the list, and each element in the array contain a single digit. + * + * You may assume the integer does not contain any leading zero, + * except the number 0 itself. + */ + +/** + * @param {number[]} digits + * @return {number[]} + */ +var plusOne = function(digits) { + let i = digits.length - 1; + digits[i] += 1; + while (digits[i] > 9) { + digits[i--] = 0; + if (digits[i]) { + digits[i] += 1; + } else { + digits.unshift(1); + } + } + return digits; +}; + +// alternative one-liner that breaks the rules: +/** + * @param {number[]} digits + * @return {number[]} + */ +var plusOne = function(digits) { + return String(BigInt(digits.join('')) + BigInt(1)).split(''); +}; diff --git a/README.md b/README.md index 77446c83..3eaafad6 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| 43|[Multiply Strings](./0043-multiply-strings.js)|Medium| 58|[Length of Last Word](./0058-length-of-last-word.js)|Easy| +66|[Plus One](./0066-plus-one.js)|Easy| 67|[Add Binary](./0067-add-binary.js)|Easy| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy| From 7359e0f65a67b6b6920b791263992dcd56674a63 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 22 Jan 2020 23:51:17 -0500 Subject: [PATCH 059/919] Add solution #824 --- 0824-goat-latin.js | 34 ++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 0824-goat-latin.js diff --git a/0824-goat-latin.js b/0824-goat-latin.js new file mode 100644 index 00000000..a49073ea --- /dev/null +++ b/0824-goat-latin.js @@ -0,0 +1,34 @@ +/** + * 824. Goat Latin + * https://leetcode.com/problems/goat-latin/ + * Difficulty: Easy + * + * A sentence S is given, composed 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 S to Goat Latin. + */ + +/** + * @param {string} S + * @return {string} + */ +var toGoatLatin = function(S) { + return S.split(' ').map((word, index) => { + return `${word.replace(/^([^aeiou])(.*)/ig, '$2$1')}ma${'a'.repeat(index + 1)}`; + }).join(' '); +}; diff --git a/README.md b/README.md index 3eaafad6..d7047c96 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,7 @@ 791|[Custom Sort String](./0791-custom-sort-string.js)|Medium| 804|[Unique Morse Code Words](./0804-unique-morse-code-words.js)|Easy| 819|[Most Common Word](./0819-most-common-word.js)|Easy| +824|[Goat Latin](./0824-goat-latin.js)|Easy| 890|[Find and Replace Pattern](./0890-find-and-replace-pattern.js)|Medium| 916|[Word Subsets](./0916-word-subsets.js)|Medium| 929|[Unique Email Addresses](./0929-unique-email-addresses.js)|Easy| From ddf325e0d1a377b60ff009b02c90f37defa6c4e7 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 23 Jan 2020 00:33:38 -0500 Subject: [PATCH 060/919] Add solution #831 --- 0831-masking-personal-information.js | 57 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 58 insertions(+) create mode 100644 0831-masking-personal-information.js diff --git a/0831-masking-personal-information.js b/0831-masking-personal-information.js new file mode 100644 index 00000000..4f3ca6f4 --- /dev/null +++ b/0831-masking-personal-information.js @@ -0,0 +1,57 @@ +/** + * 831. Masking Personal Information + * https://leetcode.com/problems/masking-personal-information/ + * Difficulty: Medium + * + * We are given a personal information string S, which may represent either an email address or a phone number. + * We would like to mask this personal information according to the following rules: + * 1. Email address: + * We define a name to be a string of length ≥ 2 consisting of only lowercase letters a-z or uppercase letters A-Z. + * An email address starts with a name, followed by the symbol '@', followed by a name, followed by the dot '.' and + * followed by a name. All email addresses are guaranteed to be valid and in the format of "name1@name2.name3". + * To mask an email, all names must be converted to lowercase and all letters between the first and last letter of + * the first name must be replaced by 5 asterisks '*'. + * + * 2. Phone number: + * A phone number is a string consisting of only the digits 0-9 or the characters from the set + * {'+', '-', '(', ')', ' '}. You may assume a phone number contains 10 to 13 digits. The last 10 digits make up the + * local number, while the digits before those make up the country code. Note that the country code is optional. We + * want to expose only the last 4 digits and mask all other digits. The local number should be formatted and masked + * as "***-***-1111", where 1 represents the exposed digits. To mask a phone number with country code like + * "+111 111 111 1111", we write it in the form "+***-***-***-1111". The '+' sign and the first '-' sign before the + * local number should only exist if there is a country code. For example, a 12 digit phone number mask should start + * with "+**-". Note that extraneous characters like "(", ")", " ", as well as extra dashes or plus signs not part of + * the above formatting scheme should be removed. + * + * Return the correct "mask" of the information provided. + */ + +// The one-line solution: +/** + * @param {string} S + * @return {string} + */ +var maskPII = function(S) { + return S.toLowerCase() + .replace(/^([a-z])[a-z]*([a-z])/, '$1*****$2') + .replace(/[)(\-\s+]+/g, '') + .replace(/^(\d*)(\d{3})(\d{3})(\d{4})$/, '+$1-$2-$3-$4') + .replace(/\d(?!\d{0,3}$)/g, '*') + .replace(/^\+\-/, ''); +}; + +// More readable alternative: +/** + * @param {string} S + * @return {string} + */ +var maskPII = function(S) { + if (S.includes('@')) { + return S.toLowerCase().replace(/^(\w)\w*(\w)/, '$1*****$2'); + } else { + return S.replace(/\D+/g, '') + .replace(/^(\d*)(\d{3})(\d{3})(\d{4})$/, '+$1-$2-$3-$4') + .replace(/\d(?!\d{0,3}$)/g, '*') + .replace(/^\+\-/, ''); + } +}; \ No newline at end of file diff --git a/README.md b/README.md index d7047c96..a7e42c8b 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,7 @@ 804|[Unique Morse Code Words](./0804-unique-morse-code-words.js)|Easy| 819|[Most Common Word](./0819-most-common-word.js)|Easy| 824|[Goat Latin](./0824-goat-latin.js)|Easy| +831|[Masking Personal Information](./0831-masking-personal-information.js)|Medium| 890|[Find and Replace Pattern](./0890-find-and-replace-pattern.js)|Medium| 916|[Word Subsets](./0916-word-subsets.js)|Medium| 929|[Unique Email Addresses](./0929-unique-email-addresses.js)|Easy| From ac44de24fd4151e83a114ac00496c4a1e2887b07 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 23 Jan 2020 23:29:45 -0500 Subject: [PATCH 061/919] Add solution #1233 --- ...-remove-sub-folders-from-the-filesystem.js | 32 +++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 1233-remove-sub-folders-from-the-filesystem.js diff --git a/1233-remove-sub-folders-from-the-filesystem.js b/1233-remove-sub-folders-from-the-filesystem.js new file mode 100644 index 00000000..a876bd66 --- /dev/null +++ b/1233-remove-sub-folders-from-the-filesystem.js @@ -0,0 +1,32 @@ +/** + * 1233. Remove Sub-Folders from the Filesystem + * https://leetcode.com/problems/remove-sub-folders-from-the-filesystem/ + * Difficulty: Medium + * + * Given a list of folders, remove all sub-folders in those folders + * and return in any order the folders after removing. + * + * If a folder[i] is located within another folder[j], it is called + * a sub-folder of it. The format of a path is one or more concatenated + * strings of the form: / followed by one or more lowercase English + * letters. For example, /leetcode and /leetcode/problems are valid + * paths while an empty string and / are not. + */ + +/** + * @param {string[]} folder + * @return {string[]} + */ +var removeSubfolders = function(folder) { + const set = new Set(folder); + return folder.filter(path => !getPathSegments(path).some(p => set.has(p))); +}; + +function getPathSegments(path) { + const split = path.split('/'); + const segments = [split.shift()]; + while (split.length > 1) { + segments.push(segments[segments.length - 1] + '/' + split.shift()); + } + return segments; +} diff --git a/README.md b/README.md index a7e42c8b..8f7a50bf 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,7 @@ 1189|[Maximum Number of Balloons](./1189-maximum-number-of-balloons.js)|Easy| 1207|[Unique Number of Occurrences](./1207-unique-number-of-occurrences.js)|Easy| 1232|[Check If It Is a Straight Line](./1232-check-if-it-is-a-straight-line.js)|Easy| +1233|[Remove Sub-Folders from the Filesystem](./1233-remove-sub-folders-from-the-filesystem.js)|Medium| 1249|[Minimum Remove to Make Valid Parentheses](./1249-minimum-remove-to-make-valid-parentheses.js)|Medium| 1252|[Cells with Odd Values in a Matrix](./1252-cells-with-odd-values-in-a-matrix.js)|Easy| 1287|[Element Appearing More Than 25% In Sorted Array](./1287-element-appearing-more-than-25-in-sorted-array.js)|Easy| From 881a1140963b90499099ca8b1127696b1754f5ba Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 23 Jan 2020 23:53:29 -0500 Subject: [PATCH 062/919] Add solution #541 --- 0541-reverse-string-ii.js | 24 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 0541-reverse-string-ii.js diff --git a/0541-reverse-string-ii.js b/0541-reverse-string-ii.js new file mode 100644 index 00000000..1f98f1db --- /dev/null +++ b/0541-reverse-string-ii.js @@ -0,0 +1,24 @@ +/** + * 541. Reverse String II + * https://leetcode.com/problems/reverse-string-ii/ + * Difficulty: Easy + * + * Given a string and an integer k, you need to reverse the first k characters + * for every 2k characters counting from the start of the string. If there are + * less than k characters left, reverse all of them. If there are less than 2k + * but greater than or equal to k characters, then reverse the first k + * characters and left the other as original. + */ + +/** + * @param {string} s + * @param {number} k + * @return {string} + */ +var reverseStr = function(s, k) { + const split = s.split(''); + for (let i = 0; i < s.length; i += 2 * k) { + split.splice(i, 0, ...split.splice(i, k).reverse()); + } + return split.join(''); +}; diff --git a/README.md b/README.md index 8f7a50bf..18066092 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,7 @@ 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| 451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| 459|[Repeated Substring Pattern](./0459-repeated-substring-pattern.js)|Easy| +541|[Reverse String II](./0541-reverse-string-ii.js)|Easy| 606|[Construct String from Binary Tree](./0606-construct-string-from-binary-tree.js)|Easy| 617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy| 648|[Replace Words](./0648-replace-words.js)|Medium| From f9de6f9291415aa321e0ebd4927c6a1a1b068e52 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 24 Jan 2020 00:15:12 -0500 Subject: [PATCH 063/919] Add solution #345 --- 0345-reverse-vowels-of-a-string.js | 17 +++++++++++++++++ README.md | 1 + 2 files changed, 18 insertions(+) create mode 100644 0345-reverse-vowels-of-a-string.js diff --git a/0345-reverse-vowels-of-a-string.js b/0345-reverse-vowels-of-a-string.js new file mode 100644 index 00000000..b21b2b54 --- /dev/null +++ b/0345-reverse-vowels-of-a-string.js @@ -0,0 +1,17 @@ +/** + * 345. Reverse Vowels of a String + * https://leetcode.com/problems/reverse-vowels-of-a-string/ + * Difficulty: Easy + * + * Write a function that takes a string as input + * and reverse only the vowels of a string. + */ + +/** + * @param {string} s + * @return {string} + */ +var reverseVowels = function(s) { + const vowels = s.match(/[aeiou]/ig); + return s.replace(/[aeiou]/ig, () => vowels.pop()); +}; diff --git a/README.md b/README.md index 18066092..4291d45e 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ 226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy| 263|[Ugly Number](./0263-ugly-number.js)|Easy| 264|[Ugly Number II](./0264-ugly-number-ii.js)|Medium| +345|[Reverse Vowels of a String](./0345-reverse-vowels-of-a-string.js)|Easy| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| 451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| 459|[Repeated Substring Pattern](./0459-repeated-substring-pattern.js)|Easy| From cb5857a6010783c6348826cbffc85e4a5d034ded Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 25 Jan 2020 23:33:20 -0500 Subject: [PATCH 064/919] Add solution #5320 --- ...ts-by-vegan-friendly-price-and-distance.js | 30 +++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 5320-filter-restaurants-by-vegan-friendly-price-and-distance.js diff --git a/5320-filter-restaurants-by-vegan-friendly-price-and-distance.js b/5320-filter-restaurants-by-vegan-friendly-price-and-distance.js new file mode 100644 index 00000000..3b0aa472 --- /dev/null +++ b/5320-filter-restaurants-by-vegan-friendly-price-and-distance.js @@ -0,0 +1,30 @@ +/** + * 5320. Filter Restaurants by Vegan-Friendly, Price and Distance + * https://leetcode.com/problems/filter-restaurants-by-vegan-friendly-price-and-distance/ + * Difficulty: Medium + * + * Given the array restaurants where restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]. + * You have to filter the restaurants using three filters. + * + * The veganFriendly filter will be either true (meaning you should only include restaurants with + * veganFriendlyi set to true) or false (meaning you can include any restaurant). In addition, you + * have the filters maxPrice and maxDistance which are the maximum value for price and distance of + * restaurants you should consider respectively. + * + * Return the array of restaurant IDs after filtering, ordered by rating from highest to lowest. + * For restaurants with the same rating, order them by id from highest to lowest. For simplicity + * veganFriendlyi and veganFriendly take value 1 when it is true, and 0 when it is false. + */ + +/** + * @param {number[][]} restaurants + * @param {number} veganFriendly + * @param {number} maxPrice + * @param {number} maxDistance + * @return {number[]} + */ +var filterRestaurants = function(restaurants, veganFriendly, maxPrice, maxDistance) { + return restaurants.filter(r => (!veganFriendly || r[2]) && r[3] <= maxPrice && r[4] <= maxDistance) + .sort((a, b) => a[1] === b[1] ? b[0] - a[0] : b[1] - a[1]) + .map(r => r[0]); +}; diff --git a/README.md b/README.md index 4291d45e..427bc372 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,7 @@ 1318|[Minimum Flips to Make a OR b Equal to c](./1318-minimum-flips-to-make-a-or-b-equal-to-c.js)|Medium| 1323|[Maximum 69 Number](./1323-maximum-69-number.js)|Easy| 1324|[Print Words Vertically](./1324-print-words-vertically.js)|Medium| +5320|[Filter Restaurants by Vegan-Friendly, Price and Distance](./5320-filter-restaurants-by-vegan-friendly-price-and-distance.js)|Medium| ## License From 59bc0c2d750226f48f59a193aa19bb12d34606e4 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 25 Jan 2020 23:36:27 -0500 Subject: [PATCH 065/919] Add solution #5319 --- 5319-remove-palindromic-subsequences.js | 23 +++++++++++++++++++++++ README.md | 1 + 2 files changed, 24 insertions(+) create mode 100644 5319-remove-palindromic-subsequences.js diff --git a/5319-remove-palindromic-subsequences.js b/5319-remove-palindromic-subsequences.js new file mode 100644 index 00000000..2939bfd4 --- /dev/null +++ b/5319-remove-palindromic-subsequences.js @@ -0,0 +1,23 @@ +/** + * 5319. Remove Palindromic Subsequences + * https://leetcode.com/problems/remove-palindromic-subsequences/ + * Difficulty: Easy + * + * Given a string s consisting only of letters 'a' and 'b'. + * In a single step you can remove one palindromic subsequence from s. + * + * Return the minimum number of steps to make the given string empty. + * A string is a subsequence of a given string, if it is generated by + * deleting some characters of a given string without changing its order. + * + * A string is called palindrome if is one that reads the same backward + * as well as forward. + */ + +/** + * @param {string} s + * @return {number} + */ +var removePalindromeSub = function(s) { + return s.length === 0 ? 0 : (s.split('').reverse().join('') === s ? 1 : 2); +}; diff --git a/README.md b/README.md index 427bc372..e565ba42 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,7 @@ 1318|[Minimum Flips to Make a OR b Equal to c](./1318-minimum-flips-to-make-a-or-b-equal-to-c.js)|Medium| 1323|[Maximum 69 Number](./1323-maximum-69-number.js)|Easy| 1324|[Print Words Vertically](./1324-print-words-vertically.js)|Medium| +5319|[Remove Palindromic Subsequences](./5319-remove-palindromic-subsequences.js)|Easy| 5320|[Filter Restaurants by Vegan-Friendly, Price and Distance](./5320-filter-restaurants-by-vegan-friendly-price-and-distance.js)|Medium| ## License From 9885b734b26875e1725251e24558b5e7da434338 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 25 Jan 2020 23:44:34 -0500 Subject: [PATCH 066/919] Add solution #5320 --- 5320-filter-restaurants-by-vegan-friendly-price-and-distance.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/5320-filter-restaurants-by-vegan-friendly-price-and-distance.js b/5320-filter-restaurants-by-vegan-friendly-price-and-distance.js index 3b0aa472..daac80f1 100644 --- a/5320-filter-restaurants-by-vegan-friendly-price-and-distance.js +++ b/5320-filter-restaurants-by-vegan-friendly-price-and-distance.js @@ -24,7 +24,7 @@ * @return {number[]} */ var filterRestaurants = function(restaurants, veganFriendly, maxPrice, maxDistance) { - return restaurants.filter(r => (!veganFriendly || r[2]) && r[3] <= maxPrice && r[4] <= maxDistance) + return restaurants.filter(([,, v, p, d]) => v >= veganFriendly && p <= maxPrice && d <= maxDistance) .sort((a, b) => a[1] === b[1] ? b[0] - a[0] : b[1] - a[1]) .map(r => r[0]); }; From ad577c19d26e4f1ca8e747fdb7ef9ad2de52357e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 26 Jan 2020 21:36:56 -0500 Subject: [PATCH 067/919] Add solution #867 --- 0867-transpose-matrix.js | 18 ++++++++++++++++++ README.md | 1 + 2 files changed, 19 insertions(+) create mode 100644 0867-transpose-matrix.js diff --git a/0867-transpose-matrix.js b/0867-transpose-matrix.js new file mode 100644 index 00000000..4154b7d6 --- /dev/null +++ b/0867-transpose-matrix.js @@ -0,0 +1,18 @@ +/** + * 867. Transpose Matrix + * https://leetcode.com/problems/transpose-matrix/ + * Difficulty: Easy + * + * Given a matrix A, return the transpose of A. + * + * The transpose of a matrix is the matrix flipped over it's main + * diagonal, switching the row and column indices of the matrix. + */ + +/** + * @param {number[][]} A + * @return {number[][]} + */ +var transpose = function(A) { + return A[0].map((_, i) => A.map(j => j[i])); +}; diff --git a/README.md b/README.md index e565ba42..e223aa13 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,7 @@ 819|[Most Common Word](./0819-most-common-word.js)|Easy| 824|[Goat Latin](./0824-goat-latin.js)|Easy| 831|[Masking Personal Information](./0831-masking-personal-information.js)|Medium| +867|[Transpose Matrix](./0867-transpose-matrix.js)|Easy| 890|[Find and Replace Pattern](./0890-find-and-replace-pattern.js)|Medium| 916|[Word Subsets](./0916-word-subsets.js)|Medium| 929|[Unique Email Addresses](./0929-unique-email-addresses.js)|Easy| From a5906218d7ba97c9749044fc3f05f19a9c12999b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 26 Jan 2020 22:15:42 -0500 Subject: [PATCH 068/919] Add solution #565 --- 0565-array-nesting.js | 34 ++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 0565-array-nesting.js diff --git a/0565-array-nesting.js b/0565-array-nesting.js new file mode 100644 index 00000000..1c34798e --- /dev/null +++ b/0565-array-nesting.js @@ -0,0 +1,34 @@ +/** + * 565. Array Nesting + * https://leetcode.com/problems/array-nesting/ + * Difficulty: Medium + * + * A zero-indexed array A of length N contains all integers from 0 to N-1. + * Find and return the longest length of set S, where S[i] = {A[i], + * A[A[i]], A[A[A[i]]], ... } subjected to the rule below. + * + * Suppose the first element in S starts with the selection of element + * A[i] of index = i, the next element in S should be A[A[i]], and then + * A[A[A[i]]]… By that analogy, we stop adding right before a duplicate + * element occurs in S. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var arrayNesting = function(nums) { + const history = new Set(); + let max = 0; + for (let i = 0; i < nums.length; i++) { + let count = 0; + let j = i; + while (!history.has(nums[j])) { + j = nums[j]; + history.add(j); + count++; + } + max = Math.max(max, count); + } + return max; +}; diff --git a/README.md b/README.md index e223aa13..ae269ba6 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ 451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| 459|[Repeated Substring Pattern](./0459-repeated-substring-pattern.js)|Easy| 541|[Reverse String II](./0541-reverse-string-ii.js)|Easy| +565|[Array Nesting](./0565-array-nesting.js)|Medium| 606|[Construct String from Binary Tree](./0606-construct-string-from-binary-tree.js)|Easy| 617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy| 648|[Replace Words](./0648-replace-words.js)|Medium| From 35606fe1e0c1921752624c31c9b1aa32f9d167dd Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 26 Jan 2020 22:43:13 -0500 Subject: [PATCH 069/919] Add solution #628 --- 0628-maximum-product-of-three-numbers.js | 18 ++++++++++++++++++ README.md | 1 + 2 files changed, 19 insertions(+) create mode 100644 0628-maximum-product-of-three-numbers.js diff --git a/0628-maximum-product-of-three-numbers.js b/0628-maximum-product-of-three-numbers.js new file mode 100644 index 00000000..fb973d59 --- /dev/null +++ b/0628-maximum-product-of-three-numbers.js @@ -0,0 +1,18 @@ +/** + * 628. Maximum Product of Three Numbers + * https://leetcode.com/problems/maximum-product-of-three-numbers/ + * Difficulty: Easy + * + * Given an integer array, find three numbers whose + * product is maximum and output the maximum product. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var maximumProduct = function(nums) { + const n = nums.length; + nums.sort((a, b) => a - b); + return Math.max(nums[0] * nums[1] * nums[n - 1], nums[n - 1] * nums[n - 2] * nums[n - 3]); +}; diff --git a/README.md b/README.md index ae269ba6..5db842a6 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,7 @@ 565|[Array Nesting](./0565-array-nesting.js)|Medium| 606|[Construct String from Binary Tree](./0606-construct-string-from-binary-tree.js)|Easy| 617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy| +628|[Maximum Product of Three Numbers](./0628-maximum-product-of-three-numbers.js)|Easy| 648|[Replace Words](./0648-replace-words.js)|Medium| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| 722|[Remove Comments](./0722-remove-comments.js)|Medium| From cd6f060a44fe950d2f43c860c2a70ff83c0bd83d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 26 Jan 2020 23:10:40 -0500 Subject: [PATCH 070/919] Add solution #36 --- 0036-valid-sudoku.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/0036-valid-sudoku.js b/0036-valid-sudoku.js index bb000b2e..41b1560f 100644 --- a/0036-valid-sudoku.js +++ b/0036-valid-sudoku.js @@ -29,8 +29,7 @@ var isValidSudoku = function(board) { const options = [rows[i], columns[j], boxes[k]]; if (options.some(option => option.has(value))) return false; - if (value === '.') continue; - options.forEach(option => option.add(value)); + if (value !== '.') options.forEach(option => option.add(value)); } } From f87d0405fb2b5e33799a899dda4be41c9221860a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 27 Jan 2020 21:59:12 -0500 Subject: [PATCH 071/919] Add solution #1332 --- ...c-subsequences.js => 1332-remove-palindromic-subsequences.js | 2 +- README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename 5319-remove-palindromic-subsequences.js => 1332-remove-palindromic-subsequences.js (94%) diff --git a/5319-remove-palindromic-subsequences.js b/1332-remove-palindromic-subsequences.js similarity index 94% rename from 5319-remove-palindromic-subsequences.js rename to 1332-remove-palindromic-subsequences.js index 2939bfd4..89eae0fb 100644 --- a/5319-remove-palindromic-subsequences.js +++ b/1332-remove-palindromic-subsequences.js @@ -1,5 +1,5 @@ /** - * 5319. Remove Palindromic Subsequences + * 1332. Remove Palindromic Subsequences * https://leetcode.com/problems/remove-palindromic-subsequences/ * Difficulty: Easy * diff --git a/README.md b/README.md index 5db842a6..455951cc 100644 --- a/README.md +++ b/README.md @@ -66,7 +66,7 @@ 1318|[Minimum Flips to Make a OR b Equal to c](./1318-minimum-flips-to-make-a-or-b-equal-to-c.js)|Medium| 1323|[Maximum 69 Number](./1323-maximum-69-number.js)|Easy| 1324|[Print Words Vertically](./1324-print-words-vertically.js)|Medium| -5319|[Remove Palindromic Subsequences](./5319-remove-palindromic-subsequences.js)|Easy| +1332|[Remove Palindromic Subsequences](./1332-remove-palindromic-subsequences.js)|Easy| 5320|[Filter Restaurants by Vegan-Friendly, Price and Distance](./5320-filter-restaurants-by-vegan-friendly-price-and-distance.js)|Medium| ## License From 9e22948bf15a03856c9b9619962ef4fae0c646d4 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 27 Jan 2020 22:03:06 -0500 Subject: [PATCH 072/919] Add solution #1333 --- ...3-filter-restaurants-by-vegan-friendly-price-and-distance.js | 2 +- README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename 5320-filter-restaurants-by-vegan-friendly-price-and-distance.js => 1333-filter-restaurants-by-vegan-friendly-price-and-distance.js (95%) diff --git a/5320-filter-restaurants-by-vegan-friendly-price-and-distance.js b/1333-filter-restaurants-by-vegan-friendly-price-and-distance.js similarity index 95% rename from 5320-filter-restaurants-by-vegan-friendly-price-and-distance.js rename to 1333-filter-restaurants-by-vegan-friendly-price-and-distance.js index daac80f1..e926910a 100644 --- a/5320-filter-restaurants-by-vegan-friendly-price-and-distance.js +++ b/1333-filter-restaurants-by-vegan-friendly-price-and-distance.js @@ -1,5 +1,5 @@ /** - * 5320. Filter Restaurants by Vegan-Friendly, Price and Distance + * 1333. Filter Restaurants by Vegan-Friendly, Price and Distance * https://leetcode.com/problems/filter-restaurants-by-vegan-friendly-price-and-distance/ * Difficulty: Medium * diff --git a/README.md b/README.md index 455951cc..76b26471 100644 --- a/README.md +++ b/README.md @@ -67,7 +67,7 @@ 1323|[Maximum 69 Number](./1323-maximum-69-number.js)|Easy| 1324|[Print Words Vertically](./1324-print-words-vertically.js)|Medium| 1332|[Remove Palindromic Subsequences](./1332-remove-palindromic-subsequences.js)|Easy| -5320|[Filter Restaurants by Vegan-Friendly, Price and Distance](./5320-filter-restaurants-by-vegan-friendly-price-and-distance.js)|Medium| +1333|[Filter Restaurants by Vegan-Friendly, Price and Distance](./1333-filter-restaurants-by-vegan-friendly-price-and-distance.js)|Medium| ## License From 7b95fcbe09cb2ba71bead76389c673ffaa06cc9a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 27 Jan 2020 22:03:31 -0500 Subject: [PATCH 073/919] Add solution #152 --- 0152-maximum-product-subarray.js | 23 +++++++++++++++++++++++ README.md | 1 + 2 files changed, 24 insertions(+) create mode 100644 0152-maximum-product-subarray.js diff --git a/0152-maximum-product-subarray.js b/0152-maximum-product-subarray.js new file mode 100644 index 00000000..44084d42 --- /dev/null +++ b/0152-maximum-product-subarray.js @@ -0,0 +1,23 @@ +/** + * 152. Maximum Product Subarray + * https://leetcode.com/problems/maximum-product-subarray/ + * Difficulty: Medium + * + * Given an integer array nums, find the contiguous subarray within an array + * (containing at least one number) which has the largest product. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var maxProduct = function(nums) { + let result = nums[0]; + let min = 1; + let max = 1; + for (let n of nums) { + [min, max] = [Math.min(n, min * n, max * n), Math.max(n, min * n, max * n)]; + result = Math.max(result, max); + } + return result; +}; diff --git a/README.md b/README.md index 76b26471..6a807fc6 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,7 @@ 66|[Plus One](./0066-plus-one.js)|Easy| 67|[Add Binary](./0067-add-binary.js)|Easy| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| +152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| 226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy| 263|[Ugly Number](./0263-ugly-number.js)|Easy| 264|[Ugly Number II](./0264-ugly-number-ii.js)|Medium| From 97055812e5a45c856e6d0ad2d5eccb8bc78a0775 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 3 Feb 2020 21:37:35 -0500 Subject: [PATCH 074/919] Add solution #713 --- 0713-subarray-product-less-than-k.js | 30 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 0713-subarray-product-less-than-k.js diff --git a/0713-subarray-product-less-than-k.js b/0713-subarray-product-less-than-k.js new file mode 100644 index 00000000..48a11c48 --- /dev/null +++ b/0713-subarray-product-less-than-k.js @@ -0,0 +1,30 @@ +/** + * 713. Subarray Product Less Than K + * https://leetcode.com/problems/subarray-product-less-than-k/ + * Difficulty: Medium + * + * Your are given an array of positive integers nums. + * + * Count and print the number of (contiguous) subarrays where the + * product of all the elements in the subarray is less than k. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var numSubarrayProductLessThanK = function(nums, k) { + let result = 0; + for (let right = 0, left = 0, product = 1; right < nums.length; right++) { + product *= nums[right]; + while (product >= k && left < nums.length) { + product /= nums[left]; + left++; + } + if (left < nums.length) { + result = result + right - left + 1; + } + } + return result; +}; diff --git a/README.md b/README.md index 6a807fc6..2a23ef16 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,7 @@ 628|[Maximum Product of Three Numbers](./0628-maximum-product-of-three-numbers.js)|Easy| 648|[Replace Words](./0648-replace-words.js)|Medium| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| +713|[Subarray Product Less Than K](./0713-subarray-product-less-than-k.js)|Medium| 722|[Remove Comments](./0722-remove-comments.js)|Medium| 739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium| 791|[Custom Sort String](./0791-custom-sort-string.js)|Medium| From c0504d418c4a7a0d7cfb07c600baa8879a7fd727 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 9 Feb 2020 22:58:12 -0500 Subject: [PATCH 075/919] Add solution #925 --- 0925-long-pressed-name.js | 21 +++++++++++++++++++++ README.md | 1 + 2 files changed, 22 insertions(+) create mode 100644 0925-long-pressed-name.js diff --git a/0925-long-pressed-name.js b/0925-long-pressed-name.js new file mode 100644 index 00000000..7b983317 --- /dev/null +++ b/0925-long-pressed-name.js @@ -0,0 +1,21 @@ +/** + * 925. Long Pressed Name + * https://leetcode.com/problems/long-pressed-name/ + * Difficulty: Easy + * + * Your friend is typing his name into a keyboard. Sometimes, when typing a character c, + * the key might get long pressed, and the character will be typed 1 or more times. + * + * You examine the typed characters of the keyboard. Return True if it is possible that + * it was your friends name, with some characters (possibly none) being long pressed. + */ + +/** + * @param {string} name + * @param {string} typed + * @return {boolean} + */ +var isLongPressedName = function(name, typed) { + let i = 0; + return typed.split('').filter(l => name[i] === l ? ++i : false).length === name.length; +}; diff --git a/README.md b/README.md index 2a23ef16..3491b029 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,7 @@ 867|[Transpose Matrix](./0867-transpose-matrix.js)|Easy| 890|[Find and Replace Pattern](./0890-find-and-replace-pattern.js)|Medium| 916|[Word Subsets](./0916-word-subsets.js)|Medium| +925|[Long Pressed Name](./0925-long-pressed-name.js)|Easy| 929|[Unique Email Addresses](./0929-unique-email-addresses.js)|Easy| 966|[Vowel Spellchecker](./0966-vowel-spellchecker.js)|Medium| 970|[Powerful Integers](./0970-powerful-integers.js)|Easy| From c9989498d9edbdeeee9675d882c6d6b1b29fee92 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 16 Sep 2021 14:54:20 -0400 Subject: [PATCH 076/919] Add solution #31 --- 0031-next-permutation.js | 50 ++++++++++++++++++++++++++++++++++++++++ README.md | 3 ++- 2 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 0031-next-permutation.js diff --git a/0031-next-permutation.js b/0031-next-permutation.js new file mode 100644 index 00000000..cc05f03c --- /dev/null +++ b/0031-next-permutation.js @@ -0,0 +1,50 @@ +/** + * 31. Next Permutation + * https://leetcode.com/problems/next-permutation/ + * Difficulty: Medium + * + * Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. + * + * If such an arrangement is not possible, it must rearrange it as the lowest possible order (i.e., sorted in ascending order). + * + * The replacement must be in place and use only constant extra memory. + */ + +/** + * @param {number[]} nums + * @return {void} Do not return anything, modify nums in-place instead. + */ + var nextPermutation = function(nums) { + let i = nums.length - 2; + + while (i >= 0 && nums[i + 1] <= nums[i]) { + i--; + } + + if (i >= 0) { + let cursor = nums.length - 1; + while (nums[cursor] <= nums[i]) { + cursor--; + } + swap(nums, i, cursor); + } + + reverse(nums, i + 1); +}; + +function reverse(nums, start) { + let i = start; + let j = nums.length - 1; + + while (i < j) { + swap(nums, i, j); + i++; + j--; + } +} + +function swap(nums, i, j) { + const temp = nums[i]; + nums[i] = nums[j]; + nums[j] = temp; +} \ No newline at end of file diff --git a/README.md b/README.md index 3491b029..1979ea1b 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,7 @@ |#|Title|Difficulty| |:---|:---|:---| 4|[Median of Two Sorted Arrays](./0004-median-of-two-sorted-arrays.js)|Hard| +31|[Next Permutation](./0031-next-permutation.js)|Medium| 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| 43|[Multiply Strings](./0043-multiply-strings.js)|Medium| 58|[Length of Last Word](./0058-length-of-last-word.js)|Easy| @@ -76,4 +77,4 @@ [MIT License](https://opensource.org/licenses/MIT) -Copyright (c) 2019-2020 [Josh Crozier](https://joshcrozier.com) +Copyright (c) 2019-2021 [Josh Crozier](https://joshcrozier.com) From 396948e7659af061b6a539f097465e651c9496d3 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 16 Sep 2021 15:04:18 -0400 Subject: [PATCH 077/919] Add solution #1360 --- 1360-number-of-days-between-two-dates.js | 18 ++++++++++++++++++ README.md | 1 + 2 files changed, 19 insertions(+) create mode 100644 1360-number-of-days-between-two-dates.js diff --git a/1360-number-of-days-between-two-dates.js b/1360-number-of-days-between-two-dates.js new file mode 100644 index 00000000..b3a6ed22 --- /dev/null +++ b/1360-number-of-days-between-two-dates.js @@ -0,0 +1,18 @@ +/** + * 1360. Number of Days Between Two Dates + * https://leetcode.com/problems/number-of-days-between-two-dates/ + * Difficulty: Easy + * + * Write a program to count the number of days between two dates. + * + * The two dates are given as strings, their format is `YYYY-MM-DD` as shown in the examples. + */ + +/** + * @param {string} date1 + * @param {string} date2 + * @return {number} + */ + var daysBetweenDates = function(date1, date2) { + return Math.abs(new Date(date1) - new Date(date2)) / (24 * 60 * 60 * 1000); +}; \ No newline at end of file diff --git a/README.md b/README.md index 1979ea1b..d9cfecf7 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,7 @@ 1324|[Print Words Vertically](./1324-print-words-vertically.js)|Medium| 1332|[Remove Palindromic Subsequences](./1332-remove-palindromic-subsequences.js)|Easy| 1333|[Filter Restaurants by Vegan-Friendly, Price and Distance](./1333-filter-restaurants-by-vegan-friendly-price-and-distance.js)|Medium| +1360|[Number of Days Between Two Dates](./1360-number-of-days-between-two-dates.js)|Easy| ## License From c863b390a02309e923222269119f937bc5d2b74c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 16 Sep 2021 15:45:18 -0400 Subject: [PATCH 078/919] Add solution #1 --- 0001-two-sum.js | 30 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 0001-two-sum.js diff --git a/0001-two-sum.js b/0001-two-sum.js new file mode 100644 index 00000000..788e9d47 --- /dev/null +++ b/0001-two-sum.js @@ -0,0 +1,30 @@ +/** + * 1. Two Sum + * https://leetcode.com/problems/two-sum/ + * Difficulty: Easy + * + * Given an array of integers `nums` and an integer `target`, return indices of the two numbers such that they add up to `target`. + * + * You may assume that each input would have exactly one solution, and you may not use the same element twice. + * + * You can return the answer in any order. + */ + +/** + * @param {number[]} nums + * @param {number} target + * @return {number[]} + */ +var twoSum = function(nums, target) { + const map = new Map(); + + for (let i = 0; i < nums.length; i++) { + const diff = target - nums[i]; + + if (map.has(diff)) { + return [map.get(diff), i]; + } + + map.set(nums[i], i); + } +}; diff --git a/README.md b/README.md index d9cfecf7..ab6b580a 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,7 @@ |#|Title|Difficulty| |:---|:---|:---| +1|[Two Sum](./0001-two-sum.js)|Easy| 4|[Median of Two Sorted Arrays](./0004-median-of-two-sorted-arrays.js)|Hard| 31|[Next Permutation](./0031-next-permutation.js)|Medium| 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| From 0c5117e8bef4da49a51ff844c43c92bc650b77fc Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 17 Sep 2021 23:59:49 -0400 Subject: [PATCH 079/919] Add solution #54 --- 0054-spiral-matrix.js | 43 +++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 44 insertions(+) create mode 100644 0054-spiral-matrix.js diff --git a/0054-spiral-matrix.js b/0054-spiral-matrix.js new file mode 100644 index 00000000..3e6616e3 --- /dev/null +++ b/0054-spiral-matrix.js @@ -0,0 +1,43 @@ +/** + * 54. Spiral Matrix + * https://leetcode.com/problems/spiral-matrix/ + * Difficulty: Medium + * + * Given an `m x n` `matrix`, return all elements of the `matrix` in spiral order. + */ + +/** + * @param {number[][]} matrix + * @return {number[]} + */ +var spiralOrder = function(matrix) { + const output = []; + let top = 0; + let right = matrix[0].length - 1; + let bottom = matrix.length - 1; + let left = 0; + + while (output.length < matrix.length * matrix[0].length) { + for (let i = left; i <= right; i++) { + output.push(matrix[top][i]); + } + top++; + + for (let i = top; i <= bottom; i++) { + output.push(matrix[i][right]); + } + right--; + + for (let i = right; top <= bottom && i >= left; i--) { + output.push(matrix[bottom][i]); + } + bottom--; + + for (let i = bottom; left <= right && i >= top; i--) { + output.push(matrix[i][left]); + } + left++; + } + + return output; +}; diff --git a/README.md b/README.md index ab6b580a..6d066af1 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,7 @@ 31|[Next Permutation](./0031-next-permutation.js)|Medium| 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| 43|[Multiply Strings](./0043-multiply-strings.js)|Medium| +54|[Spiral Matrix](./0054-spiral-matrix.js)|Medium| 58|[Length of Last Word](./0058-length-of-last-word.js)|Easy| 66|[Plus One](./0066-plus-one.js)|Easy| 67|[Add Binary](./0067-add-binary.js)|Easy| From 495f66b778a04ebe088ea7492881596147d7ae50 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 18 Sep 2021 16:57:25 -0400 Subject: [PATCH 080/919] Add solution #350 --- 0350-intersection-of-two-arrays-ii.js | 30 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 0350-intersection-of-two-arrays-ii.js diff --git a/0350-intersection-of-two-arrays-ii.js b/0350-intersection-of-two-arrays-ii.js new file mode 100644 index 00000000..4e837cf7 --- /dev/null +++ b/0350-intersection-of-two-arrays-ii.js @@ -0,0 +1,30 @@ +/** + * 350. Intersection of Two Arrays II + * https://leetcode.com/problems/intersection-of-two-arrays-ii/ + * Difficulty: Easy + * + * Given two integer arrays nums1 and nums2, return an array of their intersection. + * + * Each element in the result must appear as many times as it shows in both arrays + * and you may return the result in any order. + */ + +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number[]} + */ +var intersect = function(nums1, nums2) { + const result = []; + const map = {}; + + nums1.forEach(value => map[value] = (map[value] || 0) + 1); + nums2.forEach(value => { + if (map[value]) { + result.push(value); + map[value]--; + } + }); + + return result; +}; diff --git a/README.md b/README.md index 6d066af1..b714a8e1 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ 263|[Ugly Number](./0263-ugly-number.js)|Easy| 264|[Ugly Number II](./0264-ugly-number-ii.js)|Medium| 345|[Reverse Vowels of a String](./0345-reverse-vowels-of-a-string.js)|Easy| +350|[Intersection of Two Arrays II](./0350-intersection-of-two-arrays-ii.js)|Easy| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| 451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| 459|[Repeated Substring Pattern](./0459-repeated-substring-pattern.js)|Easy| From ad60b301877f684bd4650e2ed6e72a4b208f2081 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 18 Sep 2021 16:59:10 -0400 Subject: [PATCH 081/919] Add solution #283 --- 0283-move-zeroes.js | 29 +++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 30 insertions(+) create mode 100644 0283-move-zeroes.js diff --git a/0283-move-zeroes.js b/0283-move-zeroes.js new file mode 100644 index 00000000..3264be77 --- /dev/null +++ b/0283-move-zeroes.js @@ -0,0 +1,29 @@ +/** + * 283. Move Zeroes + * https://leetcode.com/problems/move-zeroes/ + * Difficulty: Easy + * + * Given an integer array `nums`, move all `0`'s to the end of it while maintaining the relative order of the non-zero elements. + * + * Note that you must do this in-place without making a copy of the array. + */ + +/** + * @param {number[]} nums + * @return {void} Do not return anything, modify nums in-place instead. + */ +var moveZeroes = function(nums) { + for (let i = 0, j = 0; i < nums.length; i++) { + if (nums[i] !== 0) { + swap(nums, i, j++); + } + } + + return nums; +}; + +function swap(nums, i, j) { + const temp = nums[i]; + nums[i] = nums[j]; + nums[j] = temp; +} diff --git a/README.md b/README.md index b714a8e1..1f268fb1 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ 226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy| 263|[Ugly Number](./0263-ugly-number.js)|Easy| 264|[Ugly Number II](./0264-ugly-number-ii.js)|Medium| +283|[Move Zeroes](./0283-move-zeroes.js)|Easy| 345|[Reverse Vowels of a String](./0345-reverse-vowels-of-a-string.js)|Easy| 350|[Intersection of Two Arrays II](./0350-intersection-of-two-arrays-ii.js)|Easy| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| From 6a7247bf50c0e710eea48bca7fe2ddc8ac60648a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 18 Sep 2021 19:51:34 -0400 Subject: [PATCH 082/919] Add solution #27 --- 0027-remove-element.js | 29 +++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 30 insertions(+) create mode 100644 0027-remove-element.js diff --git a/0027-remove-element.js b/0027-remove-element.js new file mode 100644 index 00000000..5547faec --- /dev/null +++ b/0027-remove-element.js @@ -0,0 +1,29 @@ +/** + * 27. Remove Element + * https://leetcode.com/problems/remove-element/ + * Difficulty: Easy + * + * Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. + * The relative order of the elements may be changed. + * + * Since it is impossible to change the length of the array in some languages, you must instead + * have the result be placed in the first part of the array nums. More formally, if there are + * k elements after removing the duplicates, then the first k elements of nums should hold the + * final result. It does not matter what you leave beyond the first k elements. + * + * Return k after placing the final result in the first k slots of nums. + * + * Do not allocate extra space for another array. You must do this by modifying the input + * array in-place with O(1) extra memory. + */ + +/** + * @param {number[]} nums + * @param {number} val + * @return {number} + */ +var removeElement = function(nums, val) { + for (let i = nums.length - 1; i > -1; i--) { + if (nums[i] === val) nums.splice(i, 1); + } +}; diff --git a/README.md b/README.md index 1f268fb1..3a285857 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ |:---|:---|:---| 1|[Two Sum](./0001-two-sum.js)|Easy| 4|[Median of Two Sorted Arrays](./0004-median-of-two-sorted-arrays.js)|Hard| +27|[Remove Element](./0027-remove-element.js)|Easy| 31|[Next Permutation](./0031-next-permutation.js)|Medium| 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| 43|[Multiply Strings](./0043-multiply-strings.js)|Medium| From b3b62ffc6f10b85995fc2b8cab5205934892eb49 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 19 Sep 2021 20:39:51 -0400 Subject: [PATCH 083/919] Add solution #7 --- 0007-reverse-integer.js | 23 +++++++++++++++++++++++ README.md | 1 + 2 files changed, 24 insertions(+) create mode 100644 0007-reverse-integer.js diff --git a/0007-reverse-integer.js b/0007-reverse-integer.js new file mode 100644 index 00000000..bf9ed763 --- /dev/null +++ b/0007-reverse-integer.js @@ -0,0 +1,23 @@ +/** + * 7. Reverse Integer + * https://leetcode.com/problems/reverse-integer/ + * Difficulty: Easy + * + * Given a signed 32-bit integer x, return x with its digits reversed. + * If reversing x causes the value to go outside the signed 32-bit integer + * range [-2^31, 2^31 - 1], then return 0. + */ + +/** + * @param {number} x + * @return {number} + */ +var reverse = function(x) { + const reversed = String(Math.abs(x)).split('').reverse().join(''); + + if (reversed > Math.pow(2, 31)) { + return 0; + } + + return reversed * Math.sign(x); +}; diff --git a/README.md b/README.md index 3a285857..b6d1a104 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ |:---|:---|:---| 1|[Two Sum](./0001-two-sum.js)|Easy| 4|[Median of Two Sorted Arrays](./0004-median-of-two-sorted-arrays.js)|Hard| +7|[Reverse Integer](./0007-reverse-integer.js)|Easy| 27|[Remove Element](./0027-remove-element.js)|Easy| 31|[Next Permutation](./0031-next-permutation.js)|Medium| 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| From 9b858c65619b2e720fc82937bcc1386d97807c38 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 19 Sep 2021 20:45:45 -0400 Subject: [PATCH 084/919] Add solution #2 --- 0002-add-two-numbers.js | 43 +++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 44 insertions(+) create mode 100644 0002-add-two-numbers.js diff --git a/0002-add-two-numbers.js b/0002-add-two-numbers.js new file mode 100644 index 00000000..93b52403 --- /dev/null +++ b/0002-add-two-numbers.js @@ -0,0 +1,43 @@ +/** + * 2. Add Two Numbers + * https://leetcode.com/problems/add-two-numbers/ + * Difficulty: Medium + * + * You are given two non-empty linked lists representing two non-negative integers. + * The digits are stored in reverse order, and each of their nodes contains a single + * digit. Add the two numbers and return the sum as a linked list. + * + * You may assume the two numbers do not contain any leading zero, except the number 0 itself. + */ + +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} l1 + * @param {ListNode} l2 + * @return {ListNode} + */ +var addTwoNumbers = function(l1, l2) { + const result = new ListNode(); + let tail = result; + let carry = 0; + + while (l1 || l2 || carry) { + const v1 = l1 ? l1.val : 0; + const v2 = l2 ? l2.val : 0; + const v = v1 + v2 + carry; + + tail.next = new ListNode(v % 10); + tail = tail.next; + carry = v >= 10 ? 1 : 0; + l1 = l1 && l1.next; + l2 = l2 && l2.next; + } + + return result.next; +}; diff --git a/README.md b/README.md index b6d1a104..eba29e71 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,7 @@ |#|Title|Difficulty| |:---|:---|:---| 1|[Two Sum](./0001-two-sum.js)|Easy| +2|[Add Two Numbers](./0002-add-two-numbers.js)|Medium| 4|[Median of Two Sorted Arrays](./0004-median-of-two-sorted-arrays.js)|Hard| 7|[Reverse Integer](./0007-reverse-integer.js)|Easy| 27|[Remove Element](./0027-remove-element.js)|Easy| From 02ab7d9110b762b882e591f7ea23b7c065c42573 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 19 Sep 2021 21:18:18 -0400 Subject: [PATCH 085/919] Add solution #3 --- ...-substring-without-repeating-characters.js | 22 +++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 0003-longest-substring-without-repeating-characters.js diff --git a/0003-longest-substring-without-repeating-characters.js b/0003-longest-substring-without-repeating-characters.js new file mode 100644 index 00000000..2bdecb15 --- /dev/null +++ b/0003-longest-substring-without-repeating-characters.js @@ -0,0 +1,22 @@ +/** + * 3. Longest Substring Without Repeating Characters + * https://leetcode.com/problems/longest-substring-without-repeating-characters/ + * Difficulty: Medium + * + * Given a string `s`, find the length of the longest substring without repeating characters. + */ + +/** + * @param {string} s + * @return {number} + */ +var lengthOfLongestSubstring = function(s) { + const map = {}; + let offset = 0; + + return s.split('').reduce((max, value, i) => { + offset = map[value] >= offset ? map[value] + 1 : offset; + map[value] = i; + return Math.max(max, i - offset + 1); + }, 0); +}; diff --git a/README.md b/README.md index eba29e71..474520b4 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ |:---|:---|:---| 1|[Two Sum](./0001-two-sum.js)|Easy| 2|[Add Two Numbers](./0002-add-two-numbers.js)|Medium| +3|[Longest Substring Without Repeating Characters](./0003-longest-substring-without-repeating-characters.js)|Medium| 4|[Median of Two Sorted Arrays](./0004-median-of-two-sorted-arrays.js)|Hard| 7|[Reverse Integer](./0007-reverse-integer.js)|Easy| 27|[Remove Element](./0027-remove-element.js)|Easy| From b864874beba28a028ee4bcb1c9d3cb275644f278 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 20 Sep 2021 17:55:20 -0400 Subject: [PATCH 086/919] Add solution #14 --- 0014-longest-common-prefix.js | 27 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 28 insertions(+) create mode 100644 0014-longest-common-prefix.js diff --git a/0014-longest-common-prefix.js b/0014-longest-common-prefix.js new file mode 100644 index 00000000..cfbe6d07 --- /dev/null +++ b/0014-longest-common-prefix.js @@ -0,0 +1,27 @@ +/** + * 14. Longest Common Prefix + * https://leetcode.com/problems/longest-common-prefix/ + * Difficulty: Easy + * + * Write a function to find the longest common prefix string amongst an array of strings. + * + * If there is no common prefix, return an empty string `""`. + */ + +/** + * @param {string[]} strs + * @return {string} + */ +var longestCommonPrefix = function(strs) { + const prefixes = strs[0].split('').map((_, i) => strs[0].slice(0, i + 1)); + + for (let i = strs.length - 1; i > -1; i--) { + for (let j = prefixes.length - 1; j > -1; j--) { + if (strs[i].substr(0, j + 1) !== prefixes[j]) { + prefixes.pop(); + } + } + } + + return prefixes.pop() || ''; +}; diff --git a/README.md b/README.md index 474520b4..6152281f 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,7 @@ 3|[Longest Substring Without Repeating Characters](./0003-longest-substring-without-repeating-characters.js)|Medium| 4|[Median of Two Sorted Arrays](./0004-median-of-two-sorted-arrays.js)|Hard| 7|[Reverse Integer](./0007-reverse-integer.js)|Easy| +14|[Longest Common Prefix](./0014-longest-common-prefix.js)|Easy| 27|[Remove Element](./0027-remove-element.js)|Easy| 31|[Next Permutation](./0031-next-permutation.js)|Medium| 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| From daa969fb39532345f522149200c751e74923754c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 20 Sep 2021 17:57:29 -0400 Subject: [PATCH 087/919] Add solution #10 --- 0010-regular-expression-matching.js | 22 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 0010-regular-expression-matching.js diff --git a/0010-regular-expression-matching.js b/0010-regular-expression-matching.js new file mode 100644 index 00000000..9e43518d --- /dev/null +++ b/0010-regular-expression-matching.js @@ -0,0 +1,22 @@ +/** + * 10. Regular Expression Matching + * https://leetcode.com/problems/regular-expression-matching/ + * Difficulty: Hard + * + * Given an input string s and a pattern p, implement regular expression + * matching with support for '.' and '*' where: + * + * '.' Matches any single character. + * '*' Matches zero or more of the preceding element. + * + * The matching should cover the entire input string (not partial). + */ + +/** + * @param {string} s + * @param {string} p + * @return {boolean} + */ +var isMatch = function(s, p) { + return new RegExp(`^${p}$`).test(s); +}; diff --git a/README.md b/README.md index 6152281f..f438b24f 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,7 @@ 3|[Longest Substring Without Repeating Characters](./0003-longest-substring-without-repeating-characters.js)|Medium| 4|[Median of Two Sorted Arrays](./0004-median-of-two-sorted-arrays.js)|Hard| 7|[Reverse Integer](./0007-reverse-integer.js)|Easy| +10|[Regular Expression Matching](./0010-regular-expression-matching.js)|Hard| 14|[Longest Common Prefix](./0014-longest-common-prefix.js)|Easy| 27|[Remove Element](./0027-remove-element.js)|Easy| 31|[Next Permutation](./0031-next-permutation.js)|Medium| From 395ae6cb05cdef7ace3770d116ba8a37094a7058 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 20 Sep 2021 18:13:42 -0400 Subject: [PATCH 088/919] Add solution #1880 --- ...k-if-word-equals-summation-of-two-words.js | 34 +++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 1880-check-if-word-equals-summation-of-two-words.js diff --git a/1880-check-if-word-equals-summation-of-two-words.js b/1880-check-if-word-equals-summation-of-two-words.js new file mode 100644 index 00000000..ea784f3c --- /dev/null +++ b/1880-check-if-word-equals-summation-of-two-words.js @@ -0,0 +1,34 @@ +/** + * 1880. Check if Word Equals Summation of Two Words + * https://leetcode.com/problems/check-if-word-equals-summation-of-two-words/ + * Difficulty: Easy + * + * The letter value of a letter is its position in the alphabet starting from + * 0 (i.e. 'a' -> 0, 'b' -> 1, 'c' -> 2, etc.). + * + * The numerical value of some string of lowercase English letters s is the + * concatenation of the letter values of each letter in s, which is then + * converted into an integer. + * + * For example, if s = "acb", we concatenate each letter's letter value, + * resulting in "021". After converting it, we get 21. + * + * You are given three strings firstWord, secondWord, and targetWord, each + * consisting of lowercase English letters 'a' through 'j' inclusive. + * + * Return true if the summation of the numerical values of firstWord and + * secondWord equals the numerical value of targetWord, or false otherwise. + */ + +/** + * @param {string} firstWord + * @param {string} secondWord + * @param {string} targetWord + * @return {boolean} + */ +var isSumEqual = function(firstWord, secondWord, targetWord) { + const [a, b, c] = [firstWord, secondWord, targetWord] + .map(str => +str.split('').map(v => v.charCodeAt() - 97).join('')); + + return a + b === c; +}; diff --git a/README.md b/README.md index f438b24f..e480fbe8 100644 --- a/README.md +++ b/README.md @@ -83,6 +83,7 @@ 1332|[Remove Palindromic Subsequences](./1332-remove-palindromic-subsequences.js)|Easy| 1333|[Filter Restaurants by Vegan-Friendly, Price and Distance](./1333-filter-restaurants-by-vegan-friendly-price-and-distance.js)|Medium| 1360|[Number of Days Between Two Dates](./1360-number-of-days-between-two-dates.js)|Easy| +1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| ## License From 288507208ae2c44bb8bb2a6f8581845e6434dd3e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 20 Sep 2021 18:38:46 -0400 Subject: [PATCH 089/919] Add solution #8 --- 0008-string-to-integer-atoi.js | 37 ++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 38 insertions(+) create mode 100644 0008-string-to-integer-atoi.js diff --git a/0008-string-to-integer-atoi.js b/0008-string-to-integer-atoi.js new file mode 100644 index 00000000..99adf77d --- /dev/null +++ b/0008-string-to-integer-atoi.js @@ -0,0 +1,37 @@ +/** + * 8. String to Integer (atoi) + * https://leetcode.com/problems/string-to-integer-atoi/ + * Difficulty: Medium + * + * Implement the myAtoi(string s) function, which converts a string to a + * 32-bit signed integer (similar to C/C++'s atoi function). + * + * The algorithm for myAtoi(string s) is as follows: + * + * - Read in and ignore any leading whitespace. + * - Check if the next character (if not already at the end of the string) + * is '-' or '+'. Read this character in if it is either. This determines + * if the final result is negative or positive respectively. + * Assume the result is positive if neither is present. + * - Read in next the characters until the next non-digit charcter or the end + * of the input is reached. The rest of the string is ignored. + * - Convert these digits into an integer (i.e. "123" -> 123, "0032" -> 32). + * If no digits were read, then the integer is 0. Change the sign as + * necessary (from step 2). + * - If the integer is out of the 32-bit signed integer range [-231, 231 - 1], + * then clamp the integer so that it remains in the range. Specifically, + * integers less than -231 should be clamped to -231, and integers greater + * than 231 - 1 should be clamped to 231 - 1. + * - Return the integer as the final result. + */ + +/** + * @param {string} s + * @return {number} + */ +var myAtoi = function(s) { + const parsed = +(s.trim().match(/^[-+]?\d+/g) || [0])[0]; + const clamped = Math.min(Math.max(parsed, (-2)**31), 2**31 - 1); + + return clamped; +}; diff --git a/README.md b/README.md index e480fbe8..9996d91d 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,7 @@ 3|[Longest Substring Without Repeating Characters](./0003-longest-substring-without-repeating-characters.js)|Medium| 4|[Median of Two Sorted Arrays](./0004-median-of-two-sorted-arrays.js)|Hard| 7|[Reverse Integer](./0007-reverse-integer.js)|Easy| +8|[String to Integer (atoi)](./0008-string-to-integer-atoi.js)|Medium| 10|[Regular Expression Matching](./0010-regular-expression-matching.js)|Hard| 14|[Longest Common Prefix](./0014-longest-common-prefix.js)|Easy| 27|[Remove Element](./0027-remove-element.js)|Easy| From a7d885d2f374682ea44ce1560d19e545b38e9002 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 22 Sep 2021 00:48:35 -0400 Subject: [PATCH 090/919] Add solution #1598 --- 1598-crawler-log-folder.js | 35 +++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 36 insertions(+) create mode 100644 1598-crawler-log-folder.js diff --git a/1598-crawler-log-folder.js b/1598-crawler-log-folder.js new file mode 100644 index 00000000..fc82db84 --- /dev/null +++ b/1598-crawler-log-folder.js @@ -0,0 +1,35 @@ +/** + * 1598. Crawler Log Folder + * https://leetcode.com/problems/crawler-log-folder/ + * Difficulty: Easy + * + * The Leetcode file system keeps a log each time some user performs + * a change folder operation. + * + * The operations are described below: + * + * - `"../"` : Move to the parent folder of the current folder. (If + * you are already in the main folder, remain in the same folder). + * - `"./"` : Remain in the same folder. + * - `"x/"` : Move to the child folder named x (This folder is + * guaranteed to always exist). + * + * You are given a list of strings logs where logs[i] is the operation + * performed by the user at the ith step. + * + * The file system starts in the main folder, then the operations in + * logs are performed. + * + * Return the minimum number of operations needed to go back to the + * main folder after the change folder operations. + */ + +/** + * @param {string[]} logs + * @return {number} + */ +var minOperations = function(logs) { + return logs.reduce((depth, log) => + Math.max(0, depth + (log === '../' ? -1 : log === './' ? 0 : 1)), 0 + ); +}; diff --git a/README.md b/README.md index 9996d91d..8c6377c0 100644 --- a/README.md +++ b/README.md @@ -84,6 +84,7 @@ 1332|[Remove Palindromic Subsequences](./1332-remove-palindromic-subsequences.js)|Easy| 1333|[Filter Restaurants by Vegan-Friendly, Price and Distance](./1333-filter-restaurants-by-vegan-friendly-price-and-distance.js)|Medium| 1360|[Number of Days Between Two Dates](./1360-number-of-days-between-two-dates.js)|Easy| +1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| ## License From b5c8a3fe0c5a0e75935c6873c8b8647015d3debe Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 22 Sep 2021 00:57:42 -0400 Subject: [PATCH 091/919] Add solution #844 --- 0844-backspace-string-compare.js | 30 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 0844-backspace-string-compare.js diff --git a/0844-backspace-string-compare.js b/0844-backspace-string-compare.js new file mode 100644 index 00000000..c5dab2e4 --- /dev/null +++ b/0844-backspace-string-compare.js @@ -0,0 +1,30 @@ +/** + * 844. Backspace String Compare + * https://leetcode.com/problems/backspace-string-compare/ + * Difficulty: Easy + * + * 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. + */ + +/** + * @param {string} s + * @param {string} t + * @return {boolean} + */ +var backspaceCompare = function(s, t) { + return handleBackspaces(s) === handleBackspaces(t); +}; + +function handleBackspaces(input) { + return input.split('').reduce((result, char) => { + if (char === '#') { + result.pop(); + } else { + result.push(char); + } + return result; + }, []).join(''); +} diff --git a/README.md b/README.md index 8c6377c0..df0264c4 100644 --- a/README.md +++ b/README.md @@ -48,6 +48,7 @@ 819|[Most Common Word](./0819-most-common-word.js)|Easy| 824|[Goat Latin](./0824-goat-latin.js)|Easy| 831|[Masking Personal Information](./0831-masking-personal-information.js)|Medium| +844|[Backspace String Compare](./0844-backspace-string-compare.js)|Easy| 867|[Transpose Matrix](./0867-transpose-matrix.js)|Easy| 890|[Find and Replace Pattern](./0890-find-and-replace-pattern.js)|Medium| 916|[Word Subsets](./0916-word-subsets.js)|Medium| From 52c700f923fc63e444429e7ea4220b15cfecdc9e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 22 Sep 2021 01:00:29 -0400 Subject: [PATCH 092/919] Add solution #1472 --- 1472-design-browser-history.js | 59 ++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 60 insertions(+) create mode 100644 1472-design-browser-history.js diff --git a/1472-design-browser-history.js b/1472-design-browser-history.js new file mode 100644 index 00000000..59a77531 --- /dev/null +++ b/1472-design-browser-history.js @@ -0,0 +1,59 @@ +/** + * 1472. Design Browser History + * https://leetcode.com/problems/design-browser-history/ + * Difficulty: Medium + * + * You have a browser of one tab where you start on the homepage and you + * can visit another url, get back in the history number of steps or move + * forward in the history number of steps. + * + * Implement the BrowserHistory class: + * + * - `BrowserHistory(string homepage)` Initializes the object with the + * homepage of the browser. + * - `void visit(string url)` Visits url from the current page. It clears + * up all the forward history. + * - `string back(int steps)` Move steps back in history. If you can only + * return x steps in the history and steps > x, you will return only x + * steps. Return the current url after moving back in history at most steps. + * - `string forward(int steps)` Move steps forward in history. If you can + * only forward x steps in the history and steps > x, you will forward only + * x steps. Return the current url after forwarding in history at most steps. + */ + +/** + * @param {string} homepage + */ +var BrowserHistory = function(homepage) { + this.history = []; + this.cursor = -1; + this.visit(homepage); +}; + +/** + * @param {string} url + * @return {void} + */ +BrowserHistory.prototype.visit = function(url) { + this.history.splice(this.cursor + 1, this.history.length); + this.history.push(url); + this.cursor++; +}; + +/** + * @param {number} steps + * @return {string} + */ +BrowserHistory.prototype.back = function(steps) { + this.cursor = Math.max(0, this.cursor - steps); + return this.history[this.cursor]; +}; + +/** + * @param {number} steps + * @return {string} + */ +BrowserHistory.prototype.forward = function(steps) { + this.cursor = Math.min(this.cursor + steps, this.history.length - 1); + return this.history[this.cursor]; +}; diff --git a/README.md b/README.md index df0264c4..72effc1c 100644 --- a/README.md +++ b/README.md @@ -85,6 +85,7 @@ 1332|[Remove Palindromic Subsequences](./1332-remove-palindromic-subsequences.js)|Easy| 1333|[Filter Restaurants by Vegan-Friendly, Price and Distance](./1333-filter-restaurants-by-vegan-friendly-price-and-distance.js)|Medium| 1360|[Number of Days Between Two Dates](./1360-number-of-days-between-two-dates.js)|Easy| +1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| From f82030aa9b9c26cbc1e3ddd0c6f7d27139befc29 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 22 Sep 2021 19:01:32 -0400 Subject: [PATCH 093/919] Add solution #349 --- 0349-intersection-of-two-arrays.js | 19 +++++++++++++++++++ README.md | 1 + 2 files changed, 20 insertions(+) create mode 100644 0349-intersection-of-two-arrays.js diff --git a/0349-intersection-of-two-arrays.js b/0349-intersection-of-two-arrays.js new file mode 100644 index 00000000..c80df42f --- /dev/null +++ b/0349-intersection-of-two-arrays.js @@ -0,0 +1,19 @@ +/** + * 349. Intersection of Two Arrays + * https://leetcode.com/problems/intersection-of-two-arrays/ + * Difficulty: Easy + * + * Given two integer arrays `nums1` and `nums2`, return an array of their intersection. + * + * Each element in the result must be unique and you may return the result in any order. + */ + +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number[]} + */ +var intersection = function(nums1, nums2) { + const set = new Set(nums1); + return nums2.filter(value => set.delete(value)); +}; diff --git a/README.md b/README.md index 72effc1c..7820c9cc 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,7 @@ 264|[Ugly Number II](./0264-ugly-number-ii.js)|Medium| 283|[Move Zeroes](./0283-move-zeroes.js)|Easy| 345|[Reverse Vowels of a String](./0345-reverse-vowels-of-a-string.js)|Easy| +349|[Intersection of Two Arrays](./0349-intersection-of-two-arrays.js)|Easy| 350|[Intersection of Two Arrays II](./0350-intersection-of-two-arrays-ii.js)|Easy| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| 451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| From 0b5920d3e6dd8df2c766f08bebc62f9aae51e420 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 22 Sep 2021 19:18:43 -0400 Subject: [PATCH 094/919] Add solution #347 --- 0347-top-k-frequent-elements.js | 24 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 0347-top-k-frequent-elements.js diff --git a/0347-top-k-frequent-elements.js b/0347-top-k-frequent-elements.js new file mode 100644 index 00000000..87b6b3e5 --- /dev/null +++ b/0347-top-k-frequent-elements.js @@ -0,0 +1,24 @@ +/** + * 347. Top K Frequent Elements + * https://leetcode.com/problems/top-k-frequent-elements/ + * Difficulty: Medium + * + * Given an integer array `nums` and an integer `k`, return the `k` most + * frequent elements. You may return the answer in any order. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {number[]} + */ +var topKFrequent = function(nums, k) { + const map = new Map(); + + nums.forEach(value => map.set(value, (map.get(value) || 0) + 1)); + + return [...map] + .sort((a, b) => b[1] - a[1]) + .slice(0, k) + .map(([value]) => value) +}; diff --git a/README.md b/README.md index 7820c9cc..435b5940 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,7 @@ 264|[Ugly Number II](./0264-ugly-number-ii.js)|Medium| 283|[Move Zeroes](./0283-move-zeroes.js)|Easy| 345|[Reverse Vowels of a String](./0345-reverse-vowels-of-a-string.js)|Easy| +347|[Top K Frequent Elements](./0347-top-k-frequent-elements.js)|Medium| 349|[Intersection of Two Arrays](./0349-intersection-of-two-arrays.js)|Easy| 350|[Intersection of Two Arrays II](./0350-intersection-of-two-arrays-ii.js)|Easy| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| From f4509a8bb285383cce397b5bdb0abd74361c11e3 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 23 Sep 2021 13:42:33 -0400 Subject: [PATCH 095/919] Add solution #448 --- ...ind-all-numbers-disappeared-in-an-array.js | 33 +++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 0448-find-all-numbers-disappeared-in-an-array.js diff --git a/0448-find-all-numbers-disappeared-in-an-array.js b/0448-find-all-numbers-disappeared-in-an-array.js new file mode 100644 index 00000000..fda2a892 --- /dev/null +++ b/0448-find-all-numbers-disappeared-in-an-array.js @@ -0,0 +1,33 @@ +/** + * 448. Find All Numbers Disappeared in an Array + * https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/ + * Difficulty: Easy + * + * Given an array `nums` of `n` integers where `nums[i]` is in the + * range `[1, n]`, return an array of all the integers in the + * range `[1, n]` that do not appear in nums. + */ + +/** + * @param {number[]} nums + * @return {number[]} + */ +var findDisappearedNumbers = function(nums) { + const result = []; + + for (let i = 0; i < nums.length;) { + if (nums[nums[i] - 1] !== nums[i]) { + [nums[nums[i] - 1], nums[i]] = [nums[i], nums[nums[i] - 1]]; + } else { + i++; + } + } + + nums.forEach((v, i) => { + if (v != i + 1) { + result.push(i + 1); + } + }); + + return result; +}; diff --git a/README.md b/README.md index 435b5940..4e724bce 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,7 @@ 349|[Intersection of Two Arrays](./0349-intersection-of-two-arrays.js)|Easy| 350|[Intersection of Two Arrays II](./0350-intersection-of-two-arrays-ii.js)|Easy| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| +448|[Find All Numbers Disappeared in an Array](./0448-find-all-numbers-disappeared-in-an-array.js)|Easy| 451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| 459|[Repeated Substring Pattern](./0459-repeated-substring-pattern.js)|Easy| 541|[Reverse String II](./0541-reverse-string-ii.js)|Easy| From 002983c874120a04d14ca92eb44ee2000024b2f5 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 23 Sep 2021 13:45:06 -0400 Subject: [PATCH 096/919] Add solution #41 --- 0041-first-missing-positive.js | 33 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 0041-first-missing-positive.js diff --git a/0041-first-missing-positive.js b/0041-first-missing-positive.js new file mode 100644 index 00000000..45d5107b --- /dev/null +++ b/0041-first-missing-positive.js @@ -0,0 +1,33 @@ +/** + * 41. First Missing Positive + * https://leetcode.com/problems/first-missing-positive/ + * Difficulty: Hard + * + * Given an unsorted integer array nums, return the smallest missing positive integer. + * + * You must implement an algorithm that runs in O(n) time and uses constant extra space. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var firstMissingPositive = function(nums) { + let i = 0; + + while (i < nums.length) { + if (nums[i] > 0 && nums[i] <= nums.length && nums[nums[i] - 1] !== nums[i]) { + [nums[nums[i] - 1], nums[i]] = [nums[i], nums[nums[i] - 1]]; + } else { + i++; + } + } + + for (i = 0; i < nums.length; i++) { + if (nums[i] !== i + 1) { + return i + 1; + } + } + + return i + 1; +}; diff --git a/README.md b/README.md index 4e724bce..93a0573f 100644 --- a/README.md +++ b/README.md @@ -17,6 +17,7 @@ 27|[Remove Element](./0027-remove-element.js)|Easy| 31|[Next Permutation](./0031-next-permutation.js)|Medium| 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| +41|[First Missing Positive](./0041-first-missing-positive.js)|Hard| 43|[Multiply Strings](./0043-multiply-strings.js)|Medium| 54|[Spiral Matrix](./0054-spiral-matrix.js)|Medium| 58|[Length of Last Word](./0058-length-of-last-word.js)|Easy| From f9493227c3eb31cd787ff9e4b7a1e0fc4ef0fa9f Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 23 Sep 2021 13:46:38 -0400 Subject: [PATCH 097/919] Add solution #268 --- 0268-missing-number.js | 25 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 26 insertions(+) create mode 100644 0268-missing-number.js diff --git a/0268-missing-number.js b/0268-missing-number.js new file mode 100644 index 00000000..f8624b64 --- /dev/null +++ b/0268-missing-number.js @@ -0,0 +1,25 @@ +/** + * 268. Missing Number + * https://leetcode.com/problems/missing-number/ + * Difficulty: Easy + * + * Given an array `nums` containing `n` distinct numbers in the range `[0, n]`, + * return the only number in the range that is missing from the array. + * + * Follow up: Could you implement a solution using only `O(1)` extra space + * complexity and `O(n)` runtime complexity? + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var missingNumber = function(nums) { + let result = 0; + + for (let i = 0; i < nums.length; i++) { + result += i + 1 - nums[i]; + } + + return result; +}; diff --git a/README.md b/README.md index 93a0573f..12993a07 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,7 @@ 226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy| 263|[Ugly Number](./0263-ugly-number.js)|Easy| 264|[Ugly Number II](./0264-ugly-number-ii.js)|Medium| +268|[Missing Number](./0268-missing-number.js)|Easy| 283|[Move Zeroes](./0283-move-zeroes.js)|Easy| 345|[Reverse Vowels of a String](./0345-reverse-vowels-of-a-string.js)|Easy| 347|[Top K Frequent Elements](./0347-top-k-frequent-elements.js)|Medium| From 073003a23f30569abfb7395dafc6d5f66b4dd58d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 23 Sep 2021 13:48:14 -0400 Subject: [PATCH 098/919] Add solution #17 --- 0017-letter-combinations-of-a-phone-number.js | 47 +++++++++++++++++++ README.md | 1 + 2 files changed, 48 insertions(+) create mode 100644 0017-letter-combinations-of-a-phone-number.js diff --git a/0017-letter-combinations-of-a-phone-number.js b/0017-letter-combinations-of-a-phone-number.js new file mode 100644 index 00000000..fd215917 --- /dev/null +++ b/0017-letter-combinations-of-a-phone-number.js @@ -0,0 +1,47 @@ +/** + * 17. Letter Combinations of a Phone Number + * https://leetcode.com/problems/letter-combinations-of-a-phone-number/ + * Difficulty: Medium + * + * Given a string containing digits from 2-9 inclusive, return all possible + * letter combinations that the number could represent. Return the answer + * in any order. + * + * A mapping of digit to letters (just like on the telephone buttons) is + * given below. Note that 1 does not map to any letters. + */ + +/** + * @param {string} digits + * @return {string[]} + */ +var letterCombinations = function(digits) { + if (!digits || !digits.length) return []; + + const map = { + 2: 'abc', + 3: 'def', + 4: 'ghi', + 5: 'jkl', + 6: 'mno', + 7: 'pqrs', + 8: 'tuv', + 9: 'wxyz' + }; + + if (digits.length === 1) { + return map[digits].split(''); + } + + const result = []; + const group1 = letterCombinations(digits.substr(0, 1)); + const group2 = letterCombinations(digits.substr(1)); + + for (let i = 0; i < group1.length; i++) { + for (let j = 0; j < group2.length; j++) { + result.push(group1[i] + group2[j]); + } + } + + return result; +}; diff --git a/README.md b/README.md index 12993a07..a0d9d909 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,7 @@ 8|[String to Integer (atoi)](./0008-string-to-integer-atoi.js)|Medium| 10|[Regular Expression Matching](./0010-regular-expression-matching.js)|Hard| 14|[Longest Common Prefix](./0014-longest-common-prefix.js)|Easy| +17|[Letter Combinations of a Phone Number](./0017-letter-combinations-of-a-phone-number.js)|Medium| 27|[Remove Element](./0027-remove-element.js)|Easy| 31|[Next Permutation](./0031-next-permutation.js)|Medium| 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| From 49a1fd12a57246f3c28c475363d9580f3365e4cf Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 24 Sep 2021 12:55:43 -0400 Subject: [PATCH 099/919] Add solution #2000 --- 2000-reverse-prefix-of-word.js | 22 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 2000-reverse-prefix-of-word.js diff --git a/2000-reverse-prefix-of-word.js b/2000-reverse-prefix-of-word.js new file mode 100644 index 00000000..531eabeb --- /dev/null +++ b/2000-reverse-prefix-of-word.js @@ -0,0 +1,22 @@ +/** + * 2000. Reverse Prefix of Word + * https://leetcode.com/problems/reverse-prefix-of-word/ + * Difficulty: Easy + * + * Given a 0-indexed string word and a character ch, reverse the segment of word that + * starts at index 0 and ends at the index of the first occurrence of ch (inclusive). + * If the character ch does not exist in word, do nothing. + * + * For example, if word = "abcdefd" and ch = "d", then you should reverse the segment + * that starts at 0 and ends at 3 (inclusive). The resulting string will be "dcbaefd". + */ + +/** + * @param {string} word + * @param {character} ch + * @return {string} + */ +var reversePrefix = function(word, ch) { + const index = word.indexOf(ch) + 1; + return word.slice(0, index).split('').reverse().join('') + word.slice(index); +}; diff --git a/README.md b/README.md index a0d9d909..d71081f8 100644 --- a/README.md +++ b/README.md @@ -94,6 +94,7 @@ 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| +2000|[Reverse Prefix of Word](./2000-reverse-prefix-of-word.js)|Easy| ## License From 78dee2bba0f9d142773259eb1809e3ee0dfe4393 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 24 Sep 2021 12:57:01 -0400 Subject: [PATCH 100/919] Add solution #884 --- 0884-uncommon-words-from-two-sentences.js | 26 +++++++++++++++++++++++ README.md | 1 + 2 files changed, 27 insertions(+) create mode 100644 0884-uncommon-words-from-two-sentences.js diff --git a/0884-uncommon-words-from-two-sentences.js b/0884-uncommon-words-from-two-sentences.js new file mode 100644 index 00000000..6ee36541 --- /dev/null +++ b/0884-uncommon-words-from-two-sentences.js @@ -0,0 +1,26 @@ +/** + * 884. Uncommon Words from Two Sentences + * https://leetcode.com/problems/uncommon-words-from-two-sentences/submissions/ + * Difficulty: Easy + * + * 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. + */ + +/** + * @param {string} s1 + * @param {string} s2 + * @return {string[]} + */ +var uncommonFromSentences = function(s1, s2) { + const map = new Map(); + + (s1 + ' ' + s2).split(/\s+/).forEach(s => map.set(s, (map.get(s) || 0) + 1)); + return [...map].reduce((a, [k, c]) => c === 1 ? [...a, k] : a, []); +}; diff --git a/README.md b/README.md index d71081f8..a02f578e 100644 --- a/README.md +++ b/README.md @@ -56,6 +56,7 @@ 831|[Masking Personal Information](./0831-masking-personal-information.js)|Medium| 844|[Backspace String Compare](./0844-backspace-string-compare.js)|Easy| 867|[Transpose Matrix](./0867-transpose-matrix.js)|Easy| +884|[Uncommon Words from Two Sentences](./0884-uncommon-words-from-two-sentences.js)|Easy| 890|[Find and Replace Pattern](./0890-find-and-replace-pattern.js)|Medium| 916|[Word Subsets](./0916-word-subsets.js)|Medium| 925|[Long Pressed Name](./0925-long-pressed-name.js)|Easy| From ba78a6b073e63aff3d78b80ae10b407ff1ac7c32 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 24 Sep 2021 12:58:19 -0400 Subject: [PATCH 101/919] Add solution #50 --- 0050-powx-n.js | 21 +++++++++++++++++++++ README.md | 1 + 2 files changed, 22 insertions(+) create mode 100644 0050-powx-n.js diff --git a/0050-powx-n.js b/0050-powx-n.js new file mode 100644 index 00000000..e0fafc09 --- /dev/null +++ b/0050-powx-n.js @@ -0,0 +1,21 @@ +/** + * 50. Pow(x, n) + * https://leetcode.com/problems/powx-n/ + * Difficulty: Medium + * + * Implement `pow(x, n)`, which calculates `x` raised to the power `n` (i.e., `x^n`). + */ + +/** + * @param {number} x + * @param {number} n + * @return {number} + */ +var myPow = function(x, n) { + if (n === 0) return 1; + if (n === 1) return x; + if (n < 0) return 1 / myPow(x, -n); + if (n % 2 === 0) return myPow(x * x, n / 2); + + return x * myPow(x * x, (n - 1) / 2); +}; diff --git a/README.md b/README.md index a02f578e..c0332676 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| 41|[First Missing Positive](./0041-first-missing-positive.js)|Hard| 43|[Multiply Strings](./0043-multiply-strings.js)|Medium| +50|[Pow(x, n)](./0050-powx-n.js)|Medium| 54|[Spiral Matrix](./0054-spiral-matrix.js)|Medium| 58|[Length of Last Word](./0058-length-of-last-word.js)|Easy| 66|[Plus One](./0066-plus-one.js)|Easy| From 196bf5d1fae7aac00f5b9c973108979285952710 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 24 Sep 2021 12:59:52 -0400 Subject: [PATCH 102/919] Add solution #49 --- 0049-group-anagrams.js | 26 ++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 27 insertions(+) create mode 100644 0049-group-anagrams.js diff --git a/0049-group-anagrams.js b/0049-group-anagrams.js new file mode 100644 index 00000000..3f48828b --- /dev/null +++ b/0049-group-anagrams.js @@ -0,0 +1,26 @@ +/** + * 49. Group Anagrams + * https://leetcode.com/problems/group-anagrams/ + * Difficulty: Medium + * + * Given an array of strings `strs`, group the anagrams together. You can return the + * answer in any order. + * + * An Anagram is a word or phrase formed by rearranging the letters of a different + * word or phrase, typically using all the original letters exactly once. + */ + +/** + * @param {string[]} strs + * @return {string[][]} + */ +var groupAnagrams = function(strs) { + const map = {}; + + strs.forEach(str => { + const key = [...str].sort(); + map[key] = map[key] ? [...map[key], str] : [str]; + }); + + return Object.values(map); +}; diff --git a/README.md b/README.md index c0332676..f0848190 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| 41|[First Missing Positive](./0041-first-missing-positive.js)|Hard| 43|[Multiply Strings](./0043-multiply-strings.js)|Medium| +49|[Group Anagrams](./0049-group-anagrams.js)|Medium| 50|[Pow(x, n)](./0050-powx-n.js)|Medium| 54|[Spiral Matrix](./0054-spiral-matrix.js)|Medium| 58|[Length of Last Word](./0058-length-of-last-word.js)|Easy| From 1a90f7beb7eaf0692a60704139201bf0864521e7 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 24 Sep 2021 13:03:34 -0400 Subject: [PATCH 103/919] Add solution #12 --- 0012-integer-to-roman.js | 44 ++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 45 insertions(+) create mode 100644 0012-integer-to-roman.js diff --git a/0012-integer-to-roman.js b/0012-integer-to-roman.js new file mode 100644 index 00000000..b4e941f6 --- /dev/null +++ b/0012-integer-to-roman.js @@ -0,0 +1,44 @@ +/** + * 12. Integer to Roman + * https://leetcode.com/problems/integer-to-roman/ + * Difficulty: Medium + * + * Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D` and `M`. + * + * Symbol Value + * I 1 + * V 5 + * X 10 + * L 50 + * C 100 + * D 500 + * M 1000 + * + * For example, `2` is written as `II` in Roman numeral, just two one's added together. `12` is written + * as `XII`, which is simply `X + II`. The number `27` is written as `XXVII`, which is `XX + V + II`. + * + * Roman numerals are usually written largest to smallest from left to right. However, the numeral for + * four is not `IIII`. Instead, the number four is written as `IV`. Because the one is before the five + * we subtract it making four. The same principle applies to the number nine, which is written as `IX`. + * There are six instances where subtraction is used: + * + * - `I` can be placed before `V (5)` and `X (10)` to make 4 and 9. + * - `X` can be placed before `L (50)` and `C (100)` to make 40 and 90. + * - `C` can be placed before `D (500)` and `M (1000)` to make 400 and 900. + * + * Given an integer, convert it to a roman numeral. + */ + +/** + * @param {number} num + * @return {string} + */ +var intToRoman = function(num) { + const map = { M: 1000, CM: 900, D: 500, CD: 400, C: 100, XC: 90, L: 50, XL: 40, X: 10, IX: 9, V: 5, IV: 4, I: 1 }; + + return Object.entries(map).reduce((result, [letter, n]) => { + result += letter.repeat(Math.floor(num / n)); + num %= n; + return result; + }, ''); +}; diff --git a/README.md b/README.md index f0848190..9aa3c8d8 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,7 @@ 7|[Reverse Integer](./0007-reverse-integer.js)|Easy| 8|[String to Integer (atoi)](./0008-string-to-integer-atoi.js)|Medium| 10|[Regular Expression Matching](./0010-regular-expression-matching.js)|Hard| +12|[Integer to Roman](./0012-integer-to-roman.js)|Medium| 14|[Longest Common Prefix](./0014-longest-common-prefix.js)|Easy| 17|[Letter Combinations of a Phone Number](./0017-letter-combinations-of-a-phone-number.js)|Medium| 27|[Remove Element](./0027-remove-element.js)|Easy| From f0ca466b646f4637175218ec6abf066731971172 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 24 Sep 2021 13:05:05 -0400 Subject: [PATCH 104/919] Add solution #13 --- 0013-roman-to-integer.js | 45 ++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 46 insertions(+) create mode 100644 0013-roman-to-integer.js diff --git a/0013-roman-to-integer.js b/0013-roman-to-integer.js new file mode 100644 index 00000000..14593317 --- /dev/null +++ b/0013-roman-to-integer.js @@ -0,0 +1,45 @@ +/** + * 13. Roman to Integer + * https://leetcode.com/problems/roman-to-integer/ + * Difficulty: Easy + * + * Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D` and `M`. + * + * Symbol Value + * I 1 + * V 5 + * X 10 + * L 50 + * C 100 + * D 500 + * M 1000 + * + * For example, `2` is written as `II` in Roman numeral, just two one's added together. `12` is written + * as `XII`, which is simply `X + II`. The number `27` is written as `XXVII`, which is `XX + V + II`. + * + * Roman numerals are usually written largest to smallest from left to right. However, the numeral for + * four is not `IIII`. Instead, the number four is written as `IV`. Because the one is before the five + * we subtract it making four. The same principle applies to the number nine, which is written as `IX`. + * There are six instances where subtraction is used: + * + * - `I` can be placed before `V (5)` and `X (10)` to make 4 and 9. + * - `X` can be placed before `L (50)` and `C (100)` to make 40 and 90. + * - `C` can be placed before `D (500)` and `M (1000)` to make 400 and 900. + * + * Given a roman numeral, convert it to an integer. + */ + +/** + * @param {string} s + * @return {number} + */ +var romanToInt = function(s) { + const map = { M: 1000, D: 500, C: 100, L: 50, X: 10, V: 5, I: 1 }; + + return s.split('').reduce((result, v, i) => { + result += map[v] >= map[s[i + 1]] || s.length === i + 1 + ? map[v] + : -1 * map[v]; + return result; + }, 0); +}; diff --git a/README.md b/README.md index 9aa3c8d8..fd3a1acc 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,7 @@ 8|[String to Integer (atoi)](./0008-string-to-integer-atoi.js)|Medium| 10|[Regular Expression Matching](./0010-regular-expression-matching.js)|Hard| 12|[Integer to Roman](./0012-integer-to-roman.js)|Medium| +13|[Roman to Integer](./0013-roman-to-integer.js)|Easy| 14|[Longest Common Prefix](./0014-longest-common-prefix.js)|Easy| 17|[Letter Combinations of a Phone Number](./0017-letter-combinations-of-a-phone-number.js)|Medium| 27|[Remove Element](./0027-remove-element.js)|Easy| From 3a62368d01f0cb2f038ef99e8260dbe9ae7561a3 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 24 Sep 2021 14:02:43 -0400 Subject: [PATCH 105/919] Add solution #1929 --- 1929-concatenation-of-array.js | 21 +++++++++++++++++++++ README.md | 1 + 2 files changed, 22 insertions(+) create mode 100644 1929-concatenation-of-array.js diff --git a/1929-concatenation-of-array.js b/1929-concatenation-of-array.js new file mode 100644 index 00000000..084d4b59 --- /dev/null +++ b/1929-concatenation-of-array.js @@ -0,0 +1,21 @@ +/** + * 1929. Concatenation of Array + * https://leetcode.com/problems/concatenation-of-array/ + * Difficulty: Easy + * + * Given an integer array `nums` of length `n`, you want to create an + * array `ans` of length `2n` where `ans[i] == nums[i`] and + * `ans[i + n] == nums[i]` for `0 <= i < n` (0-indexed). + * + * Specifically, `ans` is the concatenation of two `nums` arrays. + * + * Return the array `ans`. + */ + +/** + * @param {number[]} nums + * @return {number[]} + */ +var getConcatenation = function(nums) { + return [...nums, ...nums]; +}; diff --git a/README.md b/README.md index fd3a1acc..8a472980 100644 --- a/README.md +++ b/README.md @@ -99,6 +99,7 @@ 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| +1929|[Concatenation of Array](./1929-concatenation-of-array.js)|Easy| 2000|[Reverse Prefix of Word](./2000-reverse-prefix-of-word.js)|Easy| ## License From 50f42ec0774702c6e03f0409dad725673c8b7bdc Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 25 Sep 2021 16:26:57 -0400 Subject: [PATCH 106/919] Add solution #217 --- 0217-contains-duplicate.js | 16 ++++++++++++++++ README.md | 1 + 2 files changed, 17 insertions(+) create mode 100644 0217-contains-duplicate.js diff --git a/0217-contains-duplicate.js b/0217-contains-duplicate.js new file mode 100644 index 00000000..951c214f --- /dev/null +++ b/0217-contains-duplicate.js @@ -0,0 +1,16 @@ +/** + * 217. Contains Duplicate + * https://leetcode.com/problems/contains-duplicate/ + * Difficulty: Easy + * + * Given an integer array `nums`, return `true` if any value appears at least + * twice in the array, and return `false` if every element is distinct. + */ + +/** + * @param {number[]} nums + * @return {boolean} + */ +var containsDuplicate = function(nums) { + return new Set(nums).size !== nums.length; +}; diff --git a/README.md b/README.md index 8a472980..19924cb8 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,7 @@ 67|[Add Binary](./0067-add-binary.js)|Easy| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| +217|[Contains Duplicate](./0217-contains-duplicate.js)|Easy| 226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy| 263|[Ugly Number](./0263-ugly-number.js)|Easy| 264|[Ugly Number II](./0264-ugly-number-ii.js)|Medium| From 4213dca7f438ace5707687ad50cf3fec6f48eaa1 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 25 Sep 2021 16:28:38 -0400 Subject: [PATCH 107/919] Add solution #219 --- 0219-contains-duplicate-ii.js | 27 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 28 insertions(+) create mode 100644 0219-contains-duplicate-ii.js diff --git a/0219-contains-duplicate-ii.js b/0219-contains-duplicate-ii.js new file mode 100644 index 00000000..1b02742c --- /dev/null +++ b/0219-contains-duplicate-ii.js @@ -0,0 +1,27 @@ +/** + * 219. Contains Duplicate II + * https://leetcode.com/problems/contains-duplicate-ii/ + * Difficulty: Easy + * + * Given an integer array `nums` and an integer `k`, return `true` if there are + * two distinct indices `i` and `j` in the array such that `nums[i] == nums[j]` + * and `abs(i - j) <= k`. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {boolean} + */ +var containsNearbyDuplicate = function(nums, k) { + const map = new Map(); + + for (let i = 0; i < nums.length; i++) { + if (Math.abs(i - map.get(nums[i])) <= k) { + return true; + } + map.set(nums[i], i); + } + + return false; +}; diff --git a/README.md b/README.md index 19924cb8..dbb01348 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,7 @@ 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| 217|[Contains Duplicate](./0217-contains-duplicate.js)|Easy| +219|[Contains Duplicate II](./0219-contains-duplicate-ii.js)|Easy| 226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy| 263|[Ugly Number](./0263-ugly-number.js)|Easy| 264|[Ugly Number II](./0264-ugly-number-ii.js)|Medium| From 9dde91bebe2328b6e6af0a277d9a439c9f0f2790 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 25 Sep 2021 17:48:45 -0400 Subject: [PATCH 108/919] Add solution #88 --- 0088-merge-sorted-array.js | 34 ++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 0088-merge-sorted-array.js diff --git a/0088-merge-sorted-array.js b/0088-merge-sorted-array.js new file mode 100644 index 00000000..c94a4117 --- /dev/null +++ b/0088-merge-sorted-array.js @@ -0,0 +1,34 @@ +/** + * 88. Merge Sorted Array + * https://leetcode.com/problems/merge-sorted-array/ + * Difficulty: Easy + * + * You are given two integer arrays `nums1` and `nums2`, sorted in non-decreasing order, + * and two integers `m` and `n`, representing the number of elements in `nums1` and `nums2` + * respectively. + * + * Merge `nums1` and `nums2` into a single array sorted in non-decreasing order. + * + * The final sorted array should not be returned by the function, but instead be + * stored inside the array `nums1`. To accommodate this, `nums1` has a length of `m + n`, + * where the first `m` elements denote the elements that should be merged, and the + * last `n` elements are set to `0` and should be ignored. `nums2` has a length of `n`. + */ + +/** + * @param {number[]} nums1 + * @param {number} m + * @param {number[]} nums2 + * @param {number} n + * @return {void} Do not return anything, modify nums1 in-place instead. + */ +var merge = function(nums1, m, nums2, n) { + let i = m + n - 1; + + m--; + n--; + + while (n >= 0) { + nums1[i--] = nums1[m] > nums2[n] ? nums1[m--] : nums2[n--]; + } +}; diff --git a/README.md b/README.md index dbb01348..1254fb10 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,7 @@ 58|[Length of Last Word](./0058-length-of-last-word.js)|Easy| 66|[Plus One](./0066-plus-one.js)|Easy| 67|[Add Binary](./0067-add-binary.js)|Easy| +88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| 217|[Contains Duplicate](./0217-contains-duplicate.js)|Easy| From 43744db7fcd2e97d7bc1e1cc8a995fcea95c28c8 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 25 Sep 2021 17:49:35 -0400 Subject: [PATCH 109/919] Add solution #53 --- 0053-maximum-subarray.js | 24 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 0053-maximum-subarray.js diff --git a/0053-maximum-subarray.js b/0053-maximum-subarray.js new file mode 100644 index 00000000..55634cfc --- /dev/null +++ b/0053-maximum-subarray.js @@ -0,0 +1,24 @@ +/** + * 53. Maximum Subarray + * https://leetcode.com/problems/maximum-subarray/ + * Difficulty: Easy + * + * Given an integer array `nums`, find the contiguous subarray (containing at + * least one number) which has the largest sum and return its sum. + * + * A subarray is a contiguous part of an array. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var maxSubArray = function(nums) { + for (let i = 1; i < nums.length; i++) { + if (nums[i - 1] > 0) { + nums[i] += nums[i - 1]; + } + } + + return Math.max(...nums); +}; diff --git a/README.md b/README.md index 1254fb10..551ab0e3 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,7 @@ 43|[Multiply Strings](./0043-multiply-strings.js)|Medium| 49|[Group Anagrams](./0049-group-anagrams.js)|Medium| 50|[Pow(x, n)](./0050-powx-n.js)|Medium| +53|[Maximum Subarray](./0053-maximum-subarray.js)|Easy| 54|[Spiral Matrix](./0054-spiral-matrix.js)|Medium| 58|[Length of Last Word](./0058-length-of-last-word.js)|Easy| 66|[Plus One](./0066-plus-one.js)|Easy| From 61bf2632c75528f9fce58dba895f9fedb000d7fd Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 25 Sep 2021 17:52:11 -0400 Subject: [PATCH 110/919] Add solution #6 --- 0006-zigzag-conversion.js | 30 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 0006-zigzag-conversion.js diff --git a/0006-zigzag-conversion.js b/0006-zigzag-conversion.js new file mode 100644 index 00000000..37d5c314 --- /dev/null +++ b/0006-zigzag-conversion.js @@ -0,0 +1,30 @@ +/** + * 6. ZigZag Conversion + * https://leetcode.com/problems/zigzag-conversion/ + * Difficulty: Medium + * + * The string `"PAYPALISHIRING"` is written in a zigzag pattern on a given + * number of rows like this: (you may want to display this pattern in a + * fixed font for better legibility) + * + * > P A H N + * > A P L S I I G + * > Y I R + * + * And then read line by line: `"PAHNAPLSIIGYIR"` + */ + +/** + * @param {string} s + * @param {number} numRows + * @return {string} + */ +var convert = function(s, numRows) { + const order = [...new Array(numRows).keys()]; + order.push(...order.slice(1, -1).reverse()); + + const rows = new Array(numRows).fill(''); + [...s].forEach((c, i) => (rows[order[i % order.length]] += c)); + + return rows.join(''); +}; diff --git a/README.md b/README.md index 551ab0e3..8a98e944 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ 2|[Add Two Numbers](./0002-add-two-numbers.js)|Medium| 3|[Longest Substring Without Repeating Characters](./0003-longest-substring-without-repeating-characters.js)|Medium| 4|[Median of Two Sorted Arrays](./0004-median-of-two-sorted-arrays.js)|Hard| +6|[ZigZag Conversion](./0006-zigzag-conversion.js)|Medium| 7|[Reverse Integer](./0007-reverse-integer.js)|Easy| 8|[String to Integer (atoi)](./0008-string-to-integer-atoi.js)|Medium| 10|[Regular Expression Matching](./0010-regular-expression-matching.js)|Hard| From b105795f4716099a5f30d1c4eadb812ab9c5544c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 25 Sep 2021 17:58:43 -0400 Subject: [PATCH 111/919] Add solution #9 --- 0009-palindrome-number.js | 19 +++++++++++++++++++ README.md | 1 + 2 files changed, 20 insertions(+) create mode 100644 0009-palindrome-number.js diff --git a/0009-palindrome-number.js b/0009-palindrome-number.js new file mode 100644 index 00000000..e696c444 --- /dev/null +++ b/0009-palindrome-number.js @@ -0,0 +1,19 @@ +/** + * 9. Palindrome Number + * https://leetcode.com/problems/palindrome-number/ + * Difficulty: Easy + * + * Given an integer `x`, return `true` if `x` is palindrome integer. + +An integer is a palindrome when it reads the same backward as forward. +For example, `121` is palindrome while `123` is not. + */ + +/** + * @param {number} x + * @return {boolean} + */ +var isPalindrome = function(x) { + if (x < 0) return false; + return +String(x).split('').reverse().join('') === x; +}; diff --git a/README.md b/README.md index 8a98e944..09f0fa32 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,7 @@ 6|[ZigZag Conversion](./0006-zigzag-conversion.js)|Medium| 7|[Reverse Integer](./0007-reverse-integer.js)|Easy| 8|[String to Integer (atoi)](./0008-string-to-integer-atoi.js)|Medium| +9|[Palindrome Number](./0009-palindrome-number.js)|Easy| 10|[Regular Expression Matching](./0010-regular-expression-matching.js)|Hard| 12|[Integer to Roman](./0012-integer-to-roman.js)|Medium| 13|[Roman to Integer](./0013-roman-to-integer.js)|Easy| From 25ada88c5f5b480230b79a602a7bf4a7a5d39cbf Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 25 Sep 2021 18:07:26 -0400 Subject: [PATCH 112/919] Add solution #234 --- 0234-palindrome-linked-list.js | 30 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 0234-palindrome-linked-list.js diff --git a/0234-palindrome-linked-list.js b/0234-palindrome-linked-list.js new file mode 100644 index 00000000..37b4a5e6 --- /dev/null +++ b/0234-palindrome-linked-list.js @@ -0,0 +1,30 @@ +/** + * 234. Palindrome Linked List + * https://leetcode.com/problems/palindrome-linked-list/ + * Difficulty: Easy + * + * Given the `head` of a singly linked list, return `true` if it is a palindrome. + */ + +/** + * 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 {boolean} + */ +var isPalindrome = function(head) { + let a = '', b = ''; + + while (head) { + a = a + head.val; + b = head.val + b; + head = head.next; + } + + return a === b; +}; diff --git a/README.md b/README.md index 09f0fa32..550b2a12 100644 --- a/README.md +++ b/README.md @@ -37,6 +37,7 @@ 217|[Contains Duplicate](./0217-contains-duplicate.js)|Easy| 219|[Contains Duplicate II](./0219-contains-duplicate-ii.js)|Easy| 226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy| +234|[Palindrome Linked List](./0234-palindrome-linked-list.js)|Easy| 263|[Ugly Number](./0263-ugly-number.js)|Easy| 264|[Ugly Number II](./0264-ugly-number-ii.js)|Medium| 268|[Missing Number](./0268-missing-number.js)|Easy| From 4012c416abdbd11f65e99c2066a3f01a8b8ea1f8 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 26 Sep 2021 01:21:38 -0400 Subject: [PATCH 113/919] Add solution #42 --- 0042-trapping-rain-water.js | 35 +++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 36 insertions(+) create mode 100644 0042-trapping-rain-water.js diff --git a/0042-trapping-rain-water.js b/0042-trapping-rain-water.js new file mode 100644 index 00000000..4a7af38b --- /dev/null +++ b/0042-trapping-rain-water.js @@ -0,0 +1,35 @@ +/** + * 42. Trapping Rain Water + * https://leetcode.com/problems/trapping-rain-water/ + * Difficulty: Hard + * + * Given `n` non-negative integers representing an elevation map where the width + * of each bar is `1`, compute how much water it can trap after raining. + */ + +/** + * @param {number[]} height + * @return {number} + */ +var trap = function(height) { + const leftMax = []; + const rightMax = []; + let result = 0; + + leftMax[0] = height[0]; + rightMax[height.length - 1] = height[height.length - 1]; + + for (let i = 1; i < height.length; i++) { + leftMax[i] = Math.max(height[i], leftMax[i - 1]); + } + + for (let i = height.length - 2; i > -1; i--){ + rightMax[i] = Math.max(height[i], rightMax[i + 1]); + } + + for (let i = 0; i < height.length; i++) { + result += Math.min(leftMax[i], rightMax[i]) - height[i]; + } + + return result; +}; diff --git a/README.md b/README.md index 550b2a12..2455adf3 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ 31|[Next Permutation](./0031-next-permutation.js)|Medium| 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| 41|[First Missing Positive](./0041-first-missing-positive.js)|Hard| +42|[Trapping Rain Water](./0042-trapping-rain-water.js)|Hard| 43|[Multiply Strings](./0043-multiply-strings.js)|Medium| 49|[Group Anagrams](./0049-group-anagrams.js)|Medium| 50|[Pow(x, n)](./0050-powx-n.js)|Medium| From 3aac099f730f2550a94d127306f1c6639ed67ab6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 26 Sep 2021 01:23:53 -0400 Subject: [PATCH 114/919] Add solution #11 --- 0011-container-with-most-water.js | 35 +++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 36 insertions(+) create mode 100644 0011-container-with-most-water.js diff --git a/0011-container-with-most-water.js b/0011-container-with-most-water.js new file mode 100644 index 00000000..51818c6e --- /dev/null +++ b/0011-container-with-most-water.js @@ -0,0 +1,35 @@ +/** + * 11. Container With Most Water + * https://leetcode.com/problems/container-with-most-water/ + * Difficulty: Medium + * + * Given n non-negative integers `a1, a2, ..., an ,` where each represents a point at + * coordinate `(i, ai)`. `n` vertical lines are drawn such that the two endpoints of + * the line `i` is at `(i, ai)` and `(i, 0)`. Find two lines, which, together with the + * x-axis forms a container, such that the container contains the most water. + * + * Notice that you may not slant the container. + */ + +/** + * @param {number[]} height + * @return {number} + */ +var maxArea = function(height) { + let maxArea = 0; + + for (let left = 0, right = height.length - 1; left < right;) { + maxArea = Math.max( + maxArea, + Math.min(height[left], height[right]) * (right - left) + ); + + if (height[left] < height[right]) { + left++; + } else { + right--; + } + } + + return maxArea; +}; diff --git a/README.md b/README.md index 2455adf3..f976e203 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,7 @@ 8|[String to Integer (atoi)](./0008-string-to-integer-atoi.js)|Medium| 9|[Palindrome Number](./0009-palindrome-number.js)|Easy| 10|[Regular Expression Matching](./0010-regular-expression-matching.js)|Hard| +11|[Container With Most Water](./0011-container-with-most-water.js)|Medium| 12|[Integer to Roman](./0012-integer-to-roman.js)|Medium| 13|[Roman to Integer](./0013-roman-to-integer.js)|Easy| 14|[Longest Common Prefix](./0014-longest-common-prefix.js)|Easy| From 007bf8d379f43dde0154307ed70f659d1170573f Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 26 Sep 2021 01:25:23 -0400 Subject: [PATCH 115/919] Add solution #42 --- 0042-trapping-rain-water.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/0042-trapping-rain-water.js b/0042-trapping-rain-water.js index 4a7af38b..871e37a7 100644 --- a/0042-trapping-rain-water.js +++ b/0042-trapping-rain-water.js @@ -23,7 +23,7 @@ var trap = function(height) { leftMax[i] = Math.max(height[i], leftMax[i - 1]); } - for (let i = height.length - 2; i > -1; i--){ + for (let i = height.length - 2; i > -1; i--) { rightMax[i] = Math.max(height[i], rightMax[i + 1]); } From 1cf52caea84a52de65893634e7a2126df84aaec6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 26 Sep 2021 01:28:08 -0400 Subject: [PATCH 116/919] Add solution #73 --- 0073-set-matrix-zeroes.js | 33 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 0073-set-matrix-zeroes.js diff --git a/0073-set-matrix-zeroes.js b/0073-set-matrix-zeroes.js new file mode 100644 index 00000000..fbce9692 --- /dev/null +++ b/0073-set-matrix-zeroes.js @@ -0,0 +1,33 @@ +/** + * 73. Set Matrix Zeroes + * https://leetcode.com/problems/set-matrix-zeroes/ + * Difficulty: Medium + * + * Given an `m x n` integer `matrix` matrix, if an element is `0`, set its entire + * row and column to `0`'s, and return the matrix. + * + * You must do it in place. + */ + +/** + * @param {number[][]} matrix + * @return {void} Do not return anything, modify matrix in-place instead. + */ +var setZeroes = function(matrix) { + const columns = new Set(); + const rows = new Set(); + + matrix.forEach((row, i) => { + row.forEach((value, j) => { + if (value === 0) { + columns.add(i); + rows.add(j); + } + }); + }); + + [...columns].forEach(i => matrix[i].forEach((_, j) => matrix[i][j] = 0)); + matrix.forEach((_, i) => [...rows].forEach(j => matrix[i][j] = 0)); + + return matrix; +}; diff --git a/README.md b/README.md index f976e203..7ecba5bb 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,7 @@ 58|[Length of Last Word](./0058-length-of-last-word.js)|Easy| 66|[Plus One](./0066-plus-one.js)|Easy| 67|[Add Binary](./0067-add-binary.js)|Easy| +73|[Set Matrix Zeroes](./0073-set-matrix-zeroes.js)|Medium| 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| From 03e751ef3210568872b70d4dfe2bc168bdf4a517 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 26 Sep 2021 01:53:22 -0400 Subject: [PATCH 117/919] Add solution #273 --- 0273-integer-to-english-words.js | 33 ++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 0273-integer-to-english-words.js diff --git a/0273-integer-to-english-words.js b/0273-integer-to-english-words.js new file mode 100644 index 00000000..b664e25c --- /dev/null +++ b/0273-integer-to-english-words.js @@ -0,0 +1,33 @@ +/** + * 273. Integer to English Words + * https://leetcode.com/problems/integer-to-english-words/ + * Difficulty: Hard + * + * Convert a non-negative integer `num` to its English words representation. + */ + +/** + * @param {number} num + * @return {string} + */ +var numberToWords = function(num) { + if (num === 0) { + return 'Zero'; + } + + return convert(num).replace(/\s+/g, ' ').trim(); +}; + +const belowTen = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine']; +const belowTwenty = ['Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen']; +const belowHundred = ['', 'Ten', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety']; + +function convert(num) { + if (num < 10) return belowTen[num]; + else if (num < 20) return belowTwenty[num - 10]; + else if (num < 100) return belowHundred[Math.floor(num / 10)] + ' ' + convert(num % 10); + else if (num < 1000) return convert(Math.floor(num / 100)) + ' Hundred ' + convert(num % 100); + else if (num < 1000000) return convert(Math.floor(num / 1000)) + ' Thousand ' + convert(num % 1000); + else if (num < 1000000000) return convert(Math.floor(num / 1000000)) + ' Million ' + convert(num % 1000000); + else return convert(Math.floor(num / 1000000000)) + ' Billion ' + convert(num % 1000000000); +} diff --git a/README.md b/README.md index 7ecba5bb..6ea7a55b 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,7 @@ 263|[Ugly Number](./0263-ugly-number.js)|Easy| 264|[Ugly Number II](./0264-ugly-number-ii.js)|Medium| 268|[Missing Number](./0268-missing-number.js)|Easy| +273|[Integer to English Words](./0273-integer-to-english-words.js)|Hard| 283|[Move Zeroes](./0283-move-zeroes.js)|Easy| 345|[Reverse Vowels of a String](./0345-reverse-vowels-of-a-string.js)|Easy| 347|[Top K Frequent Elements](./0347-top-k-frequent-elements.js)|Medium| From d9224345e6c2bb7eae8febff3428056c15cbf655 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 26 Sep 2021 02:05:52 -0400 Subject: [PATCH 118/919] Add solution #121 --- 0121-best-time-to-buy-and-sell-stock.js | 29 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 30 insertions(+) create mode 100644 0121-best-time-to-buy-and-sell-stock.js diff --git a/0121-best-time-to-buy-and-sell-stock.js b/0121-best-time-to-buy-and-sell-stock.js new file mode 100644 index 00000000..20d2557f --- /dev/null +++ b/0121-best-time-to-buy-and-sell-stock.js @@ -0,0 +1,29 @@ +/** + * 121. Best Time to Buy and Sell Stock + * https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ + * Difficulty: Easy + * + * You are given an array prices where prices[i] is the price of a given stock + * on the ith day. + * + * You want to maximize your profit by choosing a single day to buy one stock + * and choosing a different day in the future to sell that stock. + * + * Return the maximum profit you can achieve from this transaction. If you + * cannot achieve any profit, return 0. + */ + +/** + * @param {number[]} prices + * @return {number} + */ +var maxProfit = function(prices) { + let max = 0; + + for (let i = 0, min = prices[0]; i < prices.length; i++) { + min = Math.min(min, prices[i]); + max = Math.max(max, prices[i] - min); + } + + return max; +}; diff --git a/README.md b/README.md index 6ea7a55b..00885999 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,7 @@ 67|[Add Binary](./0067-add-binary.js)|Easy| 73|[Set Matrix Zeroes](./0073-set-matrix-zeroes.js)|Medium| 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| +121|[Best Time to Buy and Sell Stock](./0121-best-time-to-buy-and-sell-stock.js)|Easy| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| 217|[Contains Duplicate](./0217-contains-duplicate.js)|Easy| From 391c8ff32cf043ee6b1150aade4ade6e747cf23b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 26 Sep 2021 16:07:10 -0400 Subject: [PATCH 119/919] Add solution #5 --- 0005-longest-palindromic-substring.js | 37 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 38 insertions(+) create mode 100644 0005-longest-palindromic-substring.js diff --git a/0005-longest-palindromic-substring.js b/0005-longest-palindromic-substring.js new file mode 100644 index 00000000..d15b8499 --- /dev/null +++ b/0005-longest-palindromic-substring.js @@ -0,0 +1,37 @@ +/** + * 5. Longest Palindromic Substring + * https://leetcode.com/problems/longest-palindromic-substring/ + * Difficulty: Medium + * + * Given a string `s`, return the longest palindromic substring in `s`. + */ + +/** + * @param {string} s + * @return {string} + */ +var longestPalindrome = function(s) { + let result = ''; + + for (let i = 0; i < s.length; i++) { + let palindrome1 = getExtendedPalindrome(s, i, i); + let palindrome2 = getExtendedPalindrome(s, i, i + 1); + let longerPalindrome = palindrome1.length > palindrome2.length + ? palindrome1 : palindrome2; + + if (longerPalindrome.length > result.length) { + result = longerPalindrome; + } + } + + return result; +}; + +function getExtendedPalindrome(s, start, end) { + while (start >= 0 && end < s.length && s[start] === s[end]) { + start--; + end++; + } + + return s.slice(start + 1, end); +} diff --git a/README.md b/README.md index 00885999..df1f81d6 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ 2|[Add Two Numbers](./0002-add-two-numbers.js)|Medium| 3|[Longest Substring Without Repeating Characters](./0003-longest-substring-without-repeating-characters.js)|Medium| 4|[Median of Two Sorted Arrays](./0004-median-of-two-sorted-arrays.js)|Hard| +5|[Longest Palindromic Substring](./0005-longest-palindromic-substring.js)|Medium| 6|[ZigZag Conversion](./0006-zigzag-conversion.js)|Medium| 7|[Reverse Integer](./0007-reverse-integer.js)|Easy| 8|[String to Integer (atoi)](./0008-string-to-integer-atoi.js)|Medium| From 7d50d6ff603571a60eaa04c7dc2a39f62ad65ba2 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 27 Sep 2021 01:32:38 -0400 Subject: [PATCH 120/919] Add solution #383 --- 0383-ransom-note.js | 32 ++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 0383-ransom-note.js diff --git a/0383-ransom-note.js b/0383-ransom-note.js new file mode 100644 index 00000000..5bda58f1 --- /dev/null +++ b/0383-ransom-note.js @@ -0,0 +1,32 @@ +/** + * 383. Ransom Note + * https://leetcode.com/problems/ransom-note/ + * Difficulty: Easy + * + * Given two stings ransomNote and magazine, return true if ransomNote + * can be constructed from magazine and false otherwise. + * + * Each letter in magazine can only be used once in ransomNote. + */ + +/** + * @param {string} ransomNote + * @param {string} magazine + * @return {boolean} + */ +var canConstruct = function(ransomNote, magazine) { + const map = new Map(); + + for (let i = magazine.length - 1; i > -1; i--) { + map.set(magazine[i], (map.get(magazine[i]) || 0) + 1); + } + + for (let i = ransomNote.length - 1; i > -1; i--) { + if ((map.get(ransomNote[i]) || 0) < 1) { + return false; + } + map.set(ransomNote[i], map.get(ransomNote[i]) - 1); + } + + return true; +}; diff --git a/README.md b/README.md index df1f81d6..82dff531 100644 --- a/README.md +++ b/README.md @@ -52,6 +52,7 @@ 347|[Top K Frequent Elements](./0347-top-k-frequent-elements.js)|Medium| 349|[Intersection of Two Arrays](./0349-intersection-of-two-arrays.js)|Easy| 350|[Intersection of Two Arrays II](./0350-intersection-of-two-arrays-ii.js)|Easy| +383|[Ransom Note](./0383-ransom-note.js)|Easy| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| 448|[Find All Numbers Disappeared in an Array](./0448-find-all-numbers-disappeared-in-an-array.js)|Easy| 451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| From 68fe9ef269af16b2d35f68030497bcac12a4993b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 27 Sep 2021 01:33:54 -0400 Subject: [PATCH 121/919] Add solution #442 --- 0442-find-all-duplicates-in-an-array.js | 31 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 0442-find-all-duplicates-in-an-array.js diff --git a/0442-find-all-duplicates-in-an-array.js b/0442-find-all-duplicates-in-an-array.js new file mode 100644 index 00000000..551c3a8e --- /dev/null +++ b/0442-find-all-duplicates-in-an-array.js @@ -0,0 +1,31 @@ +/** + * 442. Find All Duplicates in an Array + * https://leetcode.com/problems/find-all-duplicates-in-an-array/ + * Difficulty: Medium + * + * Given an integer array nums of length n where all the integers of nums + * are in the range [1, n] and each integer appears once or twice, return + * an array of all the integers that appears twice. + * + * You must write an algorithm that runs in O(n) time and uses only constant + * extra space. + */ + +/** + * @param {number[]} nums + * @return {number[]} + */ +var findDuplicates = function(nums) { + const result = []; + + nums.forEach((num, i) => { + const key = Math.abs(num) - 1; + if (nums[key] < 0) { + result.push(Math.abs(num)); + } else { + nums[key] *= -1; + } + }); + + return result; +}; diff --git a/README.md b/README.md index 82dff531..8e79c4d5 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,7 @@ 350|[Intersection of Two Arrays II](./0350-intersection-of-two-arrays-ii.js)|Easy| 383|[Ransom Note](./0383-ransom-note.js)|Easy| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| +442|[Find All Duplicates in an Array](./0442-find-all-duplicates-in-an-array.js)|Medium| 448|[Find All Numbers Disappeared in an Array](./0448-find-all-numbers-disappeared-in-an-array.js)|Easy| 451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| 459|[Repeated Substring Pattern](./0459-repeated-substring-pattern.js)|Easy| From 2c6618efb6c88d1c23d10ba82b180700a18b77c8 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 27 Sep 2021 01:35:53 -0400 Subject: [PATCH 122/919] Add solution #2016 --- ...-difference-between-increasing-elements.js | 26 +++++++++++++++++++ README.md | 1 + 2 files changed, 27 insertions(+) create mode 100644 2016-maximum-difference-between-increasing-elements.js diff --git a/2016-maximum-difference-between-increasing-elements.js b/2016-maximum-difference-between-increasing-elements.js new file mode 100644 index 00000000..18c1a4f4 --- /dev/null +++ b/2016-maximum-difference-between-increasing-elements.js @@ -0,0 +1,26 @@ +/** + * 2016. Maximum Difference Between Increasing Elements + * https://leetcode.com/problems/maximum-difference-between-increasing-elements/ + * Difficulty: Easy + * + * Given a 0-indexed integer array nums of size n, find the maximum difference + * between nums[i] and nums[j] (i.e., nums[j] - nums[i]), such that + * 0 <= i < j < n and nums[i] < nums[j]. + * + * Return the maximum difference. If no such i and j exists, return -1. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var maximumDifference = function(nums) { + let max = 0; + + for (let i = 0, min = nums[0]; i < nums.length; i++) { + min = Math.min(min, nums[i]); + max = Math.max(max, nums[i] - min); + } + + return max === 0 ? -1 : max; +}; diff --git a/README.md b/README.md index 8e79c4d5..c2a273fe 100644 --- a/README.md +++ b/README.md @@ -116,6 +116,7 @@ 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1929|[Concatenation of Array](./1929-concatenation-of-array.js)|Easy| 2000|[Reverse Prefix of Word](./2000-reverse-prefix-of-word.js)|Easy| +2016|[Maximum Difference Between Increasing Elements](./2016-maximum-difference-between-increasing-elements.js)|Easy| ## License From bea154f744355c9f4364b9088c4e84a11aeba1eb Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 27 Sep 2021 01:36:46 -0400 Subject: [PATCH 123/919] Add solution #118 --- 0118-pascals-triangle.js | 27 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 28 insertions(+) create mode 100644 0118-pascals-triangle.js diff --git a/0118-pascals-triangle.js b/0118-pascals-triangle.js new file mode 100644 index 00000000..f2f31523 --- /dev/null +++ b/0118-pascals-triangle.js @@ -0,0 +1,27 @@ +/** + * 118. Pascal's Triangle + * https://leetcode.com/problems/pascals-triangle/ + * Difficulty: Easy + * + * Given an integer numRows, return the first numRows of Pascal's triangle. + * + * In Pascal's triangle, each number is the sum of the two numbers directly + * above it as shown: + */ + +/** + * @param {number} numRows + * @return {number[][]} + */ +var generate = function(numRows) { + const result = [[1]]; + + for (let i = 1; i < numRows; i++) { + result[i] = [1]; + result[i - 1].forEach((value, j, prev) => { + result[i][j + 1] = (prev[j + 1] + value) || 1; + }); + } + + return result; +}; diff --git a/README.md b/README.md index c2a273fe..7e975d07 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,7 @@ 67|[Add Binary](./0067-add-binary.js)|Easy| 73|[Set Matrix Zeroes](./0073-set-matrix-zeroes.js)|Medium| 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| +118|[Pascal's Triangle](./0118-pascals-triangle.js)|Easy| 121|[Best Time to Buy and Sell Stock](./0121-best-time-to-buy-and-sell-stock.js)|Easy| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| From f1af596bb2e57c4f3d1cdbeffa54d2ebad5210f9 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 27 Sep 2021 01:37:28 -0400 Subject: [PATCH 124/919] Add solution #119 --- 0119-pascals-triangle-ii.js | 32 ++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 0119-pascals-triangle-ii.js diff --git a/0119-pascals-triangle-ii.js b/0119-pascals-triangle-ii.js new file mode 100644 index 00000000..94c61352 --- /dev/null +++ b/0119-pascals-triangle-ii.js @@ -0,0 +1,32 @@ +/** + * 119. Pascal's Triangle II + * https://leetcode.com/problems/pascals-triangle-ii/ + * Difficulty: Easy + * + * Given an integer rowIndex, return the rowIndexth (0-indexed) row of + * the Pascal's triangle. + * + * In Pascal's triangle, each number is the sum of the two numbers + * directly above it as shown: + */ + +/** + * @param {number} rowIndex + * @return {number[]} + */ +var getRow = function(rowIndex) { + return generateTriangle(rowIndex + 1)[rowIndex]; +}; + +function generateTriangle(numRows) { + const result = [[1]]; + + for (let i = 1; i < numRows; i++) { + result[i] = [1]; + result[i - 1].forEach((value, j, prev) => { + result[i][j + 1] = (prev[j + 1] + value) || 1; + }); + } + + return result; +}; diff --git a/README.md b/README.md index 7e975d07..7dafb1fc 100644 --- a/README.md +++ b/README.md @@ -37,6 +37,7 @@ 73|[Set Matrix Zeroes](./0073-set-matrix-zeroes.js)|Medium| 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| 118|[Pascal's Triangle](./0118-pascals-triangle.js)|Easy| +119|[Pascal's Triangle II](./0119-pascals-triangle-ii.js)|Easy| 121|[Best Time to Buy and Sell Stock](./0121-best-time-to-buy-and-sell-stock.js)|Easy| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| From 035be28a8c2905a27cdd6cc2ff950dd7da9335e2 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 27 Sep 2021 01:38:30 -0400 Subject: [PATCH 125/919] Add solution #566 --- 0566-reshape-the-matrix.js | 38 ++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 39 insertions(+) create mode 100644 0566-reshape-the-matrix.js diff --git a/0566-reshape-the-matrix.js b/0566-reshape-the-matrix.js new file mode 100644 index 00000000..35660d2f --- /dev/null +++ b/0566-reshape-the-matrix.js @@ -0,0 +1,38 @@ +/** + * 566. Reshape the Matrix + * https://leetcode.com/problems/reshape-the-matrix/ + * Difficulty: Easy + * + * In MATLAB, there is a handy function called reshape which can reshape an m x n + * matrix into a new one with a different size r x c keeping its original data. + * + * You are given an m x n matrix mat and two integers r and c representing the + * number of rows and the number of columns of the wanted reshaped matrix. + * + * The reshaped matrix should be filled with all the elements of the original + * matrix in the same row-traversing order as they were. + * + * If the reshape operation with given parameters is possible and legal, output + * the new reshaped matrix; Otherwise, output the original matrix. + */ + +/** + * @param {number[][]} mat + * @param {number} r + * @param {number} c + * @return {number[][]} + */ +var matrixReshape = function(mat, r, c) { + const flat = mat.flat(); + const result = []; + + if (flat.length !== r * c) { + return mat; + } + + while (flat.length) { + result.push(flat.splice(0, c)); + } + + return result; +}; diff --git a/README.md b/README.md index 7dafb1fc..aa1e8fae 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,7 @@ 459|[Repeated Substring Pattern](./0459-repeated-substring-pattern.js)|Easy| 541|[Reverse String II](./0541-reverse-string-ii.js)|Easy| 565|[Array Nesting](./0565-array-nesting.js)|Medium| +566|[Reshape the Matrix](./0566-reshape-the-matrix.js)|Easy| 606|[Construct String from Binary Tree](./0606-construct-string-from-binary-tree.js)|Easy| 617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy| 628|[Maximum Product of Three Numbers](./0628-maximum-product-of-three-numbers.js)|Easy| From 3cbf944276d5c161b9eb20a1654e2e0474ba9426 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 27 Sep 2021 01:39:15 -0400 Subject: [PATCH 126/919] Add solution #136 --- 0136-single-number.js | 19 +++++++++++++++++++ README.md | 1 + 2 files changed, 20 insertions(+) create mode 100644 0136-single-number.js diff --git a/0136-single-number.js b/0136-single-number.js new file mode 100644 index 00000000..eed32355 --- /dev/null +++ b/0136-single-number.js @@ -0,0 +1,19 @@ +/** + * 136. Single Number + * https://leetcode.com/problems/single-number/ + * Difficulty: Easy + * + * Given a non-empty array of integers nums, every element appears twice + * except for one. Find that single one. + * + * You must implement a solution with a linear runtime complexity and + * use only constant extra space. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var singleNumber = function(nums) { + return nums.reduce((result, num) => result ^= num, 0); +}; diff --git a/README.md b/README.md index aa1e8fae..06fb0efc 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,7 @@ 118|[Pascal's Triangle](./0118-pascals-triangle.js)|Easy| 119|[Pascal's Triangle II](./0119-pascals-triangle-ii.js)|Easy| 121|[Best Time to Buy and Sell Stock](./0121-best-time-to-buy-and-sell-stock.js)|Easy| +136|[Single Number](./0136-single-number.js)|Easy| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| 217|[Contains Duplicate](./0217-contains-duplicate.js)|Easy| From 844525680da52dcc34b775fb58a2842b755f1c07 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 28 Sep 2021 00:35:15 -0400 Subject: [PATCH 127/919] Add solution #83 --- 0083-remove-duplicates-from-sorted-list.js | 38 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 39 insertions(+) create mode 100644 0083-remove-duplicates-from-sorted-list.js diff --git a/0083-remove-duplicates-from-sorted-list.js b/0083-remove-duplicates-from-sorted-list.js new file mode 100644 index 00000000..1bd5a0ad --- /dev/null +++ b/0083-remove-duplicates-from-sorted-list.js @@ -0,0 +1,38 @@ +/** + * 83. Remove Duplicates from Sorted List + * https://leetcode.com/problems/remove-duplicates-from-sorted-list/ + * Difficulty: Easy + * + * Given the head of a sorted linked list, delete all duplicates such that each + * element appears only once. Return the linked list sorted as well. + */ + +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ +var deleteDuplicates = function(head) { + const result = new ListNode(); + const set = new Set(); + let tail = result; + + while (head) { + if (!set.has(head.val)) { + tail.next = new ListNode(head.val); + tail = tail.next; + } + + set.add(head.val); + + head = head.next; + } + + return result.next; +}; diff --git a/README.md b/README.md index 06fb0efc..be04336b 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,7 @@ 66|[Plus One](./0066-plus-one.js)|Easy| 67|[Add Binary](./0067-add-binary.js)|Easy| 73|[Set Matrix Zeroes](./0073-set-matrix-zeroes.js)|Medium| +83|[Remove Duplicates from Sorted List](./0083-remove-duplicates-from-sorted-list.js)|Easy| 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| 118|[Pascal's Triangle](./0118-pascals-triangle.js)|Easy| 119|[Pascal's Triangle II](./0119-pascals-triangle-ii.js)|Easy| From 97dcf402cc67f2f461377703e8431ab7cd77801c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 28 Sep 2021 00:36:10 -0400 Subject: [PATCH 128/919] Add solution #74 --- 0074-search-a-2d-matrix.js | 22 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 0074-search-a-2d-matrix.js diff --git a/0074-search-a-2d-matrix.js b/0074-search-a-2d-matrix.js new file mode 100644 index 00000000..8cb17adb --- /dev/null +++ b/0074-search-a-2d-matrix.js @@ -0,0 +1,22 @@ +/** + * 74. Search a 2D Matrix + * https://leetcode.com/problems/search-a-2d-matrix/ + * Difficulty: Medium + * + * Write an efficient algorithm that searches for a value in an m x n matrix. + * This matrix has the following properties: + * + * Integers in each row are sorted from left to right. + * The first integer of each row is greater than the last integer of the previous row. + */ + +/** + * @param {number[][]} matrix + * @param {number} target + * @return {boolean} + */ +var searchMatrix = function(matrix, target) { + return matrix + .filter(row => row[0] <= target && row[row.length - 1] >= target) + .find(row => row.includes(target)) !== undefined; +}; diff --git a/README.md b/README.md index be04336b..36792e15 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,7 @@ 66|[Plus One](./0066-plus-one.js)|Easy| 67|[Add Binary](./0067-add-binary.js)|Easy| 73|[Set Matrix Zeroes](./0073-set-matrix-zeroes.js)|Medium| +74|[Search a 2D Matrix](./0074-search-a-2d-matrix.js)|Medium| 83|[Remove Duplicates from Sorted List](./0083-remove-duplicates-from-sorted-list.js)|Easy| 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| 118|[Pascal's Triangle](./0118-pascals-triangle.js)|Easy| From f2aff574d79e9b1bd243fcbcfd7a54796cbcb641 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 28 Sep 2021 00:36:56 -0400 Subject: [PATCH 129/919] Add solution #242 --- 0242-valid-anagram.js | 17 +++++++++++++++++ README.md | 1 + 2 files changed, 18 insertions(+) create mode 100644 0242-valid-anagram.js diff --git a/0242-valid-anagram.js b/0242-valid-anagram.js new file mode 100644 index 00000000..e922f3d0 --- /dev/null +++ b/0242-valid-anagram.js @@ -0,0 +1,17 @@ +/** + * 242. Valid Anagram + * https://leetcode.com/problems/valid-anagram/ + * Difficulty: Easy + * + * Given two strings s and t, return true if t is an anagram of s, and false otherwise. + */ + +/** + * @param {string} s + * @param {string} t + * @return {boolean} + */ +var isAnagram = function(s, t) { + const sort = str => str.split('').sort().join(''); + return sort(s) === sort(t); +}; diff --git a/README.md b/README.md index 36792e15..668ac2b8 100644 --- a/README.md +++ b/README.md @@ -48,6 +48,7 @@ 219|[Contains Duplicate II](./0219-contains-duplicate-ii.js)|Easy| 226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy| 234|[Palindrome Linked List](./0234-palindrome-linked-list.js)|Easy| +242|[Valid Anagram](./0242-valid-anagram.js)|Easy| 263|[Ugly Number](./0263-ugly-number.js)|Easy| 264|[Ugly Number II](./0264-ugly-number-ii.js)|Medium| 268|[Missing Number](./0268-missing-number.js)|Easy| From 2781cb6169f2de7910641cbff46d1beb340f201d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 28 Sep 2021 01:11:58 -0400 Subject: [PATCH 130/919] Add solution #141 --- 0141-linked-list-cycle.js | 38 ++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 39 insertions(+) create mode 100644 0141-linked-list-cycle.js diff --git a/0141-linked-list-cycle.js b/0141-linked-list-cycle.js new file mode 100644 index 00000000..8d522ee2 --- /dev/null +++ b/0141-linked-list-cycle.js @@ -0,0 +1,38 @@ +/** + * 141. Linked List Cycle + * https://leetcode.com/problems/linked-list-cycle/ + * Difficulty: Easy + * + * Given head, the head of a linked list, determine if the linked list has a cycle in it. + * + * There is a cycle in a linked list if there is some node in the list that can be reached + * again by continuously following the next pointer. Internally, pos is used to denote the + * index of the node that tail's next pointer is connected to. Note that pos is not passed + * as a parameter. + * + * Return true if there is a cycle in the linked list. Otherwise, return false. + */ + +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ + +/** + * @param {ListNode} head + * @return {boolean} + */ +var hasCycle = function(head) { + while (head) { + if (head.visited) { + return true; + } + head.visited = 1; + head = head.next; + } + + return false; +}; diff --git a/README.md b/README.md index 668ac2b8..675acbe5 100644 --- a/README.md +++ b/README.md @@ -42,6 +42,7 @@ 119|[Pascal's Triangle II](./0119-pascals-triangle-ii.js)|Easy| 121|[Best Time to Buy and Sell Stock](./0121-best-time-to-buy-and-sell-stock.js)|Easy| 136|[Single Number](./0136-single-number.js)|Easy| +141|[Linked List Cycle](./0141-linked-list-cycle.js)|Easy| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| 217|[Contains Duplicate](./0217-contains-duplicate.js)|Easy| From 93af056b3cb84801596fdc1195192a8e35d7f106 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 28 Sep 2021 01:12:43 -0400 Subject: [PATCH 131/919] Add solution #21 --- 0021-merge-two-sorted-lists.js | 35 ++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 36 insertions(+) create mode 100644 0021-merge-two-sorted-lists.js diff --git a/0021-merge-two-sorted-lists.js b/0021-merge-two-sorted-lists.js new file mode 100644 index 00000000..f5c16393 --- /dev/null +++ b/0021-merge-two-sorted-lists.js @@ -0,0 +1,35 @@ +/** + * 21. Merge Two Sorted Lists + * https://leetcode.com/problems/merge-two-sorted-lists/ + * Difficulty: Easy + * + * Merge two sorted linked lists and return it as a sorted list. + * The list should be made by splicing together the nodes of the + * first two lists. + */ + +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} l1 + * @param {ListNode} l2 + * @return {ListNode} + */ +var mergeTwoLists = function(l1, l2) { + if (!l1 || !l2) { + return l1 || l2; + } + + if (l1.val > l2.val) { + [l2, l1] = [l1, l2]; + } + + l1.next = mergeTwoLists(l1.next, l2); + + return l1; +}; diff --git a/README.md b/README.md index 675acbe5..b11412d5 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ 13|[Roman to Integer](./0013-roman-to-integer.js)|Easy| 14|[Longest Common Prefix](./0014-longest-common-prefix.js)|Easy| 17|[Letter Combinations of a Phone Number](./0017-letter-combinations-of-a-phone-number.js)|Medium| +21|[Merge Two Sorted Lists](./0021-merge-two-sorted-lists.js)|Easy| 27|[Remove Element](./0027-remove-element.js)|Easy| 31|[Next Permutation](./0031-next-permutation.js)|Medium| 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| From da51e8b93085de8bd578343bf338ed43fd99d109 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 29 Sep 2021 23:45:57 -0400 Subject: [PATCH 132/919] Add solution #203 --- 0203-remove-linked-list-elements.js | 27 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 28 insertions(+) create mode 100644 0203-remove-linked-list-elements.js diff --git a/0203-remove-linked-list-elements.js b/0203-remove-linked-list-elements.js new file mode 100644 index 00000000..e305011f --- /dev/null +++ b/0203-remove-linked-list-elements.js @@ -0,0 +1,27 @@ +/** + * 203. Remove Linked List Elements + * https://leetcode.com/problems/remove-linked-list-elements/ + * Difficulty: Easy + * + * Given the head of a linked list and an integer val, remove all the + * nodes of the linked list that has Node.val == val, and return the + * new head. + */ + +/** + * 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} val + * @return {ListNode} + */ +var removeElements = function(head, val) { + if (!head) return null; + head.next = removeElements(head.next, val); + return head.val === val ? head.next : head; +}; diff --git a/README.md b/README.md index b11412d5..3b025879 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,7 @@ 141|[Linked List Cycle](./0141-linked-list-cycle.js)|Easy| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| +203|[Remove Linked List Elements](./0203-remove-linked-list-elements.js)|Easy| 217|[Contains Duplicate](./0217-contains-duplicate.js)|Easy| 219|[Contains Duplicate II](./0219-contains-duplicate-ii.js)|Easy| 226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy| From df880399a51ca734607e3c2dcc567d4ef9d96548 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 30 Sep 2021 20:32:57 -0400 Subject: [PATCH 133/919] Add solution #206 --- 0206-reverse-linked-list.js | 32 ++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 0206-reverse-linked-list.js diff --git a/0206-reverse-linked-list.js b/0206-reverse-linked-list.js new file mode 100644 index 00000000..c1b3e19a --- /dev/null +++ b/0206-reverse-linked-list.js @@ -0,0 +1,32 @@ +/** + * 206. Reverse Linked List + * https://leetcode.com/problems/reverse-linked-list/ + * Difficulty: Easy + * + * Given the head of a singly linked list, reverse the list, and return the reversed 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 reverseList = function(head) { + let prev = null; + let tail = head; + + while (tail) { + const next = tail.next; + tail.next = prev; + prev = tail; + tail = next; + } + + return prev; +}; diff --git a/README.md b/README.md index 3b025879..8e8a0e31 100644 --- a/README.md +++ b/README.md @@ -47,6 +47,7 @@ 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| 203|[Remove Linked List Elements](./0203-remove-linked-list-elements.js)|Easy| +206|[Reverse Linked List](./0206-reverse-linked-list.js)|Easy| 217|[Contains Duplicate](./0217-contains-duplicate.js)|Easy| 219|[Contains Duplicate II](./0219-contains-duplicate-ii.js)|Easy| 226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy| From add48a1d89499da93f191a48f2e406689ba936ab Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 30 Sep 2021 20:34:19 -0400 Subject: [PATCH 134/919] Add solution #237 --- 0237-delete-node-in-a-linked-list.js | 27 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 28 insertions(+) create mode 100644 0237-delete-node-in-a-linked-list.js diff --git a/0237-delete-node-in-a-linked-list.js b/0237-delete-node-in-a-linked-list.js new file mode 100644 index 00000000..d3d89b9b --- /dev/null +++ b/0237-delete-node-in-a-linked-list.js @@ -0,0 +1,27 @@ +/** + * 237. Delete Node in a Linked List + * https://leetcode.com/problems/delete-node-in-a-linked-list/ + * Difficulty: Easy + * + * Write a function to delete a node in a singly-linked list. You will not be + * given access to the head of the list, instead you will be given access to + * the node to be deleted directly. + * + * It is guaranteed that the node to be deleted is not a tail node in the list. + */ + +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ +/** + * @param {ListNode} node + * @return {void} Do not return anything, modify node in-place instead. + */ +var deleteNode = function(node) { + node.val = node.next.val; + node.next = node.next.next; +}; diff --git a/README.md b/README.md index 8e8a0e31..468b19ea 100644 --- a/README.md +++ b/README.md @@ -52,6 +52,7 @@ 219|[Contains Duplicate II](./0219-contains-duplicate-ii.js)|Easy| 226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy| 234|[Palindrome Linked List](./0234-palindrome-linked-list.js)|Easy| +237|[Delete Node in a Linked List](./0237-delete-node-in-a-linked-list.js)|Easy| 242|[Valid Anagram](./0242-valid-anagram.js)|Easy| 263|[Ugly Number](./0263-ugly-number.js)|Easy| 264|[Ugly Number II](./0264-ugly-number-ii.js)|Medium| From 853d7b2410cb0c63fcdfb83a535119453e120d7d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 30 Sep 2021 20:35:20 -0400 Subject: [PATCH 135/919] Add solution #20 --- 0020-valid-parentheses.js | 37 +++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 38 insertions(+) create mode 100644 0020-valid-parentheses.js diff --git a/0020-valid-parentheses.js b/0020-valid-parentheses.js new file mode 100644 index 00000000..bc7a1752 --- /dev/null +++ b/0020-valid-parentheses.js @@ -0,0 +1,37 @@ +/** + * 20. Valid Parentheses + * https://leetcode.com/problems/valid-parentheses/ + * Difficulty: Easy + * + * Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', + * determine if the input string is valid. + * + * An input string is valid if: + * - Open brackets must be closed by the same type of brackets. + * - Open brackets must be closed in the correct order. + */ + +/** + * @param {string} s + * @return {boolean} + */ +var isValid = function(s) { + const map = { + '(': ')', + '[': ']', + '{': '}' + } + const stack = []; + + for (let i = 0; i < s.length; i++) { + if (map[s[i]]) { + stack.push(map[s[i]]); + } else { + if (stack.pop() !== s[i]) { + return false; + } + } + } + + return stack.length === 0; +}; diff --git a/README.md b/README.md index 468b19ea..427da6bd 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ 13|[Roman to Integer](./0013-roman-to-integer.js)|Easy| 14|[Longest Common Prefix](./0014-longest-common-prefix.js)|Easy| 17|[Letter Combinations of a Phone Number](./0017-letter-combinations-of-a-phone-number.js)|Medium| +20|[Valid Parentheses](./0020-valid-parentheses.js)|Easy| 21|[Merge Two Sorted Lists](./0021-merge-two-sorted-lists.js)|Easy| 27|[Remove Element](./0027-remove-element.js)|Easy| 31|[Next Permutation](./0031-next-permutation.js)|Medium| From 175cb74f0f7e6a89d4d894e960edb7f620af2846 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 1 Oct 2021 20:40:39 -0400 Subject: [PATCH 136/919] Add solution #144 --- 0144-binary-tree-preorder-traversal.js | 25 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 26 insertions(+) create mode 100644 0144-binary-tree-preorder-traversal.js diff --git a/0144-binary-tree-preorder-traversal.js b/0144-binary-tree-preorder-traversal.js new file mode 100644 index 00000000..882ba125 --- /dev/null +++ b/0144-binary-tree-preorder-traversal.js @@ -0,0 +1,25 @@ +/** + * 144. Binary Tree Preorder Traversal + * https://leetcode.com/problems/binary-tree-preorder-traversal/ + * Difficulty: Easy + * + * Given the root of a binary tree, return the preorder traversal of its nodes' values. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number[]} + */ +var preorderTraversal = function(root) { + return root + ? [root.val, ...preorderTraversal(root.left), ...preorderTraversal(root.right)] + : []; +}; diff --git a/README.md b/README.md index 427da6bd..095c99a1 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,7 @@ 121|[Best Time to Buy and Sell Stock](./0121-best-time-to-buy-and-sell-stock.js)|Easy| 136|[Single Number](./0136-single-number.js)|Easy| 141|[Linked List Cycle](./0141-linked-list-cycle.js)|Easy| +144|[Binary Tree Preorder Traversal](./0144-binary-tree-preorder-traversal.js)|Easy| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| 203|[Remove Linked List Elements](./0203-remove-linked-list-elements.js)|Easy| From d9dad63e610818d8b1486cc5795a56264cdcd67a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 1 Oct 2021 20:41:32 -0400 Subject: [PATCH 137/919] Add solution #94 --- 0094-binary-tree-inorder-traversal.js | 37 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 38 insertions(+) create mode 100644 0094-binary-tree-inorder-traversal.js diff --git a/0094-binary-tree-inorder-traversal.js b/0094-binary-tree-inorder-traversal.js new file mode 100644 index 00000000..aa0510c1 --- /dev/null +++ b/0094-binary-tree-inorder-traversal.js @@ -0,0 +1,37 @@ +/** + * 94. Binary Tree Inorder Traversal + * https://leetcode.com/problems/binary-tree-inorder-traversal/ + * Difficulty: Easy + * + * Given the root of a binary tree, return the inorder traversal of its nodes' values. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number[]} + */ +var inorderTraversal = function(root) { + const result = []; + const stack = []; + + while (root || stack.length) { + if (root) { + stack.push(root); + root = root.left; + } else { + const { val, right } = stack.pop(); + result.push(val); + root = right; + } + } + + return result; +}; diff --git a/README.md b/README.md index 095c99a1..6c4439bc 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,7 @@ 74|[Search a 2D Matrix](./0074-search-a-2d-matrix.js)|Medium| 83|[Remove Duplicates from Sorted List](./0083-remove-duplicates-from-sorted-list.js)|Easy| 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| +94|[Binary Tree Inorder Traversal](./0094-binary-tree-inorder-traversal.js)|Easy| 118|[Pascal's Triangle](./0118-pascals-triangle.js)|Easy| 119|[Pascal's Triangle II](./0119-pascals-triangle-ii.js)|Easy| 121|[Best Time to Buy and Sell Stock](./0121-best-time-to-buy-and-sell-stock.js)|Easy| From 6a7410fffdda37b5803e2638e773ccf49f177c33 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 1 Oct 2021 20:46:39 -0400 Subject: [PATCH 138/919] Add solution #1356 --- 1356-sort-integers-by-the-number-of-1-bits.js | 22 +++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 1356-sort-integers-by-the-number-of-1-bits.js diff --git a/1356-sort-integers-by-the-number-of-1-bits.js b/1356-sort-integers-by-the-number-of-1-bits.js new file mode 100644 index 00000000..6565d125 --- /dev/null +++ b/1356-sort-integers-by-the-number-of-1-bits.js @@ -0,0 +1,22 @@ +/** + * 1356. Sort Integers by The Number of 1 Bits + * https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/ + * Difficulty: Easy + * + * Given an integer array arr. You have to sort the integers in the array in + * ascending order by the number of 1's in their binary representation and + * in case of two or more integers have the same number of 1's you have to + * sort them in ascending order. + * + * Return the sorted array. + */ + +/** + * @param {number[]} arr + * @return {number[]} + */ +var sortByBits = function(arr) { + const getCount = n => n.toString(2).replace(/0/g, '').length; + + return arr.sort((a, b) => getCount(a) - getCount(b) || a - b); +}; diff --git a/README.md b/README.md index 6c4439bc..4761388f 100644 --- a/README.md +++ b/README.md @@ -125,6 +125,7 @@ 1324|[Print Words Vertically](./1324-print-words-vertically.js)|Medium| 1332|[Remove Palindromic Subsequences](./1332-remove-palindromic-subsequences.js)|Easy| 1333|[Filter Restaurants by Vegan-Friendly, Price and Distance](./1333-filter-restaurants-by-vegan-friendly-price-and-distance.js)|Medium| +1356|[Sort Integers by The Number of 1 Bits](./1356-sort-integers-by-the-number-of-1-bits.js)|Easy| 1360|[Number of Days Between Two Dates](./1360-number-of-days-between-two-dates.js)|Easy| 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| From 4930965594180d059ae8c055f700b603d1e33746 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 1 Oct 2021 20:50:48 -0400 Subject: [PATCH 139/919] Add solution #1351 --- ...unt-negative-numbers-in-a-sorted-matrix.js | 21 +++++++++++++++++++ README.md | 1 + 2 files changed, 22 insertions(+) create mode 100644 1351-count-negative-numbers-in-a-sorted-matrix.js diff --git a/1351-count-negative-numbers-in-a-sorted-matrix.js b/1351-count-negative-numbers-in-a-sorted-matrix.js new file mode 100644 index 00000000..d232bb99 --- /dev/null +++ b/1351-count-negative-numbers-in-a-sorted-matrix.js @@ -0,0 +1,21 @@ +/** + * 1351. Count Negative Numbers in a Sorted Matrix + * https://leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix/ + * Difficulty: Easy + * + * Given a m x n matrix grid which is sorted in non-increasing order both + * row-wise and column-wise, return the number of negative numbers in grid. + */ + +/** + * @param {number[][]} grid + * @return {number} + */ +var countNegatives = function(grid) { + return grid.reduce((count, row) => { + while (row.pop() < 0) { + count++; + } + return count; + }, 0); +}; diff --git a/README.md b/README.md index 4761388f..46dab742 100644 --- a/README.md +++ b/README.md @@ -125,6 +125,7 @@ 1324|[Print Words Vertically](./1324-print-words-vertically.js)|Medium| 1332|[Remove Palindromic Subsequences](./1332-remove-palindromic-subsequences.js)|Easy| 1333|[Filter Restaurants by Vegan-Friendly, Price and Distance](./1333-filter-restaurants-by-vegan-friendly-price-and-distance.js)|Medium| +1351|[Count Negative Numbers in a Sorted Matrix](./1351-count-negative-numbers-in-a-sorted-matrix.js)|Easy| 1356|[Sort Integers by The Number of 1 Bits](./1356-sort-integers-by-the-number-of-1-bits.js)|Easy| 1360|[Number of Days Between Two Dates](./1360-number-of-days-between-two-dates.js)|Easy| 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| From aaa8743b148f01b7c385641806a30b8f8d4210c2 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 1 Oct 2021 20:53:08 -0400 Subject: [PATCH 140/919] Add solution #1295 --- 1295-find-numbers-with-even-number-of-digits.js | 16 ++++++++++++++++ README.md | 1 + 2 files changed, 17 insertions(+) create mode 100644 1295-find-numbers-with-even-number-of-digits.js diff --git a/1295-find-numbers-with-even-number-of-digits.js b/1295-find-numbers-with-even-number-of-digits.js new file mode 100644 index 00000000..2683787d --- /dev/null +++ b/1295-find-numbers-with-even-number-of-digits.js @@ -0,0 +1,16 @@ +/** + * 1295. Find Numbers with Even Number of Digits + * https://leetcode.com/problems/find-numbers-with-even-number-of-digits/ + * Difficulty: Easy + * + * Given an array nums of integers, return how many of them contain an even + * number of digits. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var findNumbers = function(nums) { + return nums.filter(num => String(num).length % 2 === 0).length; +}; diff --git a/README.md b/README.md index 46dab742..ec24f6a0 100644 --- a/README.md +++ b/README.md @@ -115,6 +115,7 @@ 1290|[Convert Binary Number in a Linked List to Integer](./1290-convert-binary-number-in-a-linked-list-to-integer.js)|Easy| 1291|[Sequential Digits](./1291-sequential-digits.js)|Medium| 1292|[Maximum Side Length of a Square with Sum Less than or Equal to Threshold](./1292-maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold.js)|Medium| +1295|[Find Numbers with Even Number of Digits](./1295-find-numbers-with-even-number-of-digits.js)|Easy| 1297|[Maximum Number of Occurrences of a Substring](./1297-maximum-number-of-occurrences-of-a-substring.js)|Medium| 1304|[Find N Unique Integers Sum up to Zero](./1304-find-n-unique-integers-sum-up-to-zero.js)|Easy| 1309|[Decrypt String from Alphabet to Integer Mapping](./1309-decrypt-string-from-alphabet-to-integer-mapping.js)|Easy| From 3e935d89d9d48e2a8f918da10454210121f60ec3 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 1 Oct 2021 20:55:10 -0400 Subject: [PATCH 141/919] Add solution #1296 --- ...-array-in-sets-of-k-consecutive-numbers.js | 40 +++++++++++++++++++ README.md | 1 + 2 files changed, 41 insertions(+) create mode 100644 1296-divide-array-in-sets-of-k-consecutive-numbers.js diff --git a/1296-divide-array-in-sets-of-k-consecutive-numbers.js b/1296-divide-array-in-sets-of-k-consecutive-numbers.js new file mode 100644 index 00000000..45719c06 --- /dev/null +++ b/1296-divide-array-in-sets-of-k-consecutive-numbers.js @@ -0,0 +1,40 @@ +/** + * 1296. Divide Array in Sets of K Consecutive Numbers + * https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/ + * Difficulty: Medium + * + * Given an array of integers nums and a positive integer k, find whether it is + * possible to divide this array into sets of k consecutive numbers. + * + * Return true if it is possible. Otherwise, return false. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {boolean} + */ +var isPossibleDivide = function(nums, k) { + if (nums.length % k) { + return false; + } + + const map = {}; + const set = new Set(nums); + nums.forEach(x => map[x] ? map[x]++ : map[x] = 1); + + let count = nums.length / k; + while (count--) { + let min = Math.min(...set); + for (let i = min; i < min + k; i++) { + if (!map[i]) { + return false; + } + if (!--map[i]) { + set.delete(i); + } + } + } + + return true; +}; diff --git a/README.md b/README.md index ec24f6a0..7da5cb51 100644 --- a/README.md +++ b/README.md @@ -116,6 +116,7 @@ 1291|[Sequential Digits](./1291-sequential-digits.js)|Medium| 1292|[Maximum Side Length of a Square with Sum Less than or Equal to Threshold](./1292-maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold.js)|Medium| 1295|[Find Numbers with Even Number of Digits](./1295-find-numbers-with-even-number-of-digits.js)|Easy| +1296|[Divide Array in Sets of K Consecutive Numbers](./1296-divide-array-in-sets-of-k-consecutive-numbers.js)|Medium| 1297|[Maximum Number of Occurrences of a Substring](./1297-maximum-number-of-occurrences-of-a-substring.js)|Medium| 1304|[Find N Unique Integers Sum up to Zero](./1304-find-n-unique-integers-sum-up-to-zero.js)|Easy| 1309|[Decrypt String from Alphabet to Integer Mapping](./1309-decrypt-string-from-alphabet-to-integer-mapping.js)|Easy| From 8ed36d4513040c2a67e4f89f3c3848a054f9e711 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 1 Oct 2021 20:56:32 -0400 Subject: [PATCH 142/919] Add solution #846 --- 0846-hand-of-straights.js | 43 +++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 44 insertions(+) create mode 100644 0846-hand-of-straights.js diff --git a/0846-hand-of-straights.js b/0846-hand-of-straights.js new file mode 100644 index 00000000..4a2bf2b1 --- /dev/null +++ b/0846-hand-of-straights.js @@ -0,0 +1,43 @@ +/** + * 846. Hand of Straights + * https://leetcode.com/problems/hand-of-straights/ + * Difficulty: Medium + * + * 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. + */ + +/** + * @param {number[]} hand + * @param {number} groupSize + * @return {boolean} + */ +var isNStraightHand = function(hand, groupSize) { + if (hand.length % groupSize) { + return false; + } + + const map = {}; + const set = new Set(hand); + hand.forEach(x => map[x] ? map[x]++ : map[x] = 1); + + let count = hand.length / groupSize; + while (count--) { + let min = Math.min(...set); + for (let i = min; i < min + groupSize; i++) { + if (!map[i]) { + return false; + } + if (!--map[i]) { + set.delete(i); + } + } + } + + return true; +}; diff --git a/README.md b/README.md index 7da5cb51..833fe508 100644 --- a/README.md +++ b/README.md @@ -89,6 +89,7 @@ 824|[Goat Latin](./0824-goat-latin.js)|Easy| 831|[Masking Personal Information](./0831-masking-personal-information.js)|Medium| 844|[Backspace String Compare](./0844-backspace-string-compare.js)|Easy| +846|[Hand of Straights](./0846-hand-of-straights.js)|Medium| 867|[Transpose Matrix](./0867-transpose-matrix.js)|Easy| 884|[Uncommon Words from Two Sentences](./0884-uncommon-words-from-two-sentences.js)|Easy| 890|[Find and Replace Pattern](./0890-find-and-replace-pattern.js)|Medium| From d135e7644948bb0108071ac0b474bb5079ba64b7 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 2 Oct 2021 19:01:59 -0400 Subject: [PATCH 143/919] Add solution #225 --- 0225-implement-stack-using-queues.js | 59 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 60 insertions(+) create mode 100644 0225-implement-stack-using-queues.js diff --git a/0225-implement-stack-using-queues.js b/0225-implement-stack-using-queues.js new file mode 100644 index 00000000..71bb7bd8 --- /dev/null +++ b/0225-implement-stack-using-queues.js @@ -0,0 +1,59 @@ +/** + * 225. Implement Stack using Queues + * https://leetcode.com/problems/implement-stack-using-queues/ + * Difficulty: Easy + * + * Implement a last-in-first-out (LIFO) stack using only two queues. + * The implemented stack should support all the functions of a normal + * stack (push, top, pop, and empty). + * + * Implement the MyStack class: + * + * - void push(int x) Pushes element x to the top of the stack. + * - int pop() Removes the element on the top of the stack and returns it. + * - int top() Returns the element on the top of the stack. + * - boolean empty() Returns true if the stack is empty, false otherwise. + */ + + +var MyStack = function() { + this.data = []; +}; + +/** + * @param {number} x + * @return {void} + */ +MyStack.prototype.push = function(x) { + this.data.push(x); +}; + +/** + * @return {number} + */ +MyStack.prototype.pop = function() { + return this.data.pop(); +}; + +/** + * @return {number} + */ +MyStack.prototype.top = function() { + return this.data[this.data.length - 1]; +}; + +/** + * @return {boolean} + */ +MyStack.prototype.empty = function() { + return !this.data.length; +}; + +/** + * Your MyStack object will be instantiated and called as such: + * var obj = new MyStack() + * obj.push(x) + * var param_2 = obj.pop() + * var param_3 = obj.top() + * var param_4 = obj.empty() + */ diff --git a/README.md b/README.md index 833fe508..6cf3ac92 100644 --- a/README.md +++ b/README.md @@ -53,6 +53,7 @@ 206|[Reverse Linked List](./0206-reverse-linked-list.js)|Easy| 217|[Contains Duplicate](./0217-contains-duplicate.js)|Easy| 219|[Contains Duplicate II](./0219-contains-duplicate-ii.js)|Easy| +225|[Implement Stack using Queues](./0225-implement-stack-using-queues.js)|Easy| 226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy| 234|[Palindrome Linked List](./0234-palindrome-linked-list.js)|Easy| 237|[Delete Node in a Linked List](./0237-delete-node-in-a-linked-list.js)|Easy| From 553a14439a3d19fa8e479587a4d70e4824d2a91b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 2 Oct 2021 19:03:04 -0400 Subject: [PATCH 144/919] Add solution #232 --- 0232-implement-queue-using-stacks.js | 58 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 59 insertions(+) create mode 100644 0232-implement-queue-using-stacks.js diff --git a/0232-implement-queue-using-stacks.js b/0232-implement-queue-using-stacks.js new file mode 100644 index 00000000..7a152a5a --- /dev/null +++ b/0232-implement-queue-using-stacks.js @@ -0,0 +1,58 @@ +/** + * 232. Implement Queue using Stacks + * https://leetcode.com/problems/implement-queue-using-stacks/ + * Difficulty: Easy + * + * Implement a first in first out (FIFO) queue using only two stacks. + * The implemented queue should support all the functions of a normal + * queue (push, peek, pop, and empty). + * + * Implement the MyQueue class: + * - void push(int x) Pushes element x to the back of the queue. + * - int pop() Removes the element from the front of the queue and returns it. + * - int peek() Returns the element at the front of the queue. + * - boolean empty() Returns true if the queue is empty, false otherwise. + */ + + +var MyQueue = function() { + this.data = []; +}; + +/** + * @param {number} x + * @return {void} + */ +MyQueue.prototype.push = function(x) { + this.data.push(x); +}; + +/** + * @return {number} + */ +MyQueue.prototype.pop = function() { + return this.data.shift(); +}; + +/** + * @return {number} + */ +MyQueue.prototype.peek = function() { + return this.data[0]; +}; + +/** + * @return {boolean} + */ +MyQueue.prototype.empty = function() { + return !this.data.length; +}; + +/** + * Your MyQueue object will be instantiated and called as such: + * var obj = new MyQueue() + * obj.push(x) + * var param_2 = obj.pop() + * var param_3 = obj.peek() + * var param_4 = obj.empty() + */ diff --git a/README.md b/README.md index 6cf3ac92..71fcdbf8 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,7 @@ 219|[Contains Duplicate II](./0219-contains-duplicate-ii.js)|Easy| 225|[Implement Stack using Queues](./0225-implement-stack-using-queues.js)|Easy| 226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy| +232|[Implement Queue using Stacks](./0232-implement-queue-using-stacks.js)|Easy| 234|[Palindrome Linked List](./0234-palindrome-linked-list.js)|Easy| 237|[Delete Node in a Linked List](./0237-delete-node-in-a-linked-list.js)|Easy| 242|[Valid Anagram](./0242-valid-anagram.js)|Easy| From 2b81e0939b40702f3e2573beee8cb0bf7f01020f Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 2 Oct 2021 21:23:05 -0400 Subject: [PATCH 145/919] Add solution #145 --- 0145-binary-tree-postorder-traversal.js | 32 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 0145-binary-tree-postorder-traversal.js diff --git a/0145-binary-tree-postorder-traversal.js b/0145-binary-tree-postorder-traversal.js new file mode 100644 index 00000000..06c23f9c --- /dev/null +++ b/0145-binary-tree-postorder-traversal.js @@ -0,0 +1,32 @@ +/** + * 145. Binary Tree Postorder Traversal + * https://leetcode.com/problems/binary-tree-postorder-traversal/ + * Difficulty: Easy + * + * Given the root of a binary tree, return the postorder traversal + * of its nodes' values. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number[]} + */ +var postorderTraversal = function(root) { + if (!root) { + return []; + } + + return [ + ...postorderTraversal(root.left), + ...postorderTraversal(root.right), + root.val + ]; +}; diff --git a/README.md b/README.md index 71fcdbf8..0950a05b 100644 --- a/README.md +++ b/README.md @@ -47,6 +47,7 @@ 136|[Single Number](./0136-single-number.js)|Easy| 141|[Linked List Cycle](./0141-linked-list-cycle.js)|Easy| 144|[Binary Tree Preorder Traversal](./0144-binary-tree-preorder-traversal.js)|Easy| +145|[Binary Tree Postorder Traversal](./0145-binary-tree-postorder-traversal.js)|Easy| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| 203|[Remove Linked List Elements](./0203-remove-linked-list-elements.js)|Easy| From cdfc6e64bd973769660b5e2602edd1fc56f0eac8 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 3 Oct 2021 14:27:29 -0400 Subject: [PATCH 146/919] Add solution #102 --- 0102-binary-tree-level-order-traversal.js | 40 +++++++++++++++++++++++ README.md | 1 + 2 files changed, 41 insertions(+) create mode 100644 0102-binary-tree-level-order-traversal.js diff --git a/0102-binary-tree-level-order-traversal.js b/0102-binary-tree-level-order-traversal.js new file mode 100644 index 00000000..eb34e09b --- /dev/null +++ b/0102-binary-tree-level-order-traversal.js @@ -0,0 +1,40 @@ +/** + * 102. Binary Tree Level Order Traversal + * https://leetcode.com/problems/binary-tree-level-order-traversal/ + * Difficulty: Medium + * + * Given the root of a binary tree, return the level order traversal of its + * nodes' values. (i.e., from left to right, level by level). + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number[][]} + */ +var levelOrder = function(root) { + const result = []; + + traverse(result, root); + + return result; +}; + +function traverse(result, node, level = 0) { + if (!node) { + return []; + } + + result[level] = result[level] || []; + result[level].push(node.val); + + traverse(result, node.left, level + 1); + traverse(result, node.right, level + 1); +} diff --git a/README.md b/README.md index 0950a05b..c6e67cc1 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,7 @@ 83|[Remove Duplicates from Sorted List](./0083-remove-duplicates-from-sorted-list.js)|Easy| 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| 94|[Binary Tree Inorder Traversal](./0094-binary-tree-inorder-traversal.js)|Easy| +102|[Binary Tree Level Order Traversal](./0102-binary-tree-level-order-traversal.js)|Medium| 118|[Pascal's Triangle](./0118-pascals-triangle.js)|Easy| 119|[Pascal's Triangle II](./0119-pascals-triangle-ii.js)|Easy| 121|[Best Time to Buy and Sell Stock](./0121-best-time-to-buy-and-sell-stock.js)|Easy| From b53f63caa6e11da9100365fe081a1e1ff654e02d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 3 Oct 2021 14:28:31 -0400 Subject: [PATCH 147/919] Add solution #111 --- 0111-minimum-depth-of-binary-tree.js | 32 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 0111-minimum-depth-of-binary-tree.js diff --git a/0111-minimum-depth-of-binary-tree.js b/0111-minimum-depth-of-binary-tree.js new file mode 100644 index 00000000..c0abee2b --- /dev/null +++ b/0111-minimum-depth-of-binary-tree.js @@ -0,0 +1,32 @@ +/** + * 111. Minimum Depth of Binary Tree + * https://leetcode.com/problems/minimum-depth-of-binary-tree/ + * Difficulty: Easy + * + * Given a binary tree, find its minimum depth. + * + * The minimum depth is the number of nodes along the shortest path from the + * root node down to the nearest leaf node. + * + * Note: A leaf is a node with no children. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number} + */ +var minDepth = function(root) { + if (!root) { + return 0; + } + const [left, right] = [root.left, root.right].map(minDepth); + return 1 + (Math.min(left, right) || Math.max(left, right)); +}; diff --git a/README.md b/README.md index c6e67cc1..6ac28654 100644 --- a/README.md +++ b/README.md @@ -42,6 +42,7 @@ 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| 94|[Binary Tree Inorder Traversal](./0094-binary-tree-inorder-traversal.js)|Easy| 102|[Binary Tree Level Order Traversal](./0102-binary-tree-level-order-traversal.js)|Medium| +111|[Minimum Depth of Binary Tree](./0111-minimum-depth-of-binary-tree.js)|Easy| 118|[Pascal's Triangle](./0118-pascals-triangle.js)|Easy| 119|[Pascal's Triangle II](./0119-pascals-triangle-ii.js)|Easy| 121|[Best Time to Buy and Sell Stock](./0121-best-time-to-buy-and-sell-stock.js)|Easy| From a3f9471ba71d10840bc9f1eaca3b2562043d20d7 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 3 Oct 2021 14:29:19 -0400 Subject: [PATCH 148/919] Add solution #104 --- 0104-maximum-depth-of-binary-tree.js | 30 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 0104-maximum-depth-of-binary-tree.js diff --git a/0104-maximum-depth-of-binary-tree.js b/0104-maximum-depth-of-binary-tree.js new file mode 100644 index 00000000..8b7858e0 --- /dev/null +++ b/0104-maximum-depth-of-binary-tree.js @@ -0,0 +1,30 @@ +/** + * 104. Maximum Depth of Binary Tree + * https://leetcode.com/problems/maximum-depth-of-binary-tree/ + * Difficulty: Easy + * + * Given the root of a binary tree, return its maximum depth. + * + * A binary tree's maximum depth is the number of nodes along the longest + * path from the root node down to the farthest leaf node. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number} + */ +var maxDepth = function(root) { + if (!root) { + return 0; + } + const [left, right] = [root.left, root.right].map(maxDepth); + return 1 + Math.max(left, right); +}; diff --git a/README.md b/README.md index 6ac28654..1b7c1d30 100644 --- a/README.md +++ b/README.md @@ -42,6 +42,7 @@ 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| 94|[Binary Tree Inorder Traversal](./0094-binary-tree-inorder-traversal.js)|Easy| 102|[Binary Tree Level Order Traversal](./0102-binary-tree-level-order-traversal.js)|Medium| +104|[Maximum Depth of Binary Tree](./0104-maximum-depth-of-binary-tree.js)|Easy| 111|[Minimum Depth of Binary Tree](./0111-minimum-depth-of-binary-tree.js)|Easy| 118|[Pascal's Triangle](./0118-pascals-triangle.js)|Easy| 119|[Pascal's Triangle II](./0119-pascals-triangle-ii.js)|Easy| From 4473e367af4ff4f5e9facf8f3c7a88f09a298907 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 4 Oct 2021 20:55:10 -0400 Subject: [PATCH 149/919] Add solution #112 --- 0112-path-sum.js | 44 ++++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 45 insertions(+) create mode 100644 0112-path-sum.js diff --git a/0112-path-sum.js b/0112-path-sum.js new file mode 100644 index 00000000..c4f37a2f --- /dev/null +++ b/0112-path-sum.js @@ -0,0 +1,44 @@ +/** + * 112. Path Sum + * https://leetcode.com/problems/path-sum/ + * Difficulty: Easy + * + * Given the root of a binary tree and an integer targetSum, return true if the + * tree has a root-to-leaf path such that adding up all the values along the + * path equals targetSum. + * + * A leaf is a node with no children. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @param {number} targetSum + * @return {boolean} + */ +var hasPathSum = function(root, targetSum) { + if (!root) { + return false; + } + const result = []; + + traverse(result, root); + + return result.includes(targetSum); +}; + +function traverse(result, node, sum = 0) { + if (!node.left && !node.right) { + result.push(sum + node.val); + } + + if (node.left) traverse(result, node.left, sum + node.val); + if (node.right) traverse(result, node.right, sum + node.val); +} diff --git a/README.md b/README.md index 1b7c1d30..86d9bd64 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,7 @@ 102|[Binary Tree Level Order Traversal](./0102-binary-tree-level-order-traversal.js)|Medium| 104|[Maximum Depth of Binary Tree](./0104-maximum-depth-of-binary-tree.js)|Easy| 111|[Minimum Depth of Binary Tree](./0111-minimum-depth-of-binary-tree.js)|Easy| +112|[Path Sum](./0112-path-sum.js)|Easy| 118|[Pascal's Triangle](./0118-pascals-triangle.js)|Easy| 119|[Pascal's Triangle II](./0119-pascals-triangle-ii.js)|Easy| 121|[Best Time to Buy and Sell Stock](./0121-best-time-to-buy-and-sell-stock.js)|Easy| From ca0e5a068e54079466e72f359a2cbf7ea72e2f85 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 4 Oct 2021 20:56:21 -0400 Subject: [PATCH 150/919] Add solution #653 --- 0653-two-sum-iv---input-is-a-bst.js | 36 +++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 37 insertions(+) create mode 100644 0653-two-sum-iv---input-is-a-bst.js diff --git a/0653-two-sum-iv---input-is-a-bst.js b/0653-two-sum-iv---input-is-a-bst.js new file mode 100644 index 00000000..6f3b4256 --- /dev/null +++ b/0653-two-sum-iv---input-is-a-bst.js @@ -0,0 +1,36 @@ +/** + * 653. Two Sum IV - Input is a BST + * https://leetcode.com/problems/two-sum-iv-input-is-a-bst/ + * Difficulty: Easy + * + * Given the root of a Binary Search Tree and a target number k, return + * true if there exist two elements in the BST such that their sum is + * equal to the given target. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @param {number} k + * @return {boolean} + */ +var findTarget = function(root, k) { + const set = new Set(); + return dfs(set, root, k); +}; + +function dfs(set, node, k) { + if (!node) return false; + if (set.has(k - node.val)) return true; + + set.add(node.val); + + return dfs(set, node.left, k) || dfs(set, node.right, k); +} diff --git a/README.md b/README.md index 86d9bd64..4a210bd2 100644 --- a/README.md +++ b/README.md @@ -86,6 +86,7 @@ 617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy| 628|[Maximum Product of Three Numbers](./0628-maximum-product-of-three-numbers.js)|Easy| 648|[Replace Words](./0648-replace-words.js)|Medium| +653|[Two Sum IV - Input is a BST](./0653-two-sum-iv---input-is-a-bst.js)|Easy| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| 713|[Subarray Product Less Than K](./0713-subarray-product-less-than-k.js)|Medium| 722|[Remove Comments](./0722-remove-comments.js)|Medium| From 9ab2580add8c77468c2c732e6b94d492a4e1d6a5 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 4 Oct 2021 20:59:39 -0400 Subject: [PATCH 151/919] Add solution #101 --- 0101-symmetric-tree.js | 34 ++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 0101-symmetric-tree.js diff --git a/0101-symmetric-tree.js b/0101-symmetric-tree.js new file mode 100644 index 00000000..548cfb75 --- /dev/null +++ b/0101-symmetric-tree.js @@ -0,0 +1,34 @@ +/** + * 101. Symmetric Tree + * https://leetcode.com/problems/symmetric-tree/ + * Difficulty: Easy + * + * Given the root of a binary tree, check whether it is a mirror + * of itself (i.e., symmetric around its center). + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {boolean} + */ +var isSymmetric = function(root) { + return isBalanced(root.left, root.right); +}; + +function isBalanced(a, b) { + if (!a && !b) { + return true; + } + if (!a || !b) { + return false; + } + return a.val === b.val && isBalanced(a.left, b.right) && isBalanced(a.right, b.left); +} diff --git a/README.md b/README.md index 4a210bd2..7a7d7410 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,7 @@ 83|[Remove Duplicates from Sorted List](./0083-remove-duplicates-from-sorted-list.js)|Easy| 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| 94|[Binary Tree Inorder Traversal](./0094-binary-tree-inorder-traversal.js)|Easy| +101|[Symmetric Tree](./0101-symmetric-tree.js)|Easy| 102|[Binary Tree Level Order Traversal](./0102-binary-tree-level-order-traversal.js)|Medium| 104|[Maximum Depth of Binary Tree](./0104-maximum-depth-of-binary-tree.js)|Easy| 111|[Minimum Depth of Binary Tree](./0111-minimum-depth-of-binary-tree.js)|Easy| From 65a96ba0be4c0c7c241f891661dcf255fa38323c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 5 Oct 2021 21:09:34 -0400 Subject: [PATCH 152/919] Add solution #701 --- 0701-insert-into-a-binary-search-tree.js | 41 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 42 insertions(+) create mode 100644 0701-insert-into-a-binary-search-tree.js diff --git a/0701-insert-into-a-binary-search-tree.js b/0701-insert-into-a-binary-search-tree.js new file mode 100644 index 00000000..ceb4a474 --- /dev/null +++ b/0701-insert-into-a-binary-search-tree.js @@ -0,0 +1,41 @@ +/** + * 701. Insert into a Binary Search Tree + * https://leetcode.com/problems/insert-into-a-binary-search-tree/ + * Difficulty: Medium + * + * You are given the root node of a binary search tree (BST) and a value + * to insert into the tree. Return the root node of the BST after the + * insertion. It is guaranteed that the new value does not exist in the + * original BST. + * + * Notice that there may exist multiple valid ways for the insertion, + * as long as the tree remains a BST after insertion. You can return + * any of them. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @param {number} val + * @return {TreeNode} + */ +var insertIntoBST = function(root, val) { + if (!root) { + return new TreeNode(val); + } + + if (val > root.val) { + root.right = insertIntoBST(root.right, val); + } else { + root.left = insertIntoBST(root.left, val); + } + + return root; +}; diff --git a/README.md b/README.md index 7a7d7410..6c30c54c 100644 --- a/README.md +++ b/README.md @@ -89,6 +89,7 @@ 648|[Replace Words](./0648-replace-words.js)|Medium| 653|[Two Sum IV - Input is a BST](./0653-two-sum-iv---input-is-a-bst.js)|Easy| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| +701|[Insert into a Binary Search Tree](./0701-insert-into-a-binary-search-tree.js)|Medium| 713|[Subarray Product Less Than K](./0713-subarray-product-less-than-k.js)|Medium| 722|[Remove Comments](./0722-remove-comments.js)|Medium| 739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium| From a9f7bf8a703b7d1c42d1b9b0488db3cb1631f39f Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 5 Oct 2021 21:10:13 -0400 Subject: [PATCH 153/919] Add solution #700 --- 0700-search-in-a-binary-search-tree.js | 34 ++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 0700-search-in-a-binary-search-tree.js diff --git a/0700-search-in-a-binary-search-tree.js b/0700-search-in-a-binary-search-tree.js new file mode 100644 index 00000000..3de1c309 --- /dev/null +++ b/0700-search-in-a-binary-search-tree.js @@ -0,0 +1,34 @@ +/** + * 700. Search in a Binary Search Tree + * https://leetcode.com/problems/search-in-a-binary-search-tree/ + * Difficulty: Easy + * + * You are given the root of a binary search tree (BST) and an integer val. + * + * Find the node in the BST that the node's value equals val and return the + * subtree rooted with that node. If such a node does not exist, return null. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @param {number} val + * @return {TreeNode} + */ +var searchBST = function(root, val) { + while (root) { + if (root.val === val) { + return root; + } + root = root.val > val ? root.left : root.right; + } + + return null; +}; diff --git a/README.md b/README.md index 6c30c54c..66486efa 100644 --- a/README.md +++ b/README.md @@ -89,6 +89,7 @@ 648|[Replace Words](./0648-replace-words.js)|Medium| 653|[Two Sum IV - Input is a BST](./0653-two-sum-iv---input-is-a-bst.js)|Easy| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| +700|[Search in a Binary Search Tree](./0700-search-in-a-binary-search-tree.js)|Easy| 701|[Insert into a Binary Search Tree](./0701-insert-into-a-binary-search-tree.js)|Medium| 713|[Subarray Product Less Than K](./0713-subarray-product-less-than-k.js)|Medium| 722|[Remove Comments](./0722-remove-comments.js)|Medium| From 2fac8adbf13529633549d993c335d1cc9cef3f0d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 6 Oct 2021 22:50:13 -0400 Subject: [PATCH 154/919] Add solution #653 --- 0653-two-sum-iv-input-is-a-bst.js | 36 +++++++++++++++++++++++++++++++ README.md | 2 +- 2 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 0653-two-sum-iv-input-is-a-bst.js diff --git a/0653-two-sum-iv-input-is-a-bst.js b/0653-two-sum-iv-input-is-a-bst.js new file mode 100644 index 00000000..75b351e9 --- /dev/null +++ b/0653-two-sum-iv-input-is-a-bst.js @@ -0,0 +1,36 @@ +/** + * 653. Two Sum IV - Input is a BST + * https://leetcode.com/problems/two-sum-iv-input-is-a-bst/ + * Difficulty: Easy + * + * Given the root of a Binary Search Tree and a target number k, return true + * if there exist two elements in the BST such that their sum is equal to the + * given target. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @param {number} k + * @return {boolean} + */ +var findTarget = function(root, k) { + const set = new Set(); + return dfs(set, root, k); +}; + +function dfs(set, node, k) { + if (!node) return false; + if (set.has(k - node.val)) return true; + + set.add(node.val); + + return dfs(set, node.left, k) || dfs(set, node.right, k); +} diff --git a/README.md b/README.md index 66486efa..6fa92232 100644 --- a/README.md +++ b/README.md @@ -87,7 +87,7 @@ 617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy| 628|[Maximum Product of Three Numbers](./0628-maximum-product-of-three-numbers.js)|Easy| 648|[Replace Words](./0648-replace-words.js)|Medium| -653|[Two Sum IV - Input is a BST](./0653-two-sum-iv---input-is-a-bst.js)|Easy| +653|[Two Sum IV - Input is a BST](./0653-two-sum-iv-input-is-a-bst.js)|Easy| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| 700|[Search in a Binary Search Tree](./0700-search-in-a-binary-search-tree.js)|Easy| 701|[Insert into a Binary Search Tree](./0701-insert-into-a-binary-search-tree.js)|Medium| From f1988a2776e73201da93f11ed4ff7fe8e8299765 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 6 Oct 2021 23:25:00 -0400 Subject: [PATCH 155/919] Add solution #1380 --- 1380-lucky-numbers-in-a-matrix.js | 22 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 1380-lucky-numbers-in-a-matrix.js diff --git a/1380-lucky-numbers-in-a-matrix.js b/1380-lucky-numbers-in-a-matrix.js new file mode 100644 index 00000000..6c0bb84e --- /dev/null +++ b/1380-lucky-numbers-in-a-matrix.js @@ -0,0 +1,22 @@ +/** + * 1380. Lucky Numbers in a Matrix + * https://leetcode.com/problems/lucky-numbers-in-a-matrix/ + * Difficulty: Easy + * + * Given an m x n matrix of distinct numbers, return all lucky numbers + * in the matrix in any order. + * + * A lucky number is an element of the matrix such that it is the minimum + * element in its row and maximum in its column. + */ + +/** + * @param {number[][]} matrix + * @return {number[]} + */ +var luckyNumbers = function(matrix) { + const min = matrix.map(row => Math.min(...row)); + const max = matrix[0].map((_, i) => Math.max(...matrix.map(row => row[i]))); + + return min.filter(value => max.includes(value)); +}; diff --git a/README.md b/README.md index 6fa92232..84253036 100644 --- a/README.md +++ b/README.md @@ -142,6 +142,7 @@ 1351|[Count Negative Numbers in a Sorted Matrix](./1351-count-negative-numbers-in-a-sorted-matrix.js)|Easy| 1356|[Sort Integers by The Number of 1 Bits](./1356-sort-integers-by-the-number-of-1-bits.js)|Easy| 1360|[Number of Days Between Two Dates](./1360-number-of-days-between-two-dates.js)|Easy| +1380|[Lucky Numbers in a Matrix](./1380-lucky-numbers-in-a-matrix.js)|Easy| 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| From 4cf346fc89eafa61e215d83a3eb759ecc54f8b3c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 6 Oct 2021 23:25:43 -0400 Subject: [PATCH 156/919] Add solution #1365 --- ...ers-are-smaller-than-the-current-number.js | 20 +++++++++++++++++++ README.md | 1 + 2 files changed, 21 insertions(+) create mode 100644 1365-how-many-numbers-are-smaller-than-the-current-number.js diff --git a/1365-how-many-numbers-are-smaller-than-the-current-number.js b/1365-how-many-numbers-are-smaller-than-the-current-number.js new file mode 100644 index 00000000..6446f40f --- /dev/null +++ b/1365-how-many-numbers-are-smaller-than-the-current-number.js @@ -0,0 +1,20 @@ +/** + * 1365. How Many Numbers Are Smaller Than the Current Number + * https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/ + * Difficulty: Easy + * + * Given the array nums, for each nums[i] find out how many numbers in the array are smaller + * than it. That is, for each nums[i] you have to count the number of valid j's such that + * j != i and nums[j] < nums[i]. + * + * Return the answer in an array. + */ + +/** + * @param {number[]} nums + * @return {number[]} + */ +var smallerNumbersThanCurrent = function(nums) { + const sorted = nums.slice().sort((a, b) => a - b); + return nums.map(num => sorted.indexOf(num)); +}; diff --git a/README.md b/README.md index 84253036..dc0eb017 100644 --- a/README.md +++ b/README.md @@ -142,6 +142,7 @@ 1351|[Count Negative Numbers in a Sorted Matrix](./1351-count-negative-numbers-in-a-sorted-matrix.js)|Easy| 1356|[Sort Integers by The Number of 1 Bits](./1356-sort-integers-by-the-number-of-1-bits.js)|Easy| 1360|[Number of Days Between Two Dates](./1360-number-of-days-between-two-dates.js)|Easy| +1365|[How Many Numbers Are Smaller Than the Current Number](./1365-how-many-numbers-are-smaller-than-the-current-number.js)|Easy| 1380|[Lucky Numbers in a Matrix](./1380-lucky-numbers-in-a-matrix.js)|Easy| 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| From 71bdcab61d5d2811ca7bce84d5f25e44983d8808 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 7 Oct 2021 00:58:15 -0400 Subject: [PATCH 157/919] Add solution #235 --- ...common-ancestor-of-a-binary-search-tree.js | 36 +++++++++++++++++++ 0653-two-sum-iv---input-is-a-bst.js | 36 ------------------- README.md | 1 + 3 files changed, 37 insertions(+), 36 deletions(-) create mode 100644 0235-lowest-common-ancestor-of-a-binary-search-tree.js delete mode 100644 0653-two-sum-iv---input-is-a-bst.js diff --git a/0235-lowest-common-ancestor-of-a-binary-search-tree.js b/0235-lowest-common-ancestor-of-a-binary-search-tree.js new file mode 100644 index 00000000..41b9360a --- /dev/null +++ b/0235-lowest-common-ancestor-of-a-binary-search-tree.js @@ -0,0 +1,36 @@ +/** + * 235. Lowest Common Ancestor of a Binary Search Tree + * https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/ + * Difficulty: Easy + * + * Given a binary search tree (BST), find the lowest common ancestor (LCA) of two + * given nodes in the BST. + * + * According to the definition of LCA on Wikipedia: “The lowest common ancestor is + * defined between two nodes p and q as the lowest node in T that has both p and q + * as descendants (where we allow a node to be a descendant of itself).” + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ + +/** + * @param {TreeNode} root + * @param {TreeNode} p + * @param {TreeNode} q + * @return {TreeNode} + */ +var lowestCommonAncestor = function(root, p, q) { + if (p.val > root.val && q.val > root.val) { + return lowestCommonAncestor(root.right, p, q); + } + if (p.val < root.val && q.val < root.val) { + return lowestCommonAncestor(root.left, p , q); + } + return root; +}; diff --git a/0653-two-sum-iv---input-is-a-bst.js b/0653-two-sum-iv---input-is-a-bst.js deleted file mode 100644 index 6f3b4256..00000000 --- a/0653-two-sum-iv---input-is-a-bst.js +++ /dev/null @@ -1,36 +0,0 @@ -/** - * 653. Two Sum IV - Input is a BST - * https://leetcode.com/problems/two-sum-iv-input-is-a-bst/ - * Difficulty: Easy - * - * Given the root of a Binary Search Tree and a target number k, return - * true if there exist two elements in the BST such that their sum is - * equal to the given target. - */ - -/** - * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - */ -/** - * @param {TreeNode} root - * @param {number} k - * @return {boolean} - */ -var findTarget = function(root, k) { - const set = new Set(); - return dfs(set, root, k); -}; - -function dfs(set, node, k) { - if (!node) return false; - if (set.has(k - node.val)) return true; - - set.add(node.val); - - return dfs(set, node.left, k) || dfs(set, node.right, k); -} diff --git a/README.md b/README.md index dc0eb017..6e7c6d89 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,7 @@ 226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy| 232|[Implement Queue using Stacks](./0232-implement-queue-using-stacks.js)|Easy| 234|[Palindrome Linked List](./0234-palindrome-linked-list.js)|Easy| +235|[Lowest Common Ancestor of a Binary Search Tree](./0235-lowest-common-ancestor-of-a-binary-search-tree.js)|Easy| 237|[Delete Node in a Linked List](./0237-delete-node-in-a-linked-list.js)|Easy| 242|[Valid Anagram](./0242-valid-anagram.js)|Easy| 263|[Ugly Number](./0263-ugly-number.js)|Easy| From 7cc8b7b1ea30d97efc8741ff8fa044c64a801662 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 7 Oct 2021 21:01:29 -0500 Subject: [PATCH 158/919] Add solution #1374 --- ...ng-with-characters-that-have-odd-counts.js | 19 +++++++++++++++++++ README.md | 1 + 2 files changed, 20 insertions(+) create mode 100644 1374-generate-a-string-with-characters-that-have-odd-counts.js diff --git a/1374-generate-a-string-with-characters-that-have-odd-counts.js b/1374-generate-a-string-with-characters-that-have-odd-counts.js new file mode 100644 index 00000000..cd7dd6d9 --- /dev/null +++ b/1374-generate-a-string-with-characters-that-have-odd-counts.js @@ -0,0 +1,19 @@ +/** + * 1374. Generate a String With Characters That Have Odd Counts + * https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts/ + * Difficulty: Easy + * + * Given an integer n, return a string with n characters such that each character in such + * string occurs an odd number of times. + * + * The returned string must contain only lowercase English letters. If there are multiples + * valid strings, return any of them. + */ + +/** + * @param {number} n + * @return {string} + */ +var generateTheString = function(n) { + return 'a'.repeat(n % 2 ? n : n - 1) + (n % 2 ? '' : 'z'); +}; diff --git a/README.md b/README.md index 6e7c6d89..69c08c47 100644 --- a/README.md +++ b/README.md @@ -144,6 +144,7 @@ 1356|[Sort Integers by The Number of 1 Bits](./1356-sort-integers-by-the-number-of-1-bits.js)|Easy| 1360|[Number of Days Between Two Dates](./1360-number-of-days-between-two-dates.js)|Easy| 1365|[How Many Numbers Are Smaller Than the Current Number](./1365-how-many-numbers-are-smaller-than-the-current-number.js)|Easy| +1374|[Generate a String With Characters That Have Odd Counts](./1374-generate-a-string-with-characters-that-have-odd-counts.js)|Easy| 1380|[Lucky Numbers in a Matrix](./1380-lucky-numbers-in-a-matrix.js)|Easy| 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| From 45749b8d3979b179469fd289bec97528db695dd6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 15 Oct 2021 15:19:36 -0400 Subject: [PATCH 159/919] Add solution #1389 --- ...-create-target-array-in-the-given-order.js | 27 +++++++++++++++++++ README.md | 1 + 2 files changed, 28 insertions(+) create mode 100644 1389-create-target-array-in-the-given-order.js diff --git a/1389-create-target-array-in-the-given-order.js b/1389-create-target-array-in-the-given-order.js new file mode 100644 index 00000000..1c31f8dc --- /dev/null +++ b/1389-create-target-array-in-the-given-order.js @@ -0,0 +1,27 @@ +/** + * 1389. Create Target Array in the Given Order + * https://leetcode.com/problems/create-target-array-in-the-given-order/ + * Difficulty: Easy + * + * Given two arrays of integers nums and index. Your task is to create target array + * under the following rules: + * + * - Initially target array is empty. + * - From left to right read nums[i] and index[i], insert at index index[i] the value + * nums[i] in target array. + * - Repeat the previous step until there are no elements to read in nums and index. + * - Return the target array. + * + * It is guaranteed that the insertion operations will be valid. + */ + +/** + * @param {number[]} nums + * @param {number[]} index + * @return {number[]} + */ +var createTargetArray = function(nums, index) { + const result = []; + index.forEach((i, j) => result.splice(i, 0, nums[j])); + return result; +}; diff --git a/README.md b/README.md index 69c08c47..af826080 100644 --- a/README.md +++ b/README.md @@ -146,6 +146,7 @@ 1365|[How Many Numbers Are Smaller Than the Current Number](./1365-how-many-numbers-are-smaller-than-the-current-number.js)|Easy| 1374|[Generate a String With Characters That Have Odd Counts](./1374-generate-a-string-with-characters-that-have-odd-counts.js)|Easy| 1380|[Lucky Numbers in a Matrix](./1380-lucky-numbers-in-a-matrix.js)|Easy| +1389|[Create Target Array in the Given Order](./1389-create-target-array-in-the-given-order.js)|Easy| 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| From 7ebb2adf36d9121fcd2d4b6983686701334712fe Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 15 Oct 2021 15:43:49 -0400 Subject: [PATCH 160/919] Add solution #1408 --- 1408-string-matching-in-an-array.js | 19 +++++++++++++++++++ README.md | 1 + 2 files changed, 20 insertions(+) create mode 100644 1408-string-matching-in-an-array.js diff --git a/1408-string-matching-in-an-array.js b/1408-string-matching-in-an-array.js new file mode 100644 index 00000000..81eb09a1 --- /dev/null +++ b/1408-string-matching-in-an-array.js @@ -0,0 +1,19 @@ +/** + * 1408. String Matching in an Array + * https://leetcode.com/problems/string-matching-in-an-array/ + * Difficulty: Easy + * + * Given an array of string words. Return all strings in words which is + * substring of another word in any order. + * + * String words[i] is substring of words[j], if can be obtained removing + * some characters to left and/or right side of words[j]. + */ + +/** + * @param {string[]} words + * @return {string[]} + */ +var stringMatching = function(words) { + return words.filter(s => words.some(word => word !== s && word.includes(s))); +}; diff --git a/README.md b/README.md index af826080..7425f143 100644 --- a/README.md +++ b/README.md @@ -147,6 +147,7 @@ 1374|[Generate a String With Characters That Have Odd Counts](./1374-generate-a-string-with-characters-that-have-odd-counts.js)|Easy| 1380|[Lucky Numbers in a Matrix](./1380-lucky-numbers-in-a-matrix.js)|Easy| 1389|[Create Target Array in the Given Order](./1389-create-target-array-in-the-given-order.js)|Easy| +1408|[String Matching in an Array](./1408-string-matching-in-an-array.js)|Easy| 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| From 266456b4947e592a6ee31c603dcf10f42ab7c01b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 28 Oct 2021 23:08:23 -0500 Subject: [PATCH 161/919] Add solution #1436 --- 1436-destination-city.js | 21 +++++++++++++++++++++ README.md | 1 + 2 files changed, 22 insertions(+) create mode 100644 1436-destination-city.js diff --git a/1436-destination-city.js b/1436-destination-city.js new file mode 100644 index 00000000..05f7fb78 --- /dev/null +++ b/1436-destination-city.js @@ -0,0 +1,21 @@ +/** + * 1436. Destination City + * https://leetcode.com/problems/destination-city/ + * Difficulty: Easy + * + * You are given the array paths, where paths[i] = [cityAi, cityBi] means there + * exists a direct path going from cityAi to cityBi. Return the destination city, + * that is, the city without any path outgoing to another city. + * + * It is guaranteed that the graph of paths forms a line without any loop, therefore, + * there will be exactly one destination city. + */ + +/** + * @param {string[][]} paths + * @return {string} + */ +var destCity = function(paths) { + const set = new Set(paths.map(([a]) => a)); + return paths.find(([_, b]) => !set.has(b))[1]; +}; diff --git a/README.md b/README.md index 7425f143..8fe642eb 100644 --- a/README.md +++ b/README.md @@ -148,6 +148,7 @@ 1380|[Lucky Numbers in a Matrix](./1380-lucky-numbers-in-a-matrix.js)|Easy| 1389|[Create Target Array in the Given Order](./1389-create-target-array-in-the-given-order.js)|Easy| 1408|[String Matching in an Array](./1408-string-matching-in-an-array.js)|Easy| +1436|[Destination City](./1436-destination-city.js)|Easy| 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| From 1acb7af030a4e7719862044fd024f689f251ca44 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 29 Oct 2021 15:01:08 -0500 Subject: [PATCH 162/919] Add solution #1437 --- ...ll-1s-are-at-least-length-k-places-away.js | 23 +++++++++++++++++++ README.md | 1 + 2 files changed, 24 insertions(+) create mode 100644 1437-check-if-all-1s-are-at-least-length-k-places-away.js diff --git a/1437-check-if-all-1s-are-at-least-length-k-places-away.js b/1437-check-if-all-1s-are-at-least-length-k-places-away.js new file mode 100644 index 00000000..26495fcf --- /dev/null +++ b/1437-check-if-all-1s-are-at-least-length-k-places-away.js @@ -0,0 +1,23 @@ +/** + * 1437. Check If All 1's Are at Least Length K Places Away + * https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away/ + * Difficulty: Easy + * + * Given an array nums of 0s and 1s and an integer k, return True if all 1's are at + * least k places away from each other, otherwise return False. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {boolean} + */ +var kLengthApart = function(nums, k) { + let offset = k; + for (const num of nums) { + if (num === 0) { offset++; continue; } + if (offset < k) return false; + offset = 0; + } + return true; +}; diff --git a/README.md b/README.md index 8fe642eb..8285a1f6 100644 --- a/README.md +++ b/README.md @@ -149,6 +149,7 @@ 1389|[Create Target Array in the Given Order](./1389-create-target-array-in-the-given-order.js)|Easy| 1408|[String Matching in an Array](./1408-string-matching-in-an-array.js)|Easy| 1436|[Destination City](./1436-destination-city.js)|Easy| +1437|[Check If All 1's Are at Least Length K Places Away](./1437-check-if-all-1s-are-at-least-length-k-places-away.js)|Easy| 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| From 95ceeef5a95194ddc8ca8a39833c49d67707b31e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 29 Oct 2021 16:28:25 -0500 Subject: [PATCH 163/919] Add solution #1446 --- 1446-consecutive-characters.js | 24 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 1446-consecutive-characters.js diff --git a/1446-consecutive-characters.js b/1446-consecutive-characters.js new file mode 100644 index 00000000..796f6319 --- /dev/null +++ b/1446-consecutive-characters.js @@ -0,0 +1,24 @@ +/** + * 1446. Consecutive Characters + * https://leetcode.com/problems/consecutive-characters/ + * Difficulty: Easy + * + * The power of the string is the maximum length of a non-empty substring + * that contains only one unique character. + * + * Given a string s, return the power of s. + */ + +/** + * @param {string} s + * @return {number} + */ +var maxPower = function(s) { + let max = 1, count = 0; + for (let i = 0; i < s.length; i++) { + const prev = s[i - 1]; + count = prev === s[i] ? count + 1 : 0; + max = Math.max(max, count + 1); + } + return max; +}; diff --git a/README.md b/README.md index 8285a1f6..e1d59409 100644 --- a/README.md +++ b/README.md @@ -150,6 +150,7 @@ 1408|[String Matching in an Array](./1408-string-matching-in-an-array.js)|Easy| 1436|[Destination City](./1436-destination-city.js)|Easy| 1437|[Check If All 1's Are at Least Length K Places Away](./1437-check-if-all-1s-are-at-least-length-k-places-away.js)|Easy| +1446|[Consecutive Characters](./1446-consecutive-characters.js)|Easy| 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| From cafc9c90f4948642c41af5339ac92535d4a5f6e4 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 30 Oct 2021 20:02:44 -0500 Subject: [PATCH 164/919] Add solution #1447 --- 1447-simplified-fractions.js | 28 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 29 insertions(+) create mode 100644 1447-simplified-fractions.js diff --git a/1447-simplified-fractions.js b/1447-simplified-fractions.js new file mode 100644 index 00000000..f3e60a15 --- /dev/null +++ b/1447-simplified-fractions.js @@ -0,0 +1,28 @@ +/** + * 1447. Simplified Fractions + * https://leetcode.com/problems/simplified-fractions/ + * Difficulty: Medium + * + * Given an integer n, return a list of all simplified fractions between 0 and 1 + * (exclusive) such that the denominator is less-than-or-equal-to n. The + * fractions can be in any order. + */ + +/** + * @param {number} n + * @return {string[]} + */ +var simplifiedFractions = function(n) { + const gcd = (a, b) => !b ? a : gcd(b, a % b); + const result = []; + + for (let i = 2; i <= n; i++) { + for (let j = 1; j < i; j++) { + if (gcd(i, j) === 1) { + result.push(`${j}/${i}`); + } + } + } + + return result; +}; diff --git a/README.md b/README.md index e1d59409..f000caf8 100644 --- a/README.md +++ b/README.md @@ -151,6 +151,7 @@ 1436|[Destination City](./1436-destination-city.js)|Easy| 1437|[Check If All 1's Are at Least Length K Places Away](./1437-check-if-all-1s-are-at-least-length-k-places-away.js)|Easy| 1446|[Consecutive Characters](./1446-consecutive-characters.js)|Easy| +1447|[Simplified Fractions](./1447-simplified-fractions.js)|Medium| 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| From dc8c800bbeaeaa9e6228a4590a8773c77bedb0ac Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 29 Nov 2021 12:35:10 -0600 Subject: [PATCH 165/919] Add solution #1450 --- ...students-doing-homework-at-a-given-time.js | 24 +++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 1450-number-of-students-doing-homework-at-a-given-time.js diff --git a/1450-number-of-students-doing-homework-at-a-given-time.js b/1450-number-of-students-doing-homework-at-a-given-time.js new file mode 100644 index 00000000..82384420 --- /dev/null +++ b/1450-number-of-students-doing-homework-at-a-given-time.js @@ -0,0 +1,24 @@ +/** + * 1450. Number of Students Doing Homework at a Given Time + * https://leetcode.com/problems/number-of-students-doing-homework-at-a-given-time/ + * Difficulty: Easy + * + * Given two integer arrays startTime and endTime and given an integer queryTime. + * + * The ith student started doing their homework at the time startTime[i] and finished it + * at time endTime[i]. + * + * Return the number of students doing their homework at time queryTime. More formally, + * return the number of students where queryTime lays in the interval [startTime[i], + * endTime[i]] inclusive. + */ + +/** + * @param {number[]} startTime + * @param {number[]} endTime + * @param {number} queryTime + * @return {number} + */ +var busyStudent = function(startTime, endTime, queryTime) { + return startTime.filter((s, i) => queryTime >= s && queryTime <= endTime[i]).length; +}; diff --git a/README.md b/README.md index f000caf8..6b0ea5ad 100644 --- a/README.md +++ b/README.md @@ -152,6 +152,7 @@ 1437|[Check If All 1's Are at Least Length K Places Away](./1437-check-if-all-1s-are-at-least-length-k-places-away.js)|Easy| 1446|[Consecutive Characters](./1446-consecutive-characters.js)|Easy| 1447|[Simplified Fractions](./1447-simplified-fractions.js)|Medium| +1450|[Number of Students Doing Homework at a Given Time](./1450-number-of-students-doing-homework-at-a-given-time.js)|Easy| 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| From 04998960c5623a2b24be17e1177da0695064394b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 29 Nov 2021 12:42:42 -0600 Subject: [PATCH 166/919] Add solution #1410 --- 1410-html-entity-parser.js | 37 +++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 38 insertions(+) create mode 100644 1410-html-entity-parser.js diff --git a/1410-html-entity-parser.js b/1410-html-entity-parser.js new file mode 100644 index 00000000..3d4c6f59 --- /dev/null +++ b/1410-html-entity-parser.js @@ -0,0 +1,37 @@ +/** + * 1410. HTML Entity Parser + * https://leetcode.com/problems/html-entity-parser/ + * Difficulty: Medium + * + * HTML entity parser is the parser that takes HTML code as input and replace all the + * entities of the special characters by the characters itself. + * + * The special characters and their entities for HTML are: + * - Quotation Mark: the entity is " and symbol character is ". + * - Single Quote Mark: the entity is ' and symbol character is '. + * - Ampersand: the entity is & and symbol character is &. + * - Greater Than Sign: the entity is > and symbol character is >. + * - Less Than Sign: the entity is < and symbol character is <. + * - Slash: the entity is ⁄ and symbol character is /. + * + * Given the input text string to the HTML parser, you have to implement the entity parser. + * + * Return the text after replacing the entities by the special characters. + */ + +/** + * @param {string} text + * @return {string} + */ +var entityParser = function(text) { + const map = { + '"': '"', + ''': '\'', + '&': '&', + '>': '>', + '<': '<', + '⁄': '/' + }; + + return text.replace(new RegExp(Object.keys(map).join('|'), 'g'), m => map[m]); +}; diff --git a/README.md b/README.md index 6b0ea5ad..e37acc5f 100644 --- a/README.md +++ b/README.md @@ -148,6 +148,7 @@ 1380|[Lucky Numbers in a Matrix](./1380-lucky-numbers-in-a-matrix.js)|Easy| 1389|[Create Target Array in the Given Order](./1389-create-target-array-in-the-given-order.js)|Easy| 1408|[String Matching in an Array](./1408-string-matching-in-an-array.js)|Easy| +1410|[HTML Entity Parser](./1410-html-entity-parser.js)|Medium| 1436|[Destination City](./1436-destination-city.js)|Easy| 1437|[Check If All 1's Are at Least Length K Places Away](./1437-check-if-all-1s-are-at-least-length-k-places-away.js)|Easy| 1446|[Consecutive Characters](./1446-consecutive-characters.js)|Easy| From 4a247a7b9aec7d47b0339e25c9a121574723a59c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 29 Nov 2021 12:57:52 -0600 Subject: [PATCH 167/919] Add solution #551 --- 0551-student-attendance-record-i.js | 26 ++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 27 insertions(+) create mode 100644 0551-student-attendance-record-i.js diff --git a/0551-student-attendance-record-i.js b/0551-student-attendance-record-i.js new file mode 100644 index 00000000..53317a4e --- /dev/null +++ b/0551-student-attendance-record-i.js @@ -0,0 +1,26 @@ +/** + * 551. Student Attendance Record I + * https://leetcode.com/problems/student-attendance-record-i/ + * Difficulty: Easy + * + * You are given a string s representing an attendance record for a student + * where each character signifies whether the student was absent, late, or + * present on that day. The record only contains the following three characters: + * - 'A': Absent. + * - 'L': Late. + * - 'P': Present. + * + * The student is eligible for an attendance award if they meet both of the following criteria: + * - The student was absent ('A') for strictly fewer than 2 days total. + * - The student was never late ('L') for 3 or more consecutive days. + * + * Return true if the student is eligible for an attendance award, or false otherwise. + */ + +/** + * @param {string} s + * @return {boolean} + */ +var checkRecord = function(s) { + return !s.includes('LLL') && (s.indexOf('A') === s.lastIndexOf('A')); +}; diff --git a/README.md b/README.md index e37acc5f..6caa91be 100644 --- a/README.md +++ b/README.md @@ -82,6 +82,7 @@ 451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| 459|[Repeated Substring Pattern](./0459-repeated-substring-pattern.js)|Easy| 541|[Reverse String II](./0541-reverse-string-ii.js)|Easy| +551|[Student Attendance Record I](./0551-student-attendance-record-i.js)|Easy| 565|[Array Nesting](./0565-array-nesting.js)|Medium| 566|[Reshape the Matrix](./0566-reshape-the-matrix.js)|Easy| 606|[Construct String from Binary Tree](./0606-construct-string-from-binary-tree.js)|Easy| From 722a46cb9a6f1fe2171d6d53edc1c69f9d6fdeae Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 29 Nov 2021 17:51:41 -0600 Subject: [PATCH 168/919] Add solution #1451 --- 1451-rearrange-words-in-a-sentence.js | 27 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 28 insertions(+) create mode 100644 1451-rearrange-words-in-a-sentence.js diff --git a/1451-rearrange-words-in-a-sentence.js b/1451-rearrange-words-in-a-sentence.js new file mode 100644 index 00000000..27d54cc8 --- /dev/null +++ b/1451-rearrange-words-in-a-sentence.js @@ -0,0 +1,27 @@ +/** + * 1451. Rearrange Words in a Sentence + * https://leetcode.com/problems/rearrange-words-in-a-sentence/ + * Difficulty: Medium + * + * Given a sentence text (A sentence is a string of space-separated words) in the following format: + * - First letter is in upper case. + * - Each word in text are separated by a single space. + * + * Your task is to rearrange the words in text such that all words are rearranged in an increasing + * order of their lengths. If two words have the same length, arrange them in their original order. + * + * Return the new text following the format shown above. + */ + +/** + * @param {string} text + * @return {string} + */ +var arrangeWords = function(text) { + return text + .split(/\s+/) + .sort((a, b) => a.length - b.length) + .join(' ') + .toLowerCase() + .replace(/^./, m => m.toUpperCase()); +}; diff --git a/README.md b/README.md index 6caa91be..79ab0fcb 100644 --- a/README.md +++ b/README.md @@ -155,6 +155,7 @@ 1446|[Consecutive Characters](./1446-consecutive-characters.js)|Easy| 1447|[Simplified Fractions](./1447-simplified-fractions.js)|Medium| 1450|[Number of Students Doing Homework at a Given Time](./1450-number-of-students-doing-homework-at-a-given-time.js)|Easy| +1451|[Rearrange Words in a Sentence](./1451-rearrange-words-in-a-sentence.js)|Medium| 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| From cb426b96ef214416cdb52df96f26dd7208d9048d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 29 Nov 2021 18:14:10 -0600 Subject: [PATCH 169/919] Add solution #1455 --- ...s-as-a-prefix-of-any-word-in-a-sentence.js | 23 +++++++++++++++++++ README.md | 1 + 2 files changed, 24 insertions(+) create mode 100644 1455-check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence.js diff --git a/1455-check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence.js b/1455-check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence.js new file mode 100644 index 00000000..78f9d522 --- /dev/null +++ b/1455-check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence.js @@ -0,0 +1,23 @@ +/** + * 1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence + * https://leetcode.com/problems/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/ + * Difficulty: Easy + * + * Given a sentence that consists of some words separated by a single space, and a searchWord, + * check if searchWord is a prefix of any word in sentence. + * + * Return the index of the word in sentence (1-indexed) where searchWord is a prefix of this word. + * If searchWord is a prefix of more than one word, return the index of the first word (minimum index). + * If there is no such word return -1. + * + * A prefix of a string s is any leading contiguous substring of s. + */ + +/** + * @param {string} sentence + * @param {string} searchWord + * @return {number} + */ +var isPrefixOfWord = function(sentence, searchWord) { + return sentence.split(/\s+/).findIndex(s => s.startsWith(searchWord)) + 1 || -1; +}; diff --git a/README.md b/README.md index 79ab0fcb..ddc047eb 100644 --- a/README.md +++ b/README.md @@ -156,6 +156,7 @@ 1447|[Simplified Fractions](./1447-simplified-fractions.js)|Medium| 1450|[Number of Students Doing Homework at a Given Time](./1450-number-of-students-doing-homework-at-a-given-time.js)|Easy| 1451|[Rearrange Words in a Sentence](./1451-rearrange-words-in-a-sentence.js)|Medium| +1455|[Check If a Word Occurs As a Prefix of Any Word in a Sentence](./1455-check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence.js)|Easy| 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| From e85225a4673d8cd13b96cb925e4303319634301f Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 30 Nov 2021 15:44:11 -0600 Subject: [PATCH 170/919] Add solution #1456 --- ...f-vowels-in-a-substring-of-given-length.js | 33 +++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 1456-maximum-number-of-vowels-in-a-substring-of-given-length.js diff --git a/1456-maximum-number-of-vowels-in-a-substring-of-given-length.js b/1456-maximum-number-of-vowels-in-a-substring-of-given-length.js new file mode 100644 index 00000000..5eb327c9 --- /dev/null +++ b/1456-maximum-number-of-vowels-in-a-substring-of-given-length.js @@ -0,0 +1,33 @@ +/** + * 1456. Maximum Number of Vowels in a Substring of Given Length + * https://leetcode.com/problems/maximum-number-of-vowels-in-a-substring-of-given-length/ + * Difficulty: Medium + * + * Given a string s and an integer k. + * + * Return the maximum number of vowel letters in any substring of s with length k. + * + * Vowel letters in English are (a, e, i, o, u). + */ + +/** + * @param {string} s + * @param {number} k + * @return {number} + */ +var maxVowels = function(s, k) { + const vowels = 'aeiou'; + let result = 0; + + for (let i = 0, count = 0; i < s.length; i++) { + if (vowels.includes(s[i])) { + count++; + } + if (i >= k && vowels.includes(s[i - k])) { + count--; + } + result = Math.max(result, count); + } + + return result; +}; diff --git a/README.md b/README.md index ddc047eb..c50e2797 100644 --- a/README.md +++ b/README.md @@ -157,6 +157,7 @@ 1450|[Number of Students Doing Homework at a Given Time](./1450-number-of-students-doing-homework-at-a-given-time.js)|Easy| 1451|[Rearrange Words in a Sentence](./1451-rearrange-words-in-a-sentence.js)|Medium| 1455|[Check If a Word Occurs As a Prefix of Any Word in a Sentence](./1455-check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence.js)|Easy| +1456|[Maximum Number of Vowels in a Substring of Given Length](./1456-maximum-number-of-vowels-in-a-substring-of-given-length.js)|Medium| 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| From f9f13cc8986fc7dbfec39f4784c561740d6ad4d3 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 30 Nov 2021 16:26:49 -0600 Subject: [PATCH 171/919] Add solution #821 --- 0821-shortest-distance-to-a-character.js | 40 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 41 insertions(+) create mode 100644 0821-shortest-distance-to-a-character.js diff --git a/0821-shortest-distance-to-a-character.js b/0821-shortest-distance-to-a-character.js new file mode 100644 index 00000000..0d0e93e1 --- /dev/null +++ b/0821-shortest-distance-to-a-character.js @@ -0,0 +1,40 @@ +/** + * 821. Shortest Distance to a Character + * https://leetcode.com/problems/shortest-distance-to-a-character/ + * Difficulty: Easy + * + * 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. + */ + +/** + * @param {string} s + * @param {character} c + * @return {number[]} + */ +var shortestToChar = function(s, c) { + const result = []; + const pointers = []; + + for (let i = 0; i < s.length; i++) { + if (s[i] === c) pointers.push(i); + } + + for (let i = 0, j = 0; i < s.length; i++) { + if (i > pointers[j + 1] && pointers.length - 2 > j) { + j++; + } + + const offset = pointers.length > 1 + ? Math.min(Math.abs(pointers[j] - i), Math.abs(pointers[j + 1] - i)) + : Math.abs(pointers[j] - i); + + result.push(offset); + } + + return result; +}; diff --git a/README.md b/README.md index c50e2797..6895b2b5 100644 --- a/README.md +++ b/README.md @@ -99,6 +99,7 @@ 791|[Custom Sort String](./0791-custom-sort-string.js)|Medium| 804|[Unique Morse Code Words](./0804-unique-morse-code-words.js)|Easy| 819|[Most Common Word](./0819-most-common-word.js)|Easy| +821|[Shortest Distance to a Character](./0821-shortest-distance-to-a-character.js)|Easy| 824|[Goat Latin](./0824-goat-latin.js)|Easy| 831|[Masking Personal Information](./0831-masking-personal-information.js)|Medium| 844|[Backspace String Compare](./0844-backspace-string-compare.js)|Easy| From 6604d5e2f8e99579f210a679bed7452bd35e1d9e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 30 Nov 2021 16:40:02 -0600 Subject: [PATCH 172/919] Add solution #179 --- 0179-largest-number.js | 22 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 0179-largest-number.js diff --git a/0179-largest-number.js b/0179-largest-number.js new file mode 100644 index 00000000..df659a9f --- /dev/null +++ b/0179-largest-number.js @@ -0,0 +1,22 @@ +/** + * 179. Largest Number + * https://leetcode.com/problems/largest-number/ + * Difficulty: Medium + * + * Given a list of non-negative integers nums, arrange them such that they + * form the largest number. + * + * Note: The result may be very large, so you need to return a string + * instead of an integer. + */ + +/** + * @param {number[]} nums + * @return {string} + */ +var largestNumber = function(nums) { + return nums + .sort((a, b) => `${b}${a}` - `${a}${b}`) + .join('') + .replace(/^0+/, 0); +}; diff --git a/README.md b/README.md index 6895b2b5..7662df66 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,7 @@ 145|[Binary Tree Postorder Traversal](./0145-binary-tree-postorder-traversal.js)|Easy| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| +179|[Largest Number](./0179-largest-number.js)|Medium| 203|[Remove Linked List Elements](./0203-remove-linked-list-elements.js)|Easy| 206|[Reverse Linked List](./0206-reverse-linked-list.js)|Easy| 217|[Contains Duplicate](./0217-contains-duplicate.js)|Easy| From ac3c1151b69bab26ceadcad0423dec00a7ff507f Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 30 Nov 2021 16:46:45 -0600 Subject: [PATCH 173/919] Add solution #1460 --- ...wo-arrays-equal-by-reversing-sub-arrays.js | 21 +++++++++++++++++++ README.md | 1 + 2 files changed, 22 insertions(+) create mode 100644 1460-make-two-arrays-equal-by-reversing-sub-arrays.js diff --git a/1460-make-two-arrays-equal-by-reversing-sub-arrays.js b/1460-make-two-arrays-equal-by-reversing-sub-arrays.js new file mode 100644 index 00000000..3040cf91 --- /dev/null +++ b/1460-make-two-arrays-equal-by-reversing-sub-arrays.js @@ -0,0 +1,21 @@ +/** + * 1460. Make Two Arrays Equal by Reversing Sub-arrays + * https://leetcode.com/problems/make-two-arrays-equal-by-reversing-sub-arrays/ + * Difficulty: Easy + * + * Given two integer arrays of equal length target and arr. + * + * In one step, you can select any non-empty sub-array of arr and reverse it. + * You are allowed to make any number of steps. + * + * Return True if you can make arr equal to target, or False otherwise. + */ + +/** + * @param {number[]} target + * @param {number[]} arr + * @return {boolean} + */ +var canBeEqual = function(target, arr) { + return target.sort().join('') === arr.sort().join(''); +}; diff --git a/README.md b/README.md index 7662df66..3e5c3175 100644 --- a/README.md +++ b/README.md @@ -160,6 +160,7 @@ 1451|[Rearrange Words in a Sentence](./1451-rearrange-words-in-a-sentence.js)|Medium| 1455|[Check If a Word Occurs As a Prefix of Any Word in a Sentence](./1455-check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence.js)|Easy| 1456|[Maximum Number of Vowels in a Substring of Given Length](./1456-maximum-number-of-vowels-in-a-substring-of-given-length.js)|Medium| +1460|[Make Two Arrays Equal by Reversing Sub-arrays](./1460-make-two-arrays-equal-by-reversing-sub-arrays.js)|Easy| 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| From f8f247544afff153e95bf8d5a91b57e5b1fa81af Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 1 Dec 2021 17:49:30 -0600 Subject: [PATCH 174/919] Add solution #1464 --- ...ximum-product-of-two-elements-in-an-array.js | 17 +++++++++++++++++ README.md | 1 + 2 files changed, 18 insertions(+) create mode 100644 1464-maximum-product-of-two-elements-in-an-array.js diff --git a/1464-maximum-product-of-two-elements-in-an-array.js b/1464-maximum-product-of-two-elements-in-an-array.js new file mode 100644 index 00000000..2b1fb2cf --- /dev/null +++ b/1464-maximum-product-of-two-elements-in-an-array.js @@ -0,0 +1,17 @@ +/** + * 1464. Maximum Product of Two Elements in an Array + * https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/ + * Difficulty: Easy + * + * Given the array of integers nums, you will choose two different indices i and j + * of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1). + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var maxProduct = function(nums) { + const [a, b] = nums.sort((a, b) => b - a); + return (a - 1) * (b - 1); +}; diff --git a/README.md b/README.md index 3e5c3175..67020ab4 100644 --- a/README.md +++ b/README.md @@ -161,6 +161,7 @@ 1455|[Check If a Word Occurs As a Prefix of Any Word in a Sentence](./1455-check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence.js)|Easy| 1456|[Maximum Number of Vowels in a Substring of Given Length](./1456-maximum-number-of-vowels-in-a-substring-of-given-length.js)|Medium| 1460|[Make Two Arrays Equal by Reversing Sub-arrays](./1460-make-two-arrays-equal-by-reversing-sub-arrays.js)|Easy| +1464|[Maximum Product of Two Elements in an Array](./1464-maximum-product-of-two-elements-in-an-array.js)|Easy| 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| From e2715edeacb8c2aff562eb022416de84b23765f3 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 1 Dec 2021 18:30:22 -0600 Subject: [PATCH 175/919] Add solution #1470 --- 1470-shuffle-the-array.js | 22 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 1470-shuffle-the-array.js diff --git a/1470-shuffle-the-array.js b/1470-shuffle-the-array.js new file mode 100644 index 00000000..a8ac4990 --- /dev/null +++ b/1470-shuffle-the-array.js @@ -0,0 +1,22 @@ +/** + * 1470. Shuffle the Array + * https://leetcode.com/problems/shuffle-the-array/ + * Difficulty: Easy + * + * Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn]. + * + * Return the array in the form [x1,y1,x2,y2,...,xn,yn]. + */ + +/** + * @param {number[]} nums + * @param {number} n + * @return {number[]} + */ +var shuffle = function(nums, n) { + const shuffled = []; + for (let i = 0; i < nums.length / 2; i++) { + shuffled.push(nums[i], nums[i + nums.length / 2]); + } + return shuffled; +}; diff --git a/README.md b/README.md index 67020ab4..ef883599 100644 --- a/README.md +++ b/README.md @@ -162,6 +162,7 @@ 1456|[Maximum Number of Vowels in a Substring of Given Length](./1456-maximum-number-of-vowels-in-a-substring-of-given-length.js)|Medium| 1460|[Make Two Arrays Equal by Reversing Sub-arrays](./1460-make-two-arrays-equal-by-reversing-sub-arrays.js)|Easy| 1464|[Maximum Product of Two Elements in an Array](./1464-maximum-product-of-two-elements-in-an-array.js)|Easy| +1470|[Shuffle the Array](./1470-shuffle-the-array.js)|Easy| 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| From 71da54d2c00f5c34700660859cca0fa98c4398e6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 1 Dec 2021 18:56:41 -0600 Subject: [PATCH 176/919] Add solution #1475 --- ...rices-with-a-special-discount-in-a-shop.js | 22 +++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 1475-final-prices-with-a-special-discount-in-a-shop.js diff --git a/1475-final-prices-with-a-special-discount-in-a-shop.js b/1475-final-prices-with-a-special-discount-in-a-shop.js new file mode 100644 index 00000000..02d9aed0 --- /dev/null +++ b/1475-final-prices-with-a-special-discount-in-a-shop.js @@ -0,0 +1,22 @@ +/** + * 1475. Final Prices With a Special Discount in a Shop + * https://leetcode.com/problems/final-prices-with-a-special-discount-in-a-shop/ + * Difficulty: Easy + * + * Given the array prices where prices[i] is the price of the ith item in a shop. + * There is a special discount for items in the shop, if you buy the ith item, + * then you will receive a discount equivalent to prices[j] where j is the minimum + * index such that j > i and prices[j] <= prices[i], otherwise, you will not receive + * any discount at all. + * + * Return an array where the ith element is the final price you will pay for the ith + * item of the shop considering the special discount. + */ + +/** + * @param {number[]} prices + * @return {number[]} + */ +var finalPrices = function(prices) { + return prices.map((n, i) => n - (prices.slice(i + 1).find(v => v <= n) || 0)); +}; diff --git a/README.md b/README.md index ef883599..a7184811 100644 --- a/README.md +++ b/README.md @@ -164,6 +164,7 @@ 1464|[Maximum Product of Two Elements in an Array](./1464-maximum-product-of-two-elements-in-an-array.js)|Easy| 1470|[Shuffle the Array](./1470-shuffle-the-array.js)|Easy| 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| +1475|[Final Prices With a Special Discount in a Shop](./1475-final-prices-with-a-special-discount-in-a-shop.js)|Easy| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1929|[Concatenation of Array](./1929-concatenation-of-array.js)|Easy| From b20ea69de7345a93c4aa4bd0fafae94fa651d146 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 2 Dec 2021 00:16:29 -0600 Subject: [PATCH 177/919] Add solution #1486 --- 1486-xor-operation-in-an-array.js | 23 +++++++++++++++++++++++ README.md | 1 + 2 files changed, 24 insertions(+) create mode 100644 1486-xor-operation-in-an-array.js diff --git a/1486-xor-operation-in-an-array.js b/1486-xor-operation-in-an-array.js new file mode 100644 index 00000000..1a897091 --- /dev/null +++ b/1486-xor-operation-in-an-array.js @@ -0,0 +1,23 @@ +/** + * 1486. XOR Operation in an Array + * https://leetcode.com/problems/xor-operation-in-an-array/ + * Difficulty: Easy + * + * Given an integer n and an integer start. + * + * Define an array nums where nums[i] = start + 2*i (0-indexed) and n == nums.length. + * + * Return the bitwise XOR of all elements of nums. + */ + +/** + * @param {number} n + * @param {number} start + * @return {number} + */ +var xorOperation = function(n, start) { + return new Array(n) + .fill(0) + .map((_, i) => start + 2 * i) + .reduce((result, n) => result ^ n, 0); +}; diff --git a/README.md b/README.md index a7184811..c503f72d 100644 --- a/README.md +++ b/README.md @@ -165,6 +165,7 @@ 1470|[Shuffle the Array](./1470-shuffle-the-array.js)|Easy| 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1475|[Final Prices With a Special Discount in a Shop](./1475-final-prices-with-a-special-discount-in-a-shop.js)|Easy| +1486|[XOR Operation in an Array](./1486-xor-operation-in-an-array.js)|Easy| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1929|[Concatenation of Array](./1929-concatenation-of-array.js)|Easy| From 21cba5b4da2a696b928b0996210e0ef30c1c90d9 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 2 Dec 2021 00:17:35 -0600 Subject: [PATCH 178/919] Add solution #231 --- 0231-power-of-two.js | 22 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 0231-power-of-two.js diff --git a/0231-power-of-two.js b/0231-power-of-two.js new file mode 100644 index 00000000..b8ad43dc --- /dev/null +++ b/0231-power-of-two.js @@ -0,0 +1,22 @@ +/** + * 231. Power of Two + * https://leetcode.com/problems/power-of-two/ + * Difficulty: Easy + * + * Given an integer n, return true if it is a power of two. Otherwise, return false. + * + * An integer n is a power of two, if there exists an integer x such that n == 2x. + */ + +/** + * @param {number} n + * @return {boolean} + */ +var isPowerOfTwo = function(n) { + if (n > 1) { + while (n % 2 === 0) { + n /= 2 + } + } + return n === 1; +}; diff --git a/README.md b/README.md index c503f72d..9fb07093 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,7 @@ 219|[Contains Duplicate II](./0219-contains-duplicate-ii.js)|Easy| 225|[Implement Stack using Queues](./0225-implement-stack-using-queues.js)|Easy| 226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy| +231|[Power of Two](./0231-power-of-two.js)|Easy| 232|[Implement Queue using Stacks](./0232-implement-queue-using-stacks.js)|Easy| 234|[Palindrome Linked List](./0234-palindrome-linked-list.js)|Easy| 235|[Lowest Common Ancestor of a Binary Search Tree](./0235-lowest-common-ancestor-of-a-binary-search-tree.js)|Easy| From 2a41126afb912b5adf5335719893f3935321e379 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 2 Dec 2021 00:18:14 -0600 Subject: [PATCH 179/919] Add solution #326 --- 0326-power-of-three.js | 22 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 0326-power-of-three.js diff --git a/0326-power-of-three.js b/0326-power-of-three.js new file mode 100644 index 00000000..514cee88 --- /dev/null +++ b/0326-power-of-three.js @@ -0,0 +1,22 @@ +/** + * 326. Power of Three + * https://leetcode.com/problems/power-of-three/ + * Difficulty: Easy + * + * Given an integer n, return true if it is a power of three. Otherwise, return false. + * + * An integer n is a power of three, if there exists an integer x such that n == 3x. + */ + +/** + * @param {number} n + * @return {boolean} + */ +var isPowerOfThree = function(n) { + if (n > 1) { + while (n % 3 === 0) { + n /= 3 + } + } + return n === 1; +}; diff --git a/README.md b/README.md index 9fb07093..71a62e87 100644 --- a/README.md +++ b/README.md @@ -73,6 +73,7 @@ 268|[Missing Number](./0268-missing-number.js)|Easy| 273|[Integer to English Words](./0273-integer-to-english-words.js)|Hard| 283|[Move Zeroes](./0283-move-zeroes.js)|Easy| +326|[Power of Three](./0326-power-of-three.js)|Easy| 345|[Reverse Vowels of a String](./0345-reverse-vowels-of-a-string.js)|Easy| 347|[Top K Frequent Elements](./0347-top-k-frequent-elements.js)|Medium| 349|[Intersection of Two Arrays](./0349-intersection-of-two-arrays.js)|Easy| From 22b3708190d873c1e1d70eee2e15948ed3a6c713 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 2 Dec 2021 00:18:50 -0600 Subject: [PATCH 180/919] Add solution #342 --- 0342-power-of-four.js | 22 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 0342-power-of-four.js diff --git a/0342-power-of-four.js b/0342-power-of-four.js new file mode 100644 index 00000000..1f49fe02 --- /dev/null +++ b/0342-power-of-four.js @@ -0,0 +1,22 @@ +/** + * 342. Power of Four + * https://leetcode.com/problems/power-of-four/ + * Difficulty: Easy + * + * Given an integer n, return true if it is a power of four. Otherwise, return false. + * + * An integer n is a power of four, if there exists an integer x such that n == 4x. + */ + +/** + * @param {number} n + * @return {boolean} + */ +var isPowerOfFour = function(n) { + if (n > 1) { + while (n % 4 === 0) { + n /= 4 + } + } + return n === 1; +}; diff --git a/README.md b/README.md index 71a62e87..b16e6297 100644 --- a/README.md +++ b/README.md @@ -74,6 +74,7 @@ 273|[Integer to English Words](./0273-integer-to-english-words.js)|Hard| 283|[Move Zeroes](./0283-move-zeroes.js)|Easy| 326|[Power of Three](./0326-power-of-three.js)|Easy| +342|[Power of Four](./0342-power-of-four.js)|Easy| 345|[Reverse Vowels of a String](./0345-reverse-vowels-of-a-string.js)|Easy| 347|[Top K Frequent Elements](./0347-top-k-frequent-elements.js)|Medium| 349|[Intersection of Two Arrays](./0349-intersection-of-two-arrays.js)|Easy| From cb1010b19127228bc1fc79bb679f073b8c22ada7 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 2 Dec 2021 00:19:42 -0600 Subject: [PATCH 181/919] Add solution #191 --- 0191-number-of-1-bits.js | 16 ++++++++++++++++ README.md | 1 + 2 files changed, 17 insertions(+) create mode 100644 0191-number-of-1-bits.js diff --git a/0191-number-of-1-bits.js b/0191-number-of-1-bits.js new file mode 100644 index 00000000..dc765426 --- /dev/null +++ b/0191-number-of-1-bits.js @@ -0,0 +1,16 @@ +/** + * 191. Number of 1 Bits + * https://leetcode.com/problems/number-of-1-bits/ + * Difficulty: Easy + * + * Write a function that takes an unsigned integer and returns the number of + * '1' bits it has (also known as the Hamming weight). + */ + +/** + * @param {number} n - a positive integer + * @return {number} + */ +var hammingWeight = function(n) { + return n.toString(2).match(/1/g)?.length || 0; +}; diff --git a/README.md b/README.md index b16e6297..27e0f198 100644 --- a/README.md +++ b/README.md @@ -56,6 +56,7 @@ 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| 179|[Largest Number](./0179-largest-number.js)|Medium| +191|[Number of 1 Bits](./0191-number-of-1-bits.js)|Easy| 203|[Remove Linked List Elements](./0203-remove-linked-list-elements.js)|Easy| 206|[Reverse Linked List](./0206-reverse-linked-list.js)|Easy| 217|[Contains Duplicate](./0217-contains-duplicate.js)|Easy| From 433e90ce5df37c2b0fbae99e7708dbe80be1f568 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 2 Dec 2021 00:22:12 -0600 Subject: [PATCH 182/919] Add solution #1780 --- ...k-if-number-is-a-sum-of-powers-of-three.js | 24 +++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 1780-check-if-number-is-a-sum-of-powers-of-three.js diff --git a/1780-check-if-number-is-a-sum-of-powers-of-three.js b/1780-check-if-number-is-a-sum-of-powers-of-three.js new file mode 100644 index 00000000..7739fda7 --- /dev/null +++ b/1780-check-if-number-is-a-sum-of-powers-of-three.js @@ -0,0 +1,24 @@ +/** + * 1780. Check if Number is a Sum of Powers of Three + * https://leetcode.com/problems/check-if-number-is-a-sum-of-powers-of-three/ + * Difficulty: Medium + * + * Given an integer n, return true if it is possible to represent n as the sum + * of distinct powers of three. Otherwise, return false. + * + * An integer y is a power of three if there exists an integer x such that y == 3x. + */ + +/** + * @param {number} n + * @return {boolean} + */ +var checkPowersOfThree = function(n) { + while (n) { + if (n % 3 === 2) { + return 0; + } + n = n / 3 >> 0; + } + return 1; +}; diff --git a/README.md b/README.md index 27e0f198..7901b798 100644 --- a/README.md +++ b/README.md @@ -171,6 +171,7 @@ 1475|[Final Prices With a Special Discount in a Shop](./1475-final-prices-with-a-special-discount-in-a-shop.js)|Easy| 1486|[XOR Operation in an Array](./1486-xor-operation-in-an-array.js)|Easy| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| +1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1929|[Concatenation of Array](./1929-concatenation-of-array.js)|Easy| 2000|[Reverse Prefix of Word](./2000-reverse-prefix-of-word.js)|Easy| From 00d3daec9e471564d78a0eeeb08007a9288f84bf Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 2 Dec 2021 00:50:11 -0600 Subject: [PATCH 183/919] Add solution #1480 --- 1480-running-sum-of-1d-array.js | 21 +++++++++++++++++++++ README.md | 1 + 2 files changed, 22 insertions(+) create mode 100644 1480-running-sum-of-1d-array.js diff --git a/1480-running-sum-of-1d-array.js b/1480-running-sum-of-1d-array.js new file mode 100644 index 00000000..03c29dec --- /dev/null +++ b/1480-running-sum-of-1d-array.js @@ -0,0 +1,21 @@ +/** + * 1480. Running Sum of 1d Array + * https://leetcode.com/problems/running-sum-of-1d-array/ + * Difficulty: Easy + * + * Given an array nums. We define a running sum of an array as + * runningSum[i] = sum(nums[0]…nums[i]). + * + * Return the running sum of nums. + */ + +/** + * @param {number[]} nums + * @return {number[]} + */ +var runningSum = function(nums) { + for (let i = 1; i < nums.length; i++) { + nums[i] = nums[i - 1] + nums[i]; + } + return nums; +}; diff --git a/README.md b/README.md index 7901b798..cb03cf74 100644 --- a/README.md +++ b/README.md @@ -169,6 +169,7 @@ 1470|[Shuffle the Array](./1470-shuffle-the-array.js)|Easy| 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1475|[Final Prices With a Special Discount in a Shop](./1475-final-prices-with-a-special-discount-in-a-shop.js)|Easy| +1480|[Running Sum of 1d Array](./1480-running-sum-of-1d-array.js)|Easy| 1486|[XOR Operation in an Array](./1486-xor-operation-in-an-array.js)|Easy| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| From 71e037c97e70d5fd88bd599fd716b820c823a900 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 2 Dec 2021 23:37:56 -0600 Subject: [PATCH 184/919] Add solution #1496 --- 1496-path-crossing.js | 37 +++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 38 insertions(+) create mode 100644 1496-path-crossing.js diff --git a/1496-path-crossing.js b/1496-path-crossing.js new file mode 100644 index 00000000..13f3e814 --- /dev/null +++ b/1496-path-crossing.js @@ -0,0 +1,37 @@ +/** + * 1496. Path Crossing + * https://leetcode.com/problems/path-crossing/ + * Difficulty: Easy + * + * Given a string path, where path[i] = 'N', 'S', 'E' or 'W', each representing + * moving one unit north, south, east, or west, respectively. You start at the + * origin (0, 0) on a 2D plane and walk on the path specified by path. + * + * Return true if the path crosses itself at any point, that is, if at any time + * you are on a location you have previously visited. Return false otherwise. + */ + +/** + * @param {string} path + * @return {boolean} + */ +var isPathCrossing = function(path) { + let x = 0, y = 0; + const toKey = (a, b) => `${a},${b}`; + const history = new Set([toKey(x, y)]); + + for (let direction of path) { + switch (direction) { + case 'N': x++; break; + case 'W': y--; break; + case 'S': x--; break; + case 'E': y++; break; + } + if (history.has(toKey(x, y))) { + return true; + } + history.add(toKey(x, y)); + } + + return false; +}; diff --git a/README.md b/README.md index cb03cf74..99ab14bf 100644 --- a/README.md +++ b/README.md @@ -171,6 +171,7 @@ 1475|[Final Prices With a Special Discount in a Shop](./1475-final-prices-with-a-special-discount-in-a-shop.js)|Easy| 1480|[Running Sum of 1d Array](./1480-running-sum-of-1d-array.js)|Easy| 1486|[XOR Operation in an Array](./1486-xor-operation-in-an-array.js)|Easy| +1496|[Path Crossing](./1496-path-crossing.js)|Easy| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| From 859595f45ffc4bbf20ff1173d90a4358fc304968 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 2 Dec 2021 23:38:46 -0600 Subject: [PATCH 185/919] Add solution #1492 --- 1492-the-kth-factor-of-n.js | 27 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 28 insertions(+) create mode 100644 1492-the-kth-factor-of-n.js diff --git a/1492-the-kth-factor-of-n.js b/1492-the-kth-factor-of-n.js new file mode 100644 index 00000000..0de7ad94 --- /dev/null +++ b/1492-the-kth-factor-of-n.js @@ -0,0 +1,27 @@ +/** + * 1492. The kth Factor of n + * https://leetcode.com/problems/the-kth-factor-of-n/ + * Difficulty: Medium + * + * Given two positive integers n and k. + * + * A factor of an integer n is defined as an integer i where n % i == 0. + * + * Consider a list of all factors of n sorted in ascending order, return + * the kth factor in this list or return -1 if n has less than k factors. + */ + +/** + * @param {number} n + * @param {number} k + * @return {number} + */ +var kthFactor = function(n, k) { + for (let i = 1; i <= n; i++) { + if (n % i === 0) { + k--; + } + if (!k) return i; + } + return -1; +}; diff --git a/README.md b/README.md index 99ab14bf..1405af92 100644 --- a/README.md +++ b/README.md @@ -171,6 +171,7 @@ 1475|[Final Prices With a Special Discount in a Shop](./1475-final-prices-with-a-special-discount-in-a-shop.js)|Easy| 1480|[Running Sum of 1d Array](./1480-running-sum-of-1d-array.js)|Easy| 1486|[XOR Operation in an Array](./1486-xor-operation-in-an-array.js)|Easy| +1492|[The kth Factor of n](./1492-the-kth-factor-of-n.js)|Medium| 1496|[Path Crossing](./1496-path-crossing.js)|Easy| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| From 340948e27a71ffbca0bbe87df2ea3ccb6866e29a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 2 Dec 2021 23:39:54 -0600 Subject: [PATCH 186/919] Add solution #1481 --- ...ber-of-unique-integers-after-k-removals.js | 26 +++++++++++++++++++ README.md | 1 + 2 files changed, 27 insertions(+) create mode 100644 1481-least-number-of-unique-integers-after-k-removals.js diff --git a/1481-least-number-of-unique-integers-after-k-removals.js b/1481-least-number-of-unique-integers-after-k-removals.js new file mode 100644 index 00000000..a786eaf4 --- /dev/null +++ b/1481-least-number-of-unique-integers-after-k-removals.js @@ -0,0 +1,26 @@ +/** + * 1481. Least Number of Unique Integers after K Removals + * https://leetcode.com/problems/least-number-of-unique-integers-after-k-removals/ + * Difficulty: Medium + * + * Given an array of integers arr and an integer k. Find the least number of + * unique integers after removing exactly k elements. + */ + +/** + * @param {number[]} arr + * @param {number} k + * @return {number} + */ +var findLeastNumOfUniqueInts = function(arr, k) { + const map = new Map(); + arr.forEach(n => map.set(n, map.has(n) ? map.get(n) + 1 : 1)); + + const sorted = [...map.values()].sort((a, b) => a - b); + while (k && sorted.length && sorted[0] <= k) { + k -= sorted[0]; + sorted.shift(); + } + + return sorted.length; +}; diff --git a/README.md b/README.md index 1405af92..d89a0c01 100644 --- a/README.md +++ b/README.md @@ -170,6 +170,7 @@ 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1475|[Final Prices With a Special Discount in a Shop](./1475-final-prices-with-a-special-discount-in-a-shop.js)|Easy| 1480|[Running Sum of 1d Array](./1480-running-sum-of-1d-array.js)|Easy| +1481|[Least Number of Unique Integers after K Removals](./1481-least-number-of-unique-integers-after-k-removals.js)|Medium| 1486|[XOR Operation in an Array](./1486-xor-operation-in-an-array.js)|Easy| 1492|[The kth Factor of n](./1492-the-kth-factor-of-n.js)|Medium| 1496|[Path Crossing](./1496-path-crossing.js)|Easy| From ee7c1540c39a5070e5e230fa96352c29ea7f3600 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 3 Dec 2021 00:10:33 -0600 Subject: [PATCH 187/919] Add solution #1502 --- ...ke-arithmetic-progression-from-sequence.js | 27 +++++++++++++++++++ README.md | 1 + 2 files changed, 28 insertions(+) create mode 100644 1502-can-make-arithmetic-progression-from-sequence.js diff --git a/1502-can-make-arithmetic-progression-from-sequence.js b/1502-can-make-arithmetic-progression-from-sequence.js new file mode 100644 index 00000000..d313fd83 --- /dev/null +++ b/1502-can-make-arithmetic-progression-from-sequence.js @@ -0,0 +1,27 @@ +/** + * 1502. Can Make Arithmetic Progression From Sequence + * https://leetcode.com/problems/can-make-arithmetic-progression-from-sequence/ + * Difficulty: Easy + * + * A sequence of numbers is called an arithmetic progression if the difference + * between any two consecutive elements is the same. + * + * Given an array of numbers arr, return true if the array can be rearranged to + * form an arithmetic progression. Otherwise, return false. + */ + +/** + * @param {number[]} arr + * @return {boolean} + */ +var canMakeArithmeticProgression = function(arr) { + arr.sort((a, b) => a - b); + + for (let i = 2, diff = arr[1] - arr[0]; i < arr.length; i++) { + if (arr[i] - arr[i - 1] !== diff) { + return false; + } + } + + return true; +}; diff --git a/README.md b/README.md index d89a0c01..acb4f065 100644 --- a/README.md +++ b/README.md @@ -174,6 +174,7 @@ 1486|[XOR Operation in an Array](./1486-xor-operation-in-an-array.js)|Easy| 1492|[The kth Factor of n](./1492-the-kth-factor-of-n.js)|Medium| 1496|[Path Crossing](./1496-path-crossing.js)|Easy| +1502|[Can Make Arithmetic Progression From Sequence](./1502-can-make-arithmetic-progression-from-sequence.js)|Easy| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| From c779ef209efe88277a4cbb788416f34656d80732 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 3 Dec 2021 00:11:24 -0600 Subject: [PATCH 188/919] Add solution #1491 --- ...xcluding-the-minimum-and-maximum-salary.js | 21 +++++++++++++++++++ README.md | 1 + 2 files changed, 22 insertions(+) create mode 100644 1491-average-salary-excluding-the-minimum-and-maximum-salary.js diff --git a/1491-average-salary-excluding-the-minimum-and-maximum-salary.js b/1491-average-salary-excluding-the-minimum-and-maximum-salary.js new file mode 100644 index 00000000..a4a4845b --- /dev/null +++ b/1491-average-salary-excluding-the-minimum-and-maximum-salary.js @@ -0,0 +1,21 @@ +/** + * 1491. Average Salary Excluding the Minimum and Maximum Salary + * https://leetcode.com/problems/average-salary-excluding-the-minimum-and-maximum-salary/ + * Difficulty: Easy + * + * Given an array of unique integers salary where salary[i] is the salary of the employee i. + * + * Return the average salary of employees excluding the minimum and maximum salary. + */ + +/** + * @param {number[]} salary + * @return {number} + */ +var average = function(salary) { + salary.sort((a, b) => a - b); + salary.shift(); + salary.pop(); + + return salary.reduce((total, n) => total + n, 0) / salary.length; +}; diff --git a/README.md b/README.md index acb4f065..b8d53d71 100644 --- a/README.md +++ b/README.md @@ -172,6 +172,7 @@ 1480|[Running Sum of 1d Array](./1480-running-sum-of-1d-array.js)|Easy| 1481|[Least Number of Unique Integers after K Removals](./1481-least-number-of-unique-integers-after-k-removals.js)|Medium| 1486|[XOR Operation in an Array](./1486-xor-operation-in-an-array.js)|Easy| +1491|[Average Salary Excluding the Minimum and Maximum Salary](./1491-average-salary-excluding-the-minimum-and-maximum-salary.js)|Easy| 1492|[The kth Factor of n](./1492-the-kth-factor-of-n.js)|Medium| 1496|[Path Crossing](./1496-path-crossing.js)|Easy| 1502|[Can Make Arithmetic Progression From Sequence](./1502-can-make-arithmetic-progression-from-sequence.js)|Easy| From 6099ae2c79ca3670704f65b4427e59038cf245f3 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 3 Dec 2021 00:12:11 -0600 Subject: [PATCH 189/919] Add solution #1493 --- ...barray-of-1s-after-deleting-one-element.js | 29 +++++++++++++++++++ README.md | 1 + 2 files changed, 30 insertions(+) create mode 100644 1493-longest-subarray-of-1s-after-deleting-one-element.js diff --git a/1493-longest-subarray-of-1s-after-deleting-one-element.js b/1493-longest-subarray-of-1s-after-deleting-one-element.js new file mode 100644 index 00000000..c1a11255 --- /dev/null +++ b/1493-longest-subarray-of-1s-after-deleting-one-element.js @@ -0,0 +1,29 @@ +/** + * 1493. Longest Subarray of 1's After Deleting One Element + * https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/ + * Difficulty: Medium + * + * Given a binary array nums, you should delete one element from it. + * + * Return the size of the longest non-empty subarray containing only 1's in the + * resulting array. Return 0 if there is no such subarray. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var longestSubarray = function(nums) { + const grouped = nums.join('').split('0').map(s => s.length); + let max = 0; + + for (let i = 0; i < grouped.length; i++) { + max = Math.max( + max, + (grouped[i - 1] ?? 0) + grouped[i], + grouped[i] + (grouped[i + 1] ?? 0) + ); + } + + return max - (nums.includes(0) ? 0 : 1); +}; diff --git a/README.md b/README.md index b8d53d71..cb3c2dc6 100644 --- a/README.md +++ b/README.md @@ -174,6 +174,7 @@ 1486|[XOR Operation in an Array](./1486-xor-operation-in-an-array.js)|Easy| 1491|[Average Salary Excluding the Minimum and Maximum Salary](./1491-average-salary-excluding-the-minimum-and-maximum-salary.js)|Easy| 1492|[The kth Factor of n](./1492-the-kth-factor-of-n.js)|Medium| +1493|[Longest Subarray of 1's After Deleting One Element](./1493-longest-subarray-of-1s-after-deleting-one-element.js)|Medium| 1496|[Path Crossing](./1496-path-crossing.js)|Easy| 1502|[Can Make Arithmetic Progression From Sequence](./1502-can-make-arithmetic-progression-from-sequence.js)|Easy| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| From bc42c36a05a9bcd057c1889988853fcb9c170cab Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 4 Dec 2021 03:09:47 -0600 Subject: [PATCH 190/919] Add solution #1507 --- 1507-reformat-date.js | 24 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 1507-reformat-date.js diff --git a/1507-reformat-date.js b/1507-reformat-date.js new file mode 100644 index 00000000..179493d6 --- /dev/null +++ b/1507-reformat-date.js @@ -0,0 +1,24 @@ +/** + * 1507. Reformat Date + * https://leetcode.com/problems/reformat-date/ + * Difficulty: Easy + * + * Given a date string in the form Day Month Year, where: + * - Day is in the set {"1st", "2nd", "3rd", "4th", ..., "30th", "31st"}. + * - Month is in the set {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}. + * - Year is in the range [1900, 2100]. + * + * Convert the date string to the format YYYY-MM-DD, where: + * - YYYY denotes the 4 digit year. + * - MM denotes the 2 digit month. + * - DD denotes the 2 digit day. + */ + +/** + * @param {string} date + * @return {string} + */ +var reformatDate = function(date) { + const [_, day, month, year] = date.match(/(\d+)\w+\s+(\w+)\s+(\d+)/); + return new Date(`${day} ${month} ${year}`).toISOString().split('T')[0]; +}; diff --git a/README.md b/README.md index cb3c2dc6..bd0d627a 100644 --- a/README.md +++ b/README.md @@ -177,6 +177,7 @@ 1493|[Longest Subarray of 1's After Deleting One Element](./1493-longest-subarray-of-1s-after-deleting-one-element.js)|Medium| 1496|[Path Crossing](./1496-path-crossing.js)|Easy| 1502|[Can Make Arithmetic Progression From Sequence](./1502-can-make-arithmetic-progression-from-sequence.js)|Easy| +1507|[Reformat Date](./1507-reformat-date.js)|Easy| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| From 2e058b2d8e387b15b0d61f585b2c4cbaeeec1641 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 10 Dec 2021 13:55:06 -0600 Subject: [PATCH 191/919] Add solution #1550 --- 1550-three-consecutive-odds.js | 20 ++++++++++++++++++++ README.md | 1 + 2 files changed, 21 insertions(+) create mode 100644 1550-three-consecutive-odds.js diff --git a/1550-three-consecutive-odds.js b/1550-three-consecutive-odds.js new file mode 100644 index 00000000..3b5a9eb2 --- /dev/null +++ b/1550-three-consecutive-odds.js @@ -0,0 +1,20 @@ +/** + * 1550. Three Consecutive Odds + * https://leetcode.com/problems/three-consecutive-odds/ + * Difficulty: Easy + * + * Given an integer array arr, return true if there are three consecutive odd + * numbers in the array. Otherwise, return false. + */ + +/** + * @param {number[]} arr + * @return {boolean} + */ +var threeConsecutiveOdds = function(arr) { + for (let i = 0, count = 0; i < arr.length; i++) { + count = arr[i] % 2 !== 0 ? count + 1 : 0; + if (count === 3) return true; + } + return false; +}; diff --git a/README.md b/README.md index bd0d627a..c0023bc0 100644 --- a/README.md +++ b/README.md @@ -178,6 +178,7 @@ 1496|[Path Crossing](./1496-path-crossing.js)|Easy| 1502|[Can Make Arithmetic Progression From Sequence](./1502-can-make-arithmetic-progression-from-sequence.js)|Easy| 1507|[Reformat Date](./1507-reformat-date.js)|Easy| +1550|[Three Consecutive Odds](./1550-three-consecutive-odds.js)|Easy| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| From e464e607d091e994a1114433726fc676d34d2ae4 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 10 Dec 2021 13:59:44 -0600 Subject: [PATCH 192/919] Add solution #1551 --- ...-minimum-operations-to-make-array-equal.js | 24 +++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 1551-minimum-operations-to-make-array-equal.js diff --git a/1551-minimum-operations-to-make-array-equal.js b/1551-minimum-operations-to-make-array-equal.js new file mode 100644 index 00000000..4dd409e0 --- /dev/null +++ b/1551-minimum-operations-to-make-array-equal.js @@ -0,0 +1,24 @@ +/** + * 1551. Minimum Operations to Make Array Equal + * https://leetcode.com/problems/minimum-operations-to-make-array-equal/ + * Difficulty: Medium + * + * You have an array arr of length n where arr[i] = (2 * i) + 1 for all valid values + * of i (i.e., 0 <= i < n). + * + * In one operation, you can select two indices x and y where 0 <= x, y < n and subtract + * 1 from arr[x] and add 1 to arr[y] (i.e., perform arr[x] -=1 and arr[y] += 1). The goal + * is to make all the elements of the array equal. It is guaranteed that all the elements + * of the array can be made equal using some operations. + * + * Given an integer n, the length of the array, return the minimum number of operations + * needed to make all the elements of arr equal. + */ + +/** + * @param {number} n + * @return {number} + */ +var minOperations = function(n) { + return n * n / 4; +}; diff --git a/README.md b/README.md index c0023bc0..e7dce5fe 100644 --- a/README.md +++ b/README.md @@ -179,6 +179,7 @@ 1502|[Can Make Arithmetic Progression From Sequence](./1502-can-make-arithmetic-progression-from-sequence.js)|Easy| 1507|[Reformat Date](./1507-reformat-date.js)|Easy| 1550|[Three Consecutive Odds](./1550-three-consecutive-odds.js)|Easy| +1551|[Minimum Operations to Make Array Equal](./1551-minimum-operations-to-make-array-equal.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| From f16e05058876ef67eae42e81874e79968d1cbe9e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 10 Dec 2021 14:20:21 -0600 Subject: [PATCH 193/919] Add solution #1402 --- 1402-reducing-dishes.js | 38 ++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 39 insertions(+) create mode 100644 1402-reducing-dishes.js diff --git a/1402-reducing-dishes.js b/1402-reducing-dishes.js new file mode 100644 index 00000000..76efb338 --- /dev/null +++ b/1402-reducing-dishes.js @@ -0,0 +1,38 @@ +/** + * 1402. Reducing Dishes + * https://leetcode.com/problems/reducing-dishes/ + * Difficulty: Hard + * + * A chef has collected data on the satisfaction level of his n dishes. + * Chef can cook any dish in 1 unit of time. + * + * Like-time coefficient of a dish is defined as the time taken to cook + * that dish including previous dishes multiplied by its satisfaction + * level i.e. time[i] * satisfaction[i]. + * + * Return the maximum sum of like-time coefficient that the chef can + * obtain after dishes preparation. + * + * Dishes can be prepared in any order and the chef can discard some + * dishes to get this maximum value. + */ + +/** + * @param {number[]} satisfaction + * @return {number} + */ +var maxSatisfaction = function(satisfaction) { + let max = 0; + + satisfaction.sort((a, b) => a - b); + + while (satisfaction.length) { + max = Math.max( + max, + satisfaction.reduce((total, n, i) => total + n * (i + 1), 0) + ); + satisfaction.shift(); + } + + return max; +}; diff --git a/README.md b/README.md index e7dce5fe..8ab8de3e 100644 --- a/README.md +++ b/README.md @@ -154,6 +154,7 @@ 1374|[Generate a String With Characters That Have Odd Counts](./1374-generate-a-string-with-characters-that-have-odd-counts.js)|Easy| 1380|[Lucky Numbers in a Matrix](./1380-lucky-numbers-in-a-matrix.js)|Easy| 1389|[Create Target Array in the Given Order](./1389-create-target-array-in-the-given-order.js)|Easy| +1402|[Reducing Dishes](./1402-reducing-dishes.js)|Hard| 1408|[String Matching in an Array](./1408-string-matching-in-an-array.js)|Easy| 1410|[HTML Entity Parser](./1410-html-entity-parser.js)|Medium| 1436|[Destination City](./1436-destination-city.js)|Easy| From 6d05e88c183fc6ee660bf2082d97ba3b60ea00a7 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 26 Dec 2021 14:18:28 -0500 Subject: [PATCH 194/919] Add solution #9 --- 0009-palindrome-number.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/0009-palindrome-number.js b/0009-palindrome-number.js index e696c444..a4691dc2 100644 --- a/0009-palindrome-number.js +++ b/0009-palindrome-number.js @@ -4,9 +4,9 @@ * Difficulty: Easy * * Given an integer `x`, return `true` if `x` is palindrome integer. - -An integer is a palindrome when it reads the same backward as forward. -For example, `121` is palindrome while `123` is not. + * + * An integer is a palindrome when it reads the same backward as forward. + * - For example, `121` is palindrome while `123` is not. */ /** From c1385f61869e6a70f9d305d3e5f5e6d7c00edb5a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 26 Dec 2021 15:18:24 -0500 Subject: [PATCH 195/919] Add solution #133 --- 0133-clone-graph.js | 48 +++++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 49 insertions(+) create mode 100644 0133-clone-graph.js diff --git a/0133-clone-graph.js b/0133-clone-graph.js new file mode 100644 index 00000000..3aa5c44c --- /dev/null +++ b/0133-clone-graph.js @@ -0,0 +1,48 @@ +/** + * 133. Clone Graph + * https://leetcode.com/problems/clone-graph/ + * Difficulty: Medium + * + * Given a reference of a node in a connected undirected graph. + * Return a deep copy (clone) of the graph. + * Each node in the graph contains a value (int) and a list (List[Node]) of its neighbors. + * + * Test case format: + * - For simplicity, each node's value is the same as the node's index (1-indexed). + * For example, the first node with val == 1, the second node with val == 2, and so on. + * The graph is represented in the test case using an adjacency list. + * + * - An adjacency list is a collection of unordered lists used to represent a finite graph. + * Each list describes the set of neighbors of a node in the graph. + * + * - The given node will always be the first node with val = 1. You must return the copy of + * the given node as a reference to the cloned graph. + */ + +/** + * // Definition for a Node. + * function Node(val, neighbors) { + * this.val = val === undefined ? 0 : val; + * this.neighbors = neighbors === undefined ? [] : neighbors; + * }; + */ + +/** + * @param {Node} node + * @return {Node} + */ +var cloneGraph = function(node) { + const map = new Map(); + return node && cloneNode(node, map); +}; + +function cloneNode(node, map) { + const cloned = new Node(node.val, node.neighbors); + map.set(node.val, cloned); + + cloned.neighbors = node.neighbors && node.neighbors.map(n => { + return map.get(n.val) || cloneNode(n, map); + }); + + return cloned; +} diff --git a/README.md b/README.md index 8ab8de3e..fe4651fb 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,7 @@ 118|[Pascal's Triangle](./0118-pascals-triangle.js)|Easy| 119|[Pascal's Triangle II](./0119-pascals-triangle-ii.js)|Easy| 121|[Best Time to Buy and Sell Stock](./0121-best-time-to-buy-and-sell-stock.js)|Easy| +133|[Clone Graph](./0133-clone-graph.js)|Medium| 136|[Single Number](./0136-single-number.js)|Easy| 141|[Linked List Cycle](./0141-linked-list-cycle.js)|Easy| 144|[Binary Tree Preorder Traversal](./0144-binary-tree-preorder-traversal.js)|Easy| From c9cb8599101f89e40bfd43d146fc758a63f1fd33 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 26 Dec 2021 16:53:22 -0500 Subject: [PATCH 196/919] Add solution #28 --- 0028-implement-strstr.js | 26 ++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 27 insertions(+) create mode 100644 0028-implement-strstr.js diff --git a/0028-implement-strstr.js b/0028-implement-strstr.js new file mode 100644 index 00000000..f7cc484e --- /dev/null +++ b/0028-implement-strstr.js @@ -0,0 +1,26 @@ +/** + * 28. Implement strStr() + * https://leetcode.com/problems/implement-strstr/ + * Difficulty: Easy + * + * Return the index of the first occurrence of needle in haystack, or -1 if needle + * is not part of haystack. + * + * Clarification: + * - What should we return when needle is an empty string? This is a great question + * to ask during an interview. + * + * - For the purpose of this problem, we will return 0 when needle is an empty string. + * This is consistent to C's strstr() and Java's indexOf(). + */ + +/** + * @param {string} haystack + * @param {string} needle + * @return {number} + */ +var strStr = function(haystack, needle) { + if (!needle) return 0; + const split = haystack.split(needle); + return split.length > 1 ? split[0].length : -1; +}; diff --git a/README.md b/README.md index fe4651fb..49db8d65 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,7 @@ 20|[Valid Parentheses](./0020-valid-parentheses.js)|Easy| 21|[Merge Two Sorted Lists](./0021-merge-two-sorted-lists.js)|Easy| 27|[Remove Element](./0027-remove-element.js)|Easy| +28|[Implement strStr()](./0028-implement-strstr.js)|Easy| 31|[Next Permutation](./0031-next-permutation.js)|Medium| 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| 41|[First Missing Positive](./0041-first-missing-positive.js)|Hard| From 3e934d313fce646ce9496dce84da43f3d8b0200a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 26 Dec 2021 17:09:50 -0500 Subject: [PATCH 197/919] Add solution #214 --- 0214-shortest-palindrome.js | 24 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 0214-shortest-palindrome.js diff --git a/0214-shortest-palindrome.js b/0214-shortest-palindrome.js new file mode 100644 index 00000000..955ae2d8 --- /dev/null +++ b/0214-shortest-palindrome.js @@ -0,0 +1,24 @@ +/** + * 214. Shortest Palindrome + * https://leetcode.com/problems/shortest-palindrome/ + * Difficulty: Hard + * + * You are given a string s. You can convert s to a palindrome by adding characters + * in front of it. + * + * Return the shortest palindrome you can find by performing this transformation. + */ + +/** + * @param {string} s + * @return {string} + */ +var shortestPalindrome = function(s) { + const reversed = s.split('').reverse().join(''); + for (let i = s.length; i > 0; i--) { + if (s.slice(0, i) === reversed.slice(s.length - i)) { + return reversed.slice(0, reversed.length - i) + s; + } + } + return ''; +}; diff --git a/README.md b/README.md index 49db8d65..1e4dfba4 100644 --- a/README.md +++ b/README.md @@ -61,6 +61,7 @@ 191|[Number of 1 Bits](./0191-number-of-1-bits.js)|Easy| 203|[Remove Linked List Elements](./0203-remove-linked-list-elements.js)|Easy| 206|[Reverse Linked List](./0206-reverse-linked-list.js)|Easy| +214|[Shortest Palindrome](./0214-shortest-palindrome.js)|Hard| 217|[Contains Duplicate](./0217-contains-duplicate.js)|Easy| 219|[Contains Duplicate II](./0219-contains-duplicate-ii.js)|Easy| 225|[Implement Stack using Queues](./0225-implement-stack-using-queues.js)|Easy| From ee0545a716a4fd92a46d05bc3195544e1bbae3d2 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 26 Dec 2021 17:20:14 -0500 Subject: [PATCH 198/919] Add solution #796 --- 0796-rotate-string.js | 25 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 26 insertions(+) create mode 100644 0796-rotate-string.js diff --git a/0796-rotate-string.js b/0796-rotate-string.js new file mode 100644 index 00000000..a9d77ee8 --- /dev/null +++ b/0796-rotate-string.js @@ -0,0 +1,25 @@ +/** + * 796. Rotate String + * https://leetcode.com/problems/rotate-string/ + * Difficulty: Easy + * + * 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. + */ + +/** + * @param {string} s + * @param {string} goal + * @return {boolean} + */ +var rotateString = function(s, goal) { + for (let i = 0; i < s.length; i++) { + if (s.slice(i) + s.slice(0, i) === goal) return true; + } + return false; +}; diff --git a/README.md b/README.md index 1e4dfba4..2d436b01 100644 --- a/README.md +++ b/README.md @@ -105,6 +105,7 @@ 722|[Remove Comments](./0722-remove-comments.js)|Medium| 739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium| 791|[Custom Sort String](./0791-custom-sort-string.js)|Medium| +796|[Rotate String](./0796-rotate-string.js)|Easy| 804|[Unique Morse Code Words](./0804-unique-morse-code-words.js)|Easy| 819|[Most Common Word](./0819-most-common-word.js)|Easy| 821|[Shortest Distance to a Character](./0821-shortest-distance-to-a-character.js)|Easy| From 2e263486d00c0a508966826f125b6c670cb60440 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 26 Dec 2021 17:32:52 -0500 Subject: [PATCH 199/919] Add solution #500 --- 0500-keyboard-row.js | 22 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 0500-keyboard-row.js diff --git a/0500-keyboard-row.js b/0500-keyboard-row.js new file mode 100644 index 00000000..f6868ab7 --- /dev/null +++ b/0500-keyboard-row.js @@ -0,0 +1,22 @@ +/** + * 500. Keyboard Row + * https://leetcode.com/problems/keyboard-row/ + * Difficulty: Easy + * + * Given an array of strings words, return the words that can be typed using letters + * of the alphabet on only one row of American keyboard like the image below. + * + * In the American keyboard: + * - the first row consists of the characters "qwertyuiop", + * - the second row consists of the characters "asdfghjkl", and + * - the third row consists of the characters "zxcvbnm". + */ + +/** + * @param {string[]} words + * @return {string[]} + */ +var findWords = function(words) { + const rows = ['qwertyuiop', 'asdfghjkl', 'zxcvbnm']; + return words.filter(word => rows.some(row => word.toLowerCase().split('').every(s => row.includes(s)))); +}; diff --git a/README.md b/README.md index 2d436b01..2ad3918c 100644 --- a/README.md +++ b/README.md @@ -89,6 +89,7 @@ 448|[Find All Numbers Disappeared in an Array](./0448-find-all-numbers-disappeared-in-an-array.js)|Easy| 451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| 459|[Repeated Substring Pattern](./0459-repeated-substring-pattern.js)|Easy| +500|[Keyboard Row](./0500-keyboard-row.js)|Easy| 541|[Reverse String II](./0541-reverse-string-ii.js)|Easy| 551|[Student Attendance Record I](./0551-student-attendance-record-i.js)|Easy| 565|[Array Nesting](./0565-array-nesting.js)|Medium| From 3e05e3f79f53b17968e131539e42d9416c688b43 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 26 Dec 2021 17:40:04 -0500 Subject: [PATCH 200/919] Add solution #1935 --- 1935-maximum-number-of-words-you-can-type.js | 25 ++++++++++++++++++++ README.md | 1 + 2 files changed, 26 insertions(+) create mode 100644 1935-maximum-number-of-words-you-can-type.js diff --git a/1935-maximum-number-of-words-you-can-type.js b/1935-maximum-number-of-words-you-can-type.js new file mode 100644 index 00000000..5f530a5b --- /dev/null +++ b/1935-maximum-number-of-words-you-can-type.js @@ -0,0 +1,25 @@ +/** + * 1935. Maximum Number of Words You Can Type + * https://leetcode.com/problems/maximum-number-of-words-you-can-type/ + * Difficulty: Easy + * + * There is a malfunctioning keyboard where some letter keys do not work. + * All other keys on the keyboard work properly. + * + * Given a string text of words separated by a single space (no leading or + * trailing spaces) and a string brokenLetters of all distinct letter keys + * that are broken, return the number of words in text you can fully type + * using this keyboard. + */ + +/** + * @param {string} text + * @param {string} brokenLetters + * @return {number} + */ +var canBeTypedWords = function(text, brokenLetters) { + return text + .split(/\s+/) + .filter(word => !brokenLetters.split('').some(s => word.includes(s))) + .length; +}; diff --git a/README.md b/README.md index 2ad3918c..270c1013 100644 --- a/README.md +++ b/README.md @@ -190,6 +190,7 @@ 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1929|[Concatenation of Array](./1929-concatenation-of-array.js)|Easy| +1935|[Maximum Number of Words You Can Type](./1935-maximum-number-of-words-you-can-type.js)|Easy| 2000|[Reverse Prefix of Word](./2000-reverse-prefix-of-word.js)|Easy| 2016|[Maximum Difference Between Increasing Elements](./2016-maximum-difference-between-increasing-elements.js)|Easy| From fe362a8a04af7eccf961319f5e7ceeeaf654bc54 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 27 Dec 2021 15:44:08 -0500 Subject: [PATCH 201/919] Add solution #1668 --- 1668-maximum-repeating-substring.js | 24 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 1668-maximum-repeating-substring.js diff --git a/1668-maximum-repeating-substring.js b/1668-maximum-repeating-substring.js new file mode 100644 index 00000000..d08ce8bf --- /dev/null +++ b/1668-maximum-repeating-substring.js @@ -0,0 +1,24 @@ +/** + * 1668. Maximum Repeating Substring + * https://leetcode.com/problems/maximum-repeating-substring/ + * Difficulty: Easy + * + * For a string sequence, a string word is k-repeating if word concatenated k times is a substring + * of sequence. The word's maximum k-repeating value is the highest value k where word is k-repeating + * in sequence. If word is not a substring of sequence, word's maximum k-repeating value is 0. + * + * Given strings sequence and word, return the maximum k-repeating value of word in sequence. + */ + +/** + * @param {string} sequence + * @param {string} word + * @return {number} + */ +var maxRepeating = function(sequence, word) { + let count = Math.floor(sequence.length / word.length) + 1; + while (--count) { + if (sequence.includes(word.repeat(count))) return count; + } + return count; +}; diff --git a/README.md b/README.md index 270c1013..01e94833 100644 --- a/README.md +++ b/README.md @@ -187,6 +187,7 @@ 1550|[Three Consecutive Odds](./1550-three-consecutive-odds.js)|Easy| 1551|[Minimum Operations to Make Array Equal](./1551-minimum-operations-to-make-array-equal.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| +1668|[Maximum Repeating Substring](./1668-maximum-repeating-substring.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1929|[Concatenation of Array](./1929-concatenation-of-array.js)|Easy| From a67b067d1135d47614964f6549c167376a9ee60d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 27 Dec 2021 16:06:32 -0500 Subject: [PATCH 202/919] Add solution #1566 --- ...rn-of-length-m-repeated-k-or-more-times.js | 28 +++++++++++++++++++ README.md | 1 + 2 files changed, 29 insertions(+) create mode 100644 1566-detect-pattern-of-length-m-repeated-k-or-more-times.js diff --git a/1566-detect-pattern-of-length-m-repeated-k-or-more-times.js b/1566-detect-pattern-of-length-m-repeated-k-or-more-times.js new file mode 100644 index 00000000..cd92cd8d --- /dev/null +++ b/1566-detect-pattern-of-length-m-repeated-k-or-more-times.js @@ -0,0 +1,28 @@ +/** + * 1566. Detect Pattern of Length M Repeated K or More Times + * https://leetcode.com/problems/detect-pattern-of-length-m-repeated-k-or-more-times/ + * Difficulty: Easy + * + * Given an array of positive integers arr, find a pattern of length m that is repeated k or more times. + * + * A pattern is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple + * times consecutively without overlapping. A pattern is defined by its length and the number of repetitions. + * + * Return true if there exists a pattern of length m that is repeated k or more times, otherwise return false. + */ + +/** + * @param {number[]} arr + * @param {number} m + * @param {number} k + * @return {boolean} + */ +var containsPattern = function(arr, m, k) { + for (let i = 0; i < arr.length - m + 1; i++) { + const pattern = new Array(k).fill(arr.slice(i, i + m).join()).join(); + if (arr.join().includes(pattern)) { + return true; + } + } + return false; +}; diff --git a/README.md b/README.md index 01e94833..05569919 100644 --- a/README.md +++ b/README.md @@ -186,6 +186,7 @@ 1507|[Reformat Date](./1507-reformat-date.js)|Easy| 1550|[Three Consecutive Odds](./1550-three-consecutive-odds.js)|Easy| 1551|[Minimum Operations to Make Array Equal](./1551-minimum-operations-to-make-array-equal.js)|Medium| +1566|[Detect Pattern of Length M Repeated K or More Times](./1566-detect-pattern-of-length-m-repeated-k-or-more-times.js)|Easy| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1668|[Maximum Repeating Substring](./1668-maximum-repeating-substring.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| From 56bb1d77d1ab7e54f4bf4e8e807336cd25195519 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 27 Dec 2021 17:56:57 -0500 Subject: [PATCH 203/919] Add solution #476 --- 0476-number-complement.js | 21 +++++++++++++++++++++ README.md | 1 + 2 files changed, 22 insertions(+) create mode 100644 0476-number-complement.js diff --git a/0476-number-complement.js b/0476-number-complement.js new file mode 100644 index 00000000..2cb0135c --- /dev/null +++ b/0476-number-complement.js @@ -0,0 +1,21 @@ +/** + * 476. Number Complement + * https://leetcode.com/problems/number-complement/ + * Difficulty: Easy + * + * The complement of an integer is the integer you get when you flip all the 0's to 1's + * and all the 1's to 0's in its binary representation. + * + * For example, The integer 5 is "101" in binary and its complement is "010" which is + * the integer 2. + * + * Given an integer num, return its complement. + */ + +/** + * @param {number} num + * @return {number} + */ +var findComplement = function(num) { + return parseInt(num.toString(2).split('').map(n => 1 - n).join(''), 2); +}; diff --git a/README.md b/README.md index 05569919..19361219 100644 --- a/README.md +++ b/README.md @@ -89,6 +89,7 @@ 448|[Find All Numbers Disappeared in an Array](./0448-find-all-numbers-disappeared-in-an-array.js)|Easy| 451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| 459|[Repeated Substring Pattern](./0459-repeated-substring-pattern.js)|Easy| +476|[Number Complement](./0476-number-complement.js)|Easy| 500|[Keyboard Row](./0500-keyboard-row.js)|Easy| 541|[Reverse String II](./0541-reverse-string-ii.js)|Easy| 551|[Student Attendance Record I](./0551-student-attendance-record-i.js)|Easy| From 052ad7502597617c9c98802e9cb55d2d5ef41b74 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 27 Dec 2021 19:49:16 -0500 Subject: [PATCH 204/919] Add solution #19 --- 0019-remove-nth-node-from-end-of-list.js | 40 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 41 insertions(+) create mode 100644 0019-remove-nth-node-from-end-of-list.js diff --git a/0019-remove-nth-node-from-end-of-list.js b/0019-remove-nth-node-from-end-of-list.js new file mode 100644 index 00000000..1e133150 --- /dev/null +++ b/0019-remove-nth-node-from-end-of-list.js @@ -0,0 +1,40 @@ +/** + * 19. Remove Nth Node From End of List + * https://leetcode.com/problems/remove-nth-node-from-end-of-list/ + * Difficulty: Medium + * + * Given the head of a linked list, remove the nth node from the end of the list + * and return its head. + */ + +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @param {number} n + * @return {ListNode} + */ +var removeNthFromEnd = function(head, n) { + const result = new ListNode(); + let slow = result; + let fast = result; + slow.next = head; + + for (let i = 0; i <= n; i++) { + fast = fast.next; + } + + while (fast) { + fast = fast.next; + slow = slow.next; + } + + slow.next = slow.next.next; + + return result.next; +}; diff --git a/README.md b/README.md index 19361219..d54219ee 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ 13|[Roman to Integer](./0013-roman-to-integer.js)|Easy| 14|[Longest Common Prefix](./0014-longest-common-prefix.js)|Easy| 17|[Letter Combinations of a Phone Number](./0017-letter-combinations-of-a-phone-number.js)|Medium| +19|[Remove Nth Node From End of List](./0019-remove-nth-node-from-end-of-list.js)|Medium| 20|[Valid Parentheses](./0020-valid-parentheses.js)|Easy| 21|[Merge Two Sorted Lists](./0021-merge-two-sorted-lists.js)|Easy| 27|[Remove Element](./0027-remove-element.js)|Easy| From 105fa39262d2248a1947744eda5ad366a94a13d6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 27 Dec 2021 20:02:53 -0500 Subject: [PATCH 205/919] Add solution #22 --- 0022-generate-parentheses.js | 28 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 29 insertions(+) create mode 100644 0022-generate-parentheses.js diff --git a/0022-generate-parentheses.js b/0022-generate-parentheses.js new file mode 100644 index 00000000..d3264697 --- /dev/null +++ b/0022-generate-parentheses.js @@ -0,0 +1,28 @@ +/** + * 22. Generate Parentheses + * https://leetcode.com/problems/generate-parentheses/ + * Difficulty: Medium + * + * Given n pairs of parentheses, write a function to generate all combinations of + * well-formed parentheses. + */ + +/** + * @param {number} n + * @return {string[]} + */ +var generateParenthesis = function(n) { + const result = []; + backtrack(result, '', 0, 0, n); + return result; +}; + +function backtrack(result, str, open, close, max) { + if (str.length == max * 2){ + result.push(str); + return; + } + + if (open < max) backtrack(result, `${str}(`, open + 1, close, max); + if (close < open) backtrack(result, `${str})`, open, close + 1, max); +} diff --git a/README.md b/README.md index d54219ee..7cbc7df1 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,7 @@ 19|[Remove Nth Node From End of List](./0019-remove-nth-node-from-end-of-list.js)|Medium| 20|[Valid Parentheses](./0020-valid-parentheses.js)|Easy| 21|[Merge Two Sorted Lists](./0021-merge-two-sorted-lists.js)|Easy| +22|[Generate Parentheses](./0022-generate-parentheses.js)|Medium| 27|[Remove Element](./0027-remove-element.js)|Easy| 28|[Implement strStr()](./0028-implement-strstr.js)|Easy| 31|[Next Permutation](./0031-next-permutation.js)|Medium| From cc373f1be9c54fb3a3cec61815b1ed9bddec5373 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 27 Dec 2021 20:16:37 -0500 Subject: [PATCH 206/919] Add solution #98 --- 0098-validate-binary-search-tree.js | 40 +++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 41 insertions(+) create mode 100644 0098-validate-binary-search-tree.js diff --git a/0098-validate-binary-search-tree.js b/0098-validate-binary-search-tree.js new file mode 100644 index 00000000..73c8d164 --- /dev/null +++ b/0098-validate-binary-search-tree.js @@ -0,0 +1,40 @@ +/** + * 98. Validate Binary Search Tree + * https://leetcode.com/problems/validate-binary-search-tree/ + * Difficulty: Medium + * + * Given the root of a binary tree, determine if it is a valid binary search tree (BST). + * + * A valid BST is defined as follows: + * - The left subtree of a node contains only nodes with keys less than the node's key. + * - The right subtree of a node contains only nodes with keys greater than the node's key. + * - Both the left and right subtrees must also be binary search trees. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {boolean} + */ +var isValidBST = function(root) { + return traverse(root, null, null); +}; + +function traverse(root, min, max) { + if (!root) { + return true; + } + + if ((min !== null && root.val <= min) || (max !== null && root.val >= max)) { + return false; + } + + return traverse(root.left, min, root.val) && traverse(root.right, root.val, max); +} diff --git a/README.md b/README.md index 7cbc7df1..e2f85ad4 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,7 @@ 83|[Remove Duplicates from Sorted List](./0083-remove-duplicates-from-sorted-list.js)|Easy| 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| 94|[Binary Tree Inorder Traversal](./0094-binary-tree-inorder-traversal.js)|Easy| +98|[Validate Binary Search Tree](./0098-validate-binary-search-tree.js)|Medium| 101|[Symmetric Tree](./0101-symmetric-tree.js)|Easy| 102|[Binary Tree Level Order Traversal](./0102-binary-tree-level-order-traversal.js)|Medium| 104|[Maximum Depth of Binary Tree](./0104-maximum-depth-of-binary-tree.js)|Easy| From a6226c175aaebf1fe99fa5087258b9e02f6e2f9e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 27 Dec 2021 20:32:33 -0500 Subject: [PATCH 207/919] Add solution #24 --- 0024-swap-nodes-in-pairs.js | 31 +++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 0024-swap-nodes-in-pairs.js diff --git a/0024-swap-nodes-in-pairs.js b/0024-swap-nodes-in-pairs.js new file mode 100644 index 00000000..39a27600 --- /dev/null +++ b/0024-swap-nodes-in-pairs.js @@ -0,0 +1,31 @@ +/** + * 24. Swap Nodes in Pairs + * https://leetcode.com/problems/swap-nodes-in-pairs/ + * Difficulty: Medium + * + * Given a linked list, swap every two adjacent nodes and return its head. You must solve the + * problem without modifying the values in the list's nodes (i.e., only nodes themselves may + * be changed.) + */ + +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ +var swapPairs = function(head) { + if (!head || !head.next) return head; + + const result = head.next; + head.next = result.next; + result.next = head; + head.next = swapPairs(head.next); + + return result; +}; diff --git a/README.md b/README.md index e2f85ad4..892d90f9 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,7 @@ 20|[Valid Parentheses](./0020-valid-parentheses.js)|Easy| 21|[Merge Two Sorted Lists](./0021-merge-two-sorted-lists.js)|Easy| 22|[Generate Parentheses](./0022-generate-parentheses.js)|Medium| +24|[Swap Nodes in Pairs](./0024-swap-nodes-in-pairs.js)|Medium| 27|[Remove Element](./0027-remove-element.js)|Easy| 28|[Implement strStr()](./0028-implement-strstr.js)|Easy| 31|[Next Permutation](./0031-next-permutation.js)|Medium| From 7c1875662ce21ad0c9a6f568f92fa4cd9adb6e5a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 28 Dec 2021 20:50:36 -0500 Subject: [PATCH 208/919] Add solution #128 --- 0128-longest-consecutive-sequence.js | 31 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 0128-longest-consecutive-sequence.js diff --git a/0128-longest-consecutive-sequence.js b/0128-longest-consecutive-sequence.js new file mode 100644 index 00000000..b72a6fe5 --- /dev/null +++ b/0128-longest-consecutive-sequence.js @@ -0,0 +1,31 @@ +/** + * 128. Longest Consecutive Sequence + * https://leetcode.com/problems/longest-consecutive-sequence/ + * Difficulty: Medium + * + * Given an unsorted array of integers nums, return the length of the + * longest consecutive elements sequence. + * + * You must write an algorithm that runs in O(n) time. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var longestConsecutive = function(nums) { + const set = new Set(nums); + let result = 0; + + for (let i = 0; i < nums.length; i++) { + if (!set.has(nums[i] - 1)) { + let streak = 1; + while (set.has(nums[i] + streak)) { + streak++; + } + result = Math.max(result, streak); + } + } + + return result; +}; diff --git a/README.md b/README.md index 892d90f9..180bb46d 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,7 @@ 118|[Pascal's Triangle](./0118-pascals-triangle.js)|Easy| 119|[Pascal's Triangle II](./0119-pascals-triangle-ii.js)|Easy| 121|[Best Time to Buy and Sell Stock](./0121-best-time-to-buy-and-sell-stock.js)|Easy| +128|[Longest Consecutive Sequence](./0128-longest-consecutive-sequence.js)|Medium| 133|[Clone Graph](./0133-clone-graph.js)|Medium| 136|[Single Number](./0136-single-number.js)|Easy| 141|[Linked List Cycle](./0141-linked-list-cycle.js)|Easy| From 390f9d78949719f6b6d4c3796afee6765c6fc60b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 28 Dec 2021 21:28:05 -0500 Subject: [PATCH 209/919] Add solution #169 --- 0169-majority-element.js | 22 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 0169-majority-element.js diff --git a/0169-majority-element.js b/0169-majority-element.js new file mode 100644 index 00000000..bad659bd --- /dev/null +++ b/0169-majority-element.js @@ -0,0 +1,22 @@ +/** + * 169. Majority Element + * https://leetcode.com/problems/majority-element/ + * Difficulty: Easy + * + * Given an array nums of size n, return the majority element. + * + * The majority element is the element that appears more than ⌊n / 2⌋ times. + * You may assume that the majority element always exists in the array. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var majorityElement = function(nums) { + const map = new Map(); + nums.forEach(n => map.set(n, (map.get(n) || 0) + 1)); + + const sorted = [...map].sort(([,a], [,b]) => b - a); + return sorted[0][0]; +}; diff --git a/README.md b/README.md index 180bb46d..2923d6d0 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,7 @@ 145|[Binary Tree Postorder Traversal](./0145-binary-tree-postorder-traversal.js)|Easy| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| +169|[Majority Element](./0169-majority-element.js)|Easy| 179|[Largest Number](./0179-largest-number.js)|Medium| 191|[Number of 1 Bits](./0191-number-of-1-bits.js)|Easy| 203|[Remove Linked List Elements](./0203-remove-linked-list-elements.js)|Easy| From 9d8bf8a8f0a421df49792bab990e317c6da3a5e5 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 28 Dec 2021 21:36:47 -0500 Subject: [PATCH 210/919] Add solution #229 --- 0229-majority-element-ii.js | 20 ++++++++++++++++++++ README.md | 1 + 2 files changed, 21 insertions(+) create mode 100644 0229-majority-element-ii.js diff --git a/0229-majority-element-ii.js b/0229-majority-element-ii.js new file mode 100644 index 00000000..f3ce6493 --- /dev/null +++ b/0229-majority-element-ii.js @@ -0,0 +1,20 @@ +/** + * 229. Majority Element II + * https://leetcode.com/problems/majority-element-ii/ + * Difficulty: Medium + * + * Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. + */ + +/** + * @param {number[]} nums + * @return {number[]} + */ +var majorityElement = function(nums) { + const map = new Map(); + nums.forEach(n => map.set(n, (map.get(n) || 0) + 1)); + + return [...map] + .filter(([key, value]) => value > nums.length / 3) + .map(([key]) => key); +}; diff --git a/README.md b/README.md index 2923d6d0..1c6aea68 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,7 @@ 219|[Contains Duplicate II](./0219-contains-duplicate-ii.js)|Easy| 225|[Implement Stack using Queues](./0225-implement-stack-using-queues.js)|Easy| 226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy| +229|[Majority Element II](./0229-majority-element-ii.js)|Medium| 231|[Power of Two](./0231-power-of-two.js)|Easy| 232|[Implement Queue using Stacks](./0232-implement-queue-using-stacks.js)|Easy| 234|[Palindrome Linked List](./0234-palindrome-linked-list.js)|Easy| From 43bc233e57eb6efb310e0361f79f6cf8ac7f2b5e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 30 Dec 2021 17:28:12 -0500 Subject: [PATCH 211/919] Add solution #33 --- 0033-search-in-rotated-sorted-array.js | 44 ++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 45 insertions(+) create mode 100644 0033-search-in-rotated-sorted-array.js diff --git a/0033-search-in-rotated-sorted-array.js b/0033-search-in-rotated-sorted-array.js new file mode 100644 index 00000000..632b7e3c --- /dev/null +++ b/0033-search-in-rotated-sorted-array.js @@ -0,0 +1,44 @@ +/** + * 33. Search in Rotated Sorted Array + * https://leetcode.com/problems/search-in-rotated-sorted-array/ + * Difficulty: Medium + * + * There is an integer array nums sorted in ascending order (with distinct values). + * + * Prior to being passed to your function, nums is possibly rotated at an unknown pivot + * index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], + * ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] + * might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. + * + * Given the array nums after the possible rotation and an integer target, return the index + * of target if it is in nums, or -1 if it is not in nums. + * + * You must write an algorithm with O(log n) runtime complexity. + */ + +/** + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +var search = function(nums, target) { + let start = 0; + let end = nums.length; + + while (start < end) { + const i = Math.floor((start + end) / 2); + const middle = nums[i] < nums[0] === target < nums[0] + ? nums[i] + : target < nums[0] ? -Infinity : Infinity; + + if (middle < target) { + start = i + 1; + } else if (middle > target) { + end = i; + } else { + return i; + } + } + + return -1; +}; diff --git a/README.md b/README.md index 1c6aea68..908369b4 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,7 @@ 27|[Remove Element](./0027-remove-element.js)|Easy| 28|[Implement strStr()](./0028-implement-strstr.js)|Easy| 31|[Next Permutation](./0031-next-permutation.js)|Medium| +33|[Search in Rotated Sorted Array](./0033-search-in-rotated-sorted-array.js)|Medium| 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| 41|[First Missing Positive](./0041-first-missing-positive.js)|Hard| 42|[Trapping Rain Water](./0042-trapping-rain-water.js)|Hard| From 1ff72319ea2ebd2e0188b9478c9f85aa3089f4e5 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 30 Dec 2021 17:46:41 -0500 Subject: [PATCH 212/919] Add solution #35 --- 0035-search-insert-position.js | 32 ++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 0035-search-insert-position.js diff --git a/0035-search-insert-position.js b/0035-search-insert-position.js new file mode 100644 index 00000000..bb8fe77a --- /dev/null +++ b/0035-search-insert-position.js @@ -0,0 +1,32 @@ +/** + * 35. Search Insert Position + * https://leetcode.com/problems/search-insert-position/ + * Difficulty: Easy + * + * Given a sorted array of distinct integers and a target value, return the + * index if the target is found. If not, return the index where it would be + * if it were inserted in order. + * + * You must write an algorithm with O(log n) runtime complexity. + */ + +/** + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +var searchInsert = function(nums, target) { + let start = 0; + let end = nums.length - 1; + + while (start <= end) { + const middle = Math.floor((start + end) / 2); + if (target > nums[middle]) { + start = middle + 1; + } else { + end = middle - 1; + } + } + + return start; +}; diff --git a/README.md b/README.md index 908369b4..53606f99 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,7 @@ 28|[Implement strStr()](./0028-implement-strstr.js)|Easy| 31|[Next Permutation](./0031-next-permutation.js)|Medium| 33|[Search in Rotated Sorted Array](./0033-search-in-rotated-sorted-array.js)|Medium| +35|[Search Insert Position](./0035-search-insert-position.js)|Easy| 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| 41|[First Missing Positive](./0041-first-missing-positive.js)|Hard| 42|[Trapping Rain Water](./0042-trapping-rain-water.js)|Hard| From 8b3539560319c47af83f68bfbc77744bb1f4184b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 30 Dec 2021 17:57:06 -0500 Subject: [PATCH 213/919] Add solution #34 --- ...ast-position-of-element-in-sorted-array.js | 40 +++++++++++++++++++ README.md | 1 + 2 files changed, 41 insertions(+) create mode 100644 0034-find-first-and-last-position-of-element-in-sorted-array.js diff --git a/0034-find-first-and-last-position-of-element-in-sorted-array.js b/0034-find-first-and-last-position-of-element-in-sorted-array.js new file mode 100644 index 00000000..11d61353 --- /dev/null +++ b/0034-find-first-and-last-position-of-element-in-sorted-array.js @@ -0,0 +1,40 @@ +/** + * 34. Find First and Last Position of Element in Sorted Array + * https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/ + * Difficulty: Medium + * + * Given an array of integers nums sorted in non-decreasing order, find the starting and + * ending position of a given target value. + * + * If target is not found in the array, return [-1, -1]. + * + * You must write an algorithm with O(log n) runtime complexity. + */ + +/** + * @param {number[]} nums + * @param {number} target + * @return {number[]} + */ +var searchRange = function(nums, target) { + let start = 0; + let end = nums.length - 1; + + while (start <= end) { + const middle = Math.floor((start + end) / 2); + if (target > nums[middle]) { + start = middle + 1; + } else { + end = middle - 1; + } + } + + if (nums[start] !== target) { + return [-1, -1]; + } + + while (nums[start - 1] === target) start--; + while (nums[end + 1] === target) end++; + + return [start, end]; +}; diff --git a/README.md b/README.md index 53606f99..b092a0eb 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,7 @@ 28|[Implement strStr()](./0028-implement-strstr.js)|Easy| 31|[Next Permutation](./0031-next-permutation.js)|Medium| 33|[Search in Rotated Sorted Array](./0033-search-in-rotated-sorted-array.js)|Medium| +34|[Find First and Last Position of Element in Sorted Array](./0034-find-first-and-last-position-of-element-in-sorted-array.js)|Medium| 35|[Search Insert Position](./0035-search-insert-position.js)|Easy| 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| 41|[First Missing Positive](./0041-first-missing-positive.js)|Hard| From b4c51d54094d399f25173299b677ffde4db38336 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 30 Dec 2021 18:11:11 -0500 Subject: [PATCH 214/919] Add solution #116 --- ...lating-next-right-pointers-in-each-node.js | 50 +++++++++++++++++++ README.md | 1 + 2 files changed, 51 insertions(+) create mode 100644 0116-populating-next-right-pointers-in-each-node.js diff --git a/0116-populating-next-right-pointers-in-each-node.js b/0116-populating-next-right-pointers-in-each-node.js new file mode 100644 index 00000000..a6efdcbc --- /dev/null +++ b/0116-populating-next-right-pointers-in-each-node.js @@ -0,0 +1,50 @@ +/** + * 116. Populating Next Right Pointers in Each Node + * https://leetcode.com/problems/populating-next-right-pointers-in-each-node/ + * Difficulty: Medium + * + * You are given a perfect binary tree where all leaves are on the same level, and + * every parent has two children. The binary tree has the following definition: + * + * Populate each next pointer to point to its next right node. If there is no next + * right node, the next pointer should be set to NULL. + * + * Initially, all next pointers are set to NULL. + */ + +/** + * // Definition for a Node. + * function Node(val, left, right, next) { + * this.val = val === undefined ? null : val; + * this.left = left === undefined ? null : left; + * this.right = right === undefined ? null : right; + * this.next = next === undefined ? null : next; + * }; + */ + +/** + * @param {Node} root + * @return {Node} + */ +var connect = function(root) { + const order = []; + traverse(order, root); + for (let level of order) { + for (let i = 0; i < level.length - 1; i++) { + level[i].next = level[i + 1]; + } + } + return root; +}; + +function traverse(order, node, level = 0) { + if (!node) { + return []; + } + + order[level] = order[level] || []; + order[level].push(node); + + traverse(order, node.left, level + 1); + traverse(order, node.right, level + 1); +} diff --git a/README.md b/README.md index b092a0eb..edc3267b 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,7 @@ 104|[Maximum Depth of Binary Tree](./0104-maximum-depth-of-binary-tree.js)|Easy| 111|[Minimum Depth of Binary Tree](./0111-minimum-depth-of-binary-tree.js)|Easy| 112|[Path Sum](./0112-path-sum.js)|Easy| +116|[Populating Next Right Pointers in Each Node](./0116-populating-next-right-pointers-in-each-node.js)|Medium| 118|[Pascal's Triangle](./0118-pascals-triangle.js)|Easy| 119|[Pascal's Triangle II](./0119-pascals-triangle-ii.js)|Easy| 121|[Best Time to Buy and Sell Stock](./0121-best-time-to-buy-and-sell-stock.js)|Easy| From b72f110b67f007c0f148cd3bc8d812c2d92cb35d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 30 Dec 2021 18:37:56 -0500 Subject: [PATCH 215/919] Add solution #29 --- 0029-divide-two-integers.js | 46 +++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 47 insertions(+) create mode 100644 0029-divide-two-integers.js diff --git a/0029-divide-two-integers.js b/0029-divide-two-integers.js new file mode 100644 index 00000000..babc4531 --- /dev/null +++ b/0029-divide-two-integers.js @@ -0,0 +1,46 @@ +/** + * 29. Divide Two Integers + * https://leetcode.com/problems/divide-two-integers/ + * Difficulty: Medium + * + * Given two integers dividend and divisor, divide two integers without using multiplication, + * division, and mod operator. + * + * The integer division should truncate toward zero, which means losing its fractional part. + * For example, 8.345 would be truncated to 8, and -2.7335 would be truncated to -2. + * + * Return the quotient after dividing dividend by divisor. + * + * Note: Assume we are dealing with an environment that could only store integers within the + * 32-bit signed integer range: [−231, 231 − 1]. For this problem, if the quotient is strictly + * greater than 231 - 1, then return 231 - 1, and if the quotient is strictly less than -231, + * then return -231. + */ + +/** + * @param {number} dividend + * @param {number} divisor + * @return {number} + */ +var divide = function(dividend, divisor) { + if (divisor === -1 && dividend === Math.pow(-2, 31)) { + return Math.pow(2, 31) - 1; + } + const isNegative = dividend > 0 ^ divisor > 0; + let result = 0; + + dividend = Math.abs(dividend); + subtract(Math.abs(divisor), 1); + + function subtract(n, quotient) { + if (dividend > n) { + subtract(n * 2, quotient * 2); + } + if (dividend >= n) { + dividend -= n; + result += quotient; + } + } + + return isNegative ? -result : result; +}; diff --git a/README.md b/README.md index edc3267b..0a494d43 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,7 @@ 24|[Swap Nodes in Pairs](./0024-swap-nodes-in-pairs.js)|Medium| 27|[Remove Element](./0027-remove-element.js)|Easy| 28|[Implement strStr()](./0028-implement-strstr.js)|Easy| +29|[Divide Two Integers](./0029-divide-two-integers.js)|Medium| 31|[Next Permutation](./0031-next-permutation.js)|Medium| 33|[Search in Rotated Sorted Array](./0033-search-in-rotated-sorted-array.js)|Medium| 34|[Find First and Last Position of Element in Sorted Array](./0034-find-first-and-last-position-of-element-in-sorted-array.js)|Medium| From 1c0851f953725dcaaa452107650755d1fe26b926 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 30 Dec 2021 19:07:11 -0500 Subject: [PATCH 216/919] Add solution #23 --- 0023-merge-k-sorted-lists.js | 43 ++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 44 insertions(+) create mode 100644 0023-merge-k-sorted-lists.js diff --git a/0023-merge-k-sorted-lists.js b/0023-merge-k-sorted-lists.js new file mode 100644 index 00000000..2586988c --- /dev/null +++ b/0023-merge-k-sorted-lists.js @@ -0,0 +1,43 @@ +/** + * 23. Merge k Sorted Lists + * https://leetcode.com/problems/merge-k-sorted-lists/ + * Difficulty: Hard + * + * You are given an array of k linked-lists lists, each linked-list is sorted + * in ascending order. + * + * Merge all the linked-lists into one sorted linked-list and return it. + */ + +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode[]} lists + * @return {ListNode} + */ +var mergeKLists = function(lists) { + const map = new Map(); + for (let list of lists) { + while (list) { + map.set(list.val, (map.get(list.val) || 0) + 1); + list = list.next; + } + } + const sorted = [...map].sort(([a], [b]) => a - b); + const result = new ListNode(); + let tail = result; + + for (let [key, value] of sorted) { + while (value--) { + tail.next = new ListNode(key); + tail = tail.next; + } + } + + return result.next; +}; diff --git a/README.md b/README.md index 0a494d43..3bbd5678 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,7 @@ 20|[Valid Parentheses](./0020-valid-parentheses.js)|Easy| 21|[Merge Two Sorted Lists](./0021-merge-two-sorted-lists.js)|Easy| 22|[Generate Parentheses](./0022-generate-parentheses.js)|Medium| +23|[Merge k Sorted Lists](./0023-merge-k-sorted-lists.js)|Hard| 24|[Swap Nodes in Pairs](./0024-swap-nodes-in-pairs.js)|Medium| 27|[Remove Element](./0027-remove-element.js)|Easy| 28|[Implement strStr()](./0028-implement-strstr.js)|Easy| From 4e202ba69daa083cddab3c9f5eba0cfaa2e9bdeb Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 30 Dec 2021 19:22:16 -0500 Subject: [PATCH 217/919] Add solution #26 --- 0026-remove-duplicates-from-sorted-array.js | 34 +++++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 0026-remove-duplicates-from-sorted-array.js diff --git a/0026-remove-duplicates-from-sorted-array.js b/0026-remove-duplicates-from-sorted-array.js new file mode 100644 index 00000000..326d46ef --- /dev/null +++ b/0026-remove-duplicates-from-sorted-array.js @@ -0,0 +1,34 @@ +/** + * 26. Remove Duplicates from Sorted Array + * https://leetcode.com/problems/remove-duplicates-from-sorted-array/ + * Difficulty: Easy + * + * Given an integer array nums sorted in non-decreasing order, remove the + * duplicates in-place such that each unique element appears only once. + * The relative order of the elements should be kept the same. + * + * Since it is impossible to change the length of the array in some languages, + * you must instead have the result be placed in the first part of the array + * nums. More formally, if there are k elements after removing the duplicates, + * then the first k elements of nums should hold the final result. It does not + * matter what you leave beyond the first k elements. + * + * Return k after placing the final result in the first k slots of nums. + * + * Do not allocate extra space for another array. You must do this by modifying + * the input array in-place with O(1) extra memory. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var removeDuplicates = function(nums) { + let i = 0; + for (let j = 0; j < nums.length; j++) { + if (nums[i] !== nums[j]) { + nums[++i] = nums[j]; + } + } + return ++i; +}; diff --git a/README.md b/README.md index 3bbd5678..f073be28 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,7 @@ 22|[Generate Parentheses](./0022-generate-parentheses.js)|Medium| 23|[Merge k Sorted Lists](./0023-merge-k-sorted-lists.js)|Hard| 24|[Swap Nodes in Pairs](./0024-swap-nodes-in-pairs.js)|Medium| +26|[Remove Duplicates from Sorted Array](./0026-remove-duplicates-from-sorted-array.js)|Easy| 27|[Remove Element](./0027-remove-element.js)|Easy| 28|[Implement strStr()](./0028-implement-strstr.js)|Easy| 29|[Divide Two Integers](./0029-divide-two-integers.js)|Medium| From 60af415555e671863371b6c504bc7097fcdcd1f9 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 31 Dec 2021 19:03:55 -0500 Subject: [PATCH 218/919] Add solution #506 --- 0506-relative-ranks.js | 38 ++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 39 insertions(+) create mode 100644 0506-relative-ranks.js diff --git a/0506-relative-ranks.js b/0506-relative-ranks.js new file mode 100644 index 00000000..1ee77ce5 --- /dev/null +++ b/0506-relative-ranks.js @@ -0,0 +1,38 @@ +/** + * 506. Relative Ranks + * https://leetcode.com/problems/relative-ranks/ + * Difficulty: Easy + * + * You are given an integer array score of size n, where score[i] is the score of the ith + * athlete in a competition. All the scores are guaranteed to be unique. + * + * The athletes are placed based on their scores, where the 1st place athlete has the highest + * score, the 2nd place athlete has the 2nd highest score, and so on. The placement of each + * athlete determines their rank: + * - The 1st place athlete's rank is "Gold Medal". + * - The 2nd place athlete's rank is "Silver Medal". + * - The 3rd place athlete's rank is "Bronze Medal". + * - For the 4th place to the nth place athlete, their rank is their placement number + * (i.e., the xth place athlete's rank is "x"). + * + * Return an array answer of size n where answer[i] is the rank of the ith athlete. + */ + +/** + * @param {number[]} score + * @return {string[]} + */ +var findRelativeRanks = function(score) { + const PLACEMENTS = ['Gold Medal', 'Silver Medal', 'Bronze Medal']; + const map = new Map(); + score.forEach((rank, index) => map.set(rank, index)); + + const result = score.slice(); + const sorted = [...map].sort(([a], [b]) => b - a); + + sorted.forEach(([_, index], rank) => { + result[index] = PLACEMENTS[rank] || `${rank + 1}`; + }); + + return result; +}; diff --git a/README.md b/README.md index f073be28..6081d26c 100644 --- a/README.md +++ b/README.md @@ -105,6 +105,7 @@ 459|[Repeated Substring Pattern](./0459-repeated-substring-pattern.js)|Easy| 476|[Number Complement](./0476-number-complement.js)|Easy| 500|[Keyboard Row](./0500-keyboard-row.js)|Easy| +506|[Relative Ranks](./0506-relative-ranks.js)|Easy| 541|[Reverse String II](./0541-reverse-string-ii.js)|Easy| 551|[Student Attendance Record I](./0551-student-attendance-record-i.js)|Easy| 565|[Array Nesting](./0565-array-nesting.js)|Medium| From 36395acb4824fb08c1cdacb0f5d66a58ec1a7d7b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 1 Jan 2022 13:46:34 -0500 Subject: [PATCH 219/919] Add solution #46 --- 0046-permutations.js | 32 ++++++++++++++++++++++++++++++++ README.md | 3 ++- 2 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 0046-permutations.js diff --git a/0046-permutations.js b/0046-permutations.js new file mode 100644 index 00000000..ca0a39a4 --- /dev/null +++ b/0046-permutations.js @@ -0,0 +1,32 @@ +/** + * 46. Permutations + * https://leetcode.com/problems/permutations/ + * Difficulty: Medium + * + * Given an array nums of distinct integers, return all the possible permutations. + * You can return the answer in any order. + */ + +/** + * @param {number[]} nums + * @return {number[][]} + */ +var permute = function(nums) { + const result = []; + backtrack(result, nums); + return result; +}; + +function backtrack(result, nums, order = []) { + if (!nums.length) { + result.push(order); + } else { + for (let i = 0; i < nums.length; i++) { + backtrack( + result, + [...nums.slice(0, i), ...nums.slice(i + 1)], + [...order, nums[i]] + ); + } + } +} diff --git a/README.md b/README.md index 6081d26c..1926e941 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,7 @@ 41|[First Missing Positive](./0041-first-missing-positive.js)|Hard| 42|[Trapping Rain Water](./0042-trapping-rain-water.js)|Hard| 43|[Multiply Strings](./0043-multiply-strings.js)|Medium| +46|[Permutations](./0046-permutations.js)|Medium| 49|[Group Anagrams](./0049-group-anagrams.js)|Medium| 50|[Pow(x, n)](./0050-powx-n.js)|Medium| 53|[Maximum Subarray](./0053-maximum-subarray.js)|Easy| @@ -216,4 +217,4 @@ [MIT License](https://opensource.org/licenses/MIT) -Copyright (c) 2019-2021 [Josh Crozier](https://joshcrozier.com) +Copyright (c) 2019-2022 [Josh Crozier](https://joshcrozier.com) From 914458b593464e15c2c976a65fd41c3c4213053e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 1 Jan 2022 13:58:20 -0500 Subject: [PATCH 220/919] Add solution #2011 --- ...of-variable-after-performing-operations.js | 24 +++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 2011-final-value-of-variable-after-performing-operations.js diff --git a/2011-final-value-of-variable-after-performing-operations.js b/2011-final-value-of-variable-after-performing-operations.js new file mode 100644 index 00000000..08743e60 --- /dev/null +++ b/2011-final-value-of-variable-after-performing-operations.js @@ -0,0 +1,24 @@ +/** + * 2011. Final Value of Variable After Performing Operations + * https://leetcode.com/problems/final-value-of-variable-after-performing-operations/ + * Difficulty: Easy + * + * There is a programming language with only four operations and one variable X: + * - ++X and X++ increments the value of the variable X by 1. + * - --X and X-- decrements the value of the variable X by 1. + * + * Initially, the value of X is 0. + * + * Given an array of strings operations containing a list of operations, return the + * final value of X after performing all the operations. + */ + +/** + * @param {string[]} operations + * @return {number} + */ +var finalValueAfterOperations = function(operations) { + return operations + .map(n => n.includes('++') ? 1 : -1) + .reduce((sum, n) => sum + n, 0); +}; diff --git a/README.md b/README.md index 1926e941..a3c92b98 100644 --- a/README.md +++ b/README.md @@ -211,6 +211,7 @@ 1929|[Concatenation of Array](./1929-concatenation-of-array.js)|Easy| 1935|[Maximum Number of Words You Can Type](./1935-maximum-number-of-words-you-can-type.js)|Easy| 2000|[Reverse Prefix of Word](./2000-reverse-prefix-of-word.js)|Easy| +2011|[Final Value of Variable After Performing Operations](./2011-final-value-of-variable-after-performing-operations.js)|Easy| 2016|[Maximum Difference Between Increasing Elements](./2016-maximum-difference-between-increasing-elements.js)|Easy| ## License From b5525c15d8675fba6e7677433be4315b1f6dd6ad Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 1 Jan 2022 14:01:41 -0500 Subject: [PATCH 221/919] Add solution #1672 --- 1672-richest-customer-wealth.js | 20 ++++++++++++++++++++ README.md | 1 + 2 files changed, 21 insertions(+) create mode 100644 1672-richest-customer-wealth.js diff --git a/1672-richest-customer-wealth.js b/1672-richest-customer-wealth.js new file mode 100644 index 00000000..c0f89318 --- /dev/null +++ b/1672-richest-customer-wealth.js @@ -0,0 +1,20 @@ +/** + * 1672. Richest Customer Wealth + * https://leetcode.com/problems/richest-customer-wealth/ + * Difficulty: Easy + * + * You are given an m x n integer grid accounts where accounts[i][j] is the + * amount of money the i​​​​​​​​​​​th​​​​ customer has in the j​​​​​​​​​​​th​​​​ bank. Return the wealth + * that the richest customer has. + * + * A customer's wealth is the amount of money they have in all their bank + * accounts. The richest customer is the customer that has the maximum wealth. + */ + +/** + * @param {number[][]} accounts + * @return {number} + */ +var maximumWealth = function(accounts) { + return Math.max(...accounts.map(account => account.reduce((sum, n) => sum + n), 0)); +}; diff --git a/README.md b/README.md index a3c92b98..38f7ccc2 100644 --- a/README.md +++ b/README.md @@ -206,6 +206,7 @@ 1566|[Detect Pattern of Length M Repeated K or More Times](./1566-detect-pattern-of-length-m-repeated-k-or-more-times.js)|Easy| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1668|[Maximum Repeating Substring](./1668-maximum-repeating-substring.js)|Easy| +1672|[Richest Customer Wealth](./1672-richest-customer-wealth.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1929|[Concatenation of Array](./1929-concatenation-of-array.js)|Easy| From 09f82eb1a19f031705821aef400a0901197e02f9 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 1 Jan 2022 14:21:34 -0500 Subject: [PATCH 222/919] Add solution #1431 --- ...ids-with-the-greatest-number-of-candies.js | 25 +++++++++++++++++++ README.md | 1 + 2 files changed, 26 insertions(+) create mode 100644 1431-kids-with-the-greatest-number-of-candies.js diff --git a/1431-kids-with-the-greatest-number-of-candies.js b/1431-kids-with-the-greatest-number-of-candies.js new file mode 100644 index 00000000..f24b577f --- /dev/null +++ b/1431-kids-with-the-greatest-number-of-candies.js @@ -0,0 +1,25 @@ +/** + * 1431. Kids With the Greatest Number of Candies + * https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/ + * Difficulty: Easy + * + * There are n kids with candies. You are given an integer array candies, where each + * candies[i] represents the number of candies the ith kid has, and an integer + * extraCandies, denoting the number of extra candies that you have. + * + * Return a boolean array result of length n, where result[i] is true if, after giving + * the ith kid all the extraCandies, they will have the greatest number of candies + * among all the kids, or false otherwise. + * + * Note that multiple kids can have the greatest number of candies. + */ + +/** + * @param {number[]} candies + * @param {number} extraCandies + * @return {boolean[]} + */ +var kidsWithCandies = function(candies, extraCandies) { + const max = Math.max(...candies); + return candies.map(count => count + extraCandies >= max); +}; diff --git a/README.md b/README.md index 38f7ccc2..7a8590b9 100644 --- a/README.md +++ b/README.md @@ -179,6 +179,7 @@ 1402|[Reducing Dishes](./1402-reducing-dishes.js)|Hard| 1408|[String Matching in an Array](./1408-string-matching-in-an-array.js)|Easy| 1410|[HTML Entity Parser](./1410-html-entity-parser.js)|Medium| +1431|[Kids With the Greatest Number of Candies](./1431-kids-with-the-greatest-number-of-candies.js)|Easy| 1436|[Destination City](./1436-destination-city.js)|Easy| 1437|[Check If All 1's Are at Least Length K Places Away](./1437-check-if-all-1s-are-at-least-length-k-places-away.js)|Easy| 1446|[Consecutive Characters](./1446-consecutive-characters.js)|Easy| From 8cc5309423d3b3f6e2a443ce1f02241a481ea099 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 2 Jan 2022 14:08:20 -0500 Subject: [PATCH 223/919] Add solution #25 --- 0025-reverse-nodes-in-k-group.js | 49 ++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 50 insertions(+) create mode 100644 0025-reverse-nodes-in-k-group.js diff --git a/0025-reverse-nodes-in-k-group.js b/0025-reverse-nodes-in-k-group.js new file mode 100644 index 00000000..8ac3e662 --- /dev/null +++ b/0025-reverse-nodes-in-k-group.js @@ -0,0 +1,49 @@ +/** + * 25. Reverse Nodes in k-Group + * https://leetcode.com/problems/reverse-nodes-in-k-group/ + * Difficulty: Hard + * + * Given the head of a linked list, reverse the nodes of the list k at a time, + * and return the modified list. + * + * k is a positive integer and is less than or equal to the length of the linked + * list. If the number of nodes is not a multiple of k then left-out nodes, in + * the end, should remain as it is. + * + * You may not alter the values in the list's nodes, only nodes themselves may + * be changed. + */ + +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @param {number} k + * @return {ListNode} + */ +var reverseKGroup = function(head, k) { + const result = new ListNode(null, head); + const stack = []; + let tail = result; + + while (head) { + for (let i = 0; i < k && head; i++) { + stack.push(head); + head = head.next; + } + if (stack.length === k) { + while (stack.length) { + tail.next = stack.pop(); + tail = tail.next; + } + tail.next = head; + } + } + + return result.next; +}; diff --git a/README.md b/README.md index 7a8590b9..04d357b1 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,7 @@ 22|[Generate Parentheses](./0022-generate-parentheses.js)|Medium| 23|[Merge k Sorted Lists](./0023-merge-k-sorted-lists.js)|Hard| 24|[Swap Nodes in Pairs](./0024-swap-nodes-in-pairs.js)|Medium| +25|[Reverse Nodes in k-Group](./0025-reverse-nodes-in-k-group.js)|Hard| 26|[Remove Duplicates from Sorted Array](./0026-remove-duplicates-from-sorted-array.js)|Easy| 27|[Remove Element](./0027-remove-element.js)|Easy| 28|[Implement strStr()](./0028-implement-strstr.js)|Easy| From a158e7b3a9f0d51d820b05dde14244c73cb6deb3 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 2 Jan 2022 18:08:10 -0500 Subject: [PATCH 224/919] Add solution #2047 --- 2047-number-of-valid-words-in-a-sentence.js | 31 +++++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 2047-number-of-valid-words-in-a-sentence.js diff --git a/2047-number-of-valid-words-in-a-sentence.js b/2047-number-of-valid-words-in-a-sentence.js new file mode 100644 index 00000000..f19c7734 --- /dev/null +++ b/2047-number-of-valid-words-in-a-sentence.js @@ -0,0 +1,31 @@ +/** + * 2047. Number of Valid Words in a Sentence + * https://leetcode.com/problems/number-of-valid-words-in-a-sentence/ + * Difficulty: Easy + * + * A sentence consists of lowercase letters ('a' to 'z'), digits ('0' to '9'), + * hyphens ('-'), punctuation marks ('!', '.', and ','), and spaces (' ') only. + * Each sentence can be broken down into one or more tokens separated by one or + * more spaces ' '. + * + * A token is a valid word if all three of the following are true: + * - It only contains lowercase letters, hyphens, and/or punctuation (no digits). + * - There is at most one hyphen '-'. If present, it must be surrounded by lowercase + * characters ("a-b" is valid, but "-ab" and "ab-" are not valid). + * - There is at most one punctuation mark. If present, it must be at the end of + * the token ("ab,", "cd!", and "." are valid, but "a!b" and "c.," are not valid). + * + * Examples of valid words include "a-b.", "afad", "ba-c", "a!", and "!". + * + * Given a string sentence, return the number of valid words in sentence. + */ + +/** + * @param {string} sentence + * @return {number} + */ +var countValidWords = function(sentence) { + return sentence.trim().split(/\s+/).reduce((total, str) => { + return total + (/^(?:([a-z]+\-?[a-z]+)|([a-z+]))?[!.,]?$/.test(str) ? 1 : 0); + }, 0); +}; diff --git a/README.md b/README.md index 04d357b1..40f93aa3 100644 --- a/README.md +++ b/README.md @@ -216,6 +216,7 @@ 2000|[Reverse Prefix of Word](./2000-reverse-prefix-of-word.js)|Easy| 2011|[Final Value of Variable After Performing Operations](./2011-final-value-of-variable-after-performing-operations.js)|Easy| 2016|[Maximum Difference Between Increasing Elements](./2016-maximum-difference-between-increasing-elements.js)|Easy| +2047|[Number of Valid Words in a Sentence](./2047-number-of-valid-words-in-a-sentence.js)|Easy| ## License From 61ec3976ca3654f83d97443134963922c6cf7d5b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 2 Jan 2022 18:11:06 -0500 Subject: [PATCH 225/919] Add solution #1996 --- ...e-number-of-weak-characters-in-the-game.js | 35 +++++++++++++++++++ README.md | 1 + 2 files changed, 36 insertions(+) create mode 100644 1996-the-number-of-weak-characters-in-the-game.js diff --git a/1996-the-number-of-weak-characters-in-the-game.js b/1996-the-number-of-weak-characters-in-the-game.js new file mode 100644 index 00000000..bbf5b54d --- /dev/null +++ b/1996-the-number-of-weak-characters-in-the-game.js @@ -0,0 +1,35 @@ +/** + * 1996. The Number of Weak Characters in the Game + * https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/ + * Difficulty: Medium + * + * You are playing a game that contains multiple characters, and each of the + * characters has two main properties: attack and defense. You are given a 2D + * integer array properties where properties[i] = [attacki, defensei] represents + * the properties of the ith character in the game. + * + * A character is said to be weak if any other character has both attack and + * defense levels strictly greater than this character's attack and defense levels. + * More formally, a character i is said to be weak if there exists another character + * j where attackj > attacki and defensej > defensei. + * + * Return the number of weak characters. + */ + +/** + * @param {number[][]} properties + * @return {number} + */ +var numberOfWeakCharacters = function(properties) { + let result = 0; + let max = 0; + + properties.sort((a, b) => (b[0] === a[0]) ? a[1] - b[1] : b[0] - a[0]); + + for (let i = 0; i < properties.length; i++) { + if (properties[i][1] < max) result++; + max = Math.max(max, properties[i][1]); + } + + return result; +}; diff --git a/README.md b/README.md index 40f93aa3..668d062f 100644 --- a/README.md +++ b/README.md @@ -213,6 +213,7 @@ 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1929|[Concatenation of Array](./1929-concatenation-of-array.js)|Easy| 1935|[Maximum Number of Words You Can Type](./1935-maximum-number-of-words-you-can-type.js)|Easy| +1996|[The Number of Weak Characters in the Game](./1996-the-number-of-weak-characters-in-the-game.js)|Medium| 2000|[Reverse Prefix of Word](./2000-reverse-prefix-of-word.js)|Easy| 2011|[Final Value of Variable After Performing Operations](./2011-final-value-of-variable-after-performing-operations.js)|Easy| 2016|[Maximum Difference Between Increasing Elements](./2016-maximum-difference-between-increasing-elements.js)|Easy| From a0fc36fafb29f64424b55804ebbc31cac242b541 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 3 Jan 2022 19:02:08 -0500 Subject: [PATCH 226/919] Add solution #1010 --- ...gs-with-total-durations-divisible-by-60.js | 24 +++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 1010-pairs-of-songs-with-total-durations-divisible-by-60.js diff --git a/1010-pairs-of-songs-with-total-durations-divisible-by-60.js b/1010-pairs-of-songs-with-total-durations-divisible-by-60.js new file mode 100644 index 00000000..7f4ef23d --- /dev/null +++ b/1010-pairs-of-songs-with-total-durations-divisible-by-60.js @@ -0,0 +1,24 @@ +/** + * 1010. Pairs of Songs With Total Durations Divisible by 60 + * https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/ + * Difficulty: Medium + * + * You are given a list of songs where the ith song has a duration of time[i] seconds. + * + * Return the number of pairs of songs for which their total duration in seconds is + * divisible by 60. Formally, we want the number of indices i, j such that i < j with + * (time[i] + time[j]) % 60 == 0. + */ + +/** + * @param {number[]} time + * @return {number} + */ +var numPairsDivisibleBy60 = function(time) { + const mods = new Array(60).fill(0); + return time.reduce((sum, t) => { + sum += mods[(60 - t % 60) % 60]; + mods[t % 60]++; + return sum; + }, 0); +}; diff --git a/README.md b/README.md index 668d062f..aee23be5 100644 --- a/README.md +++ b/README.md @@ -145,6 +145,7 @@ 985|[Sum of Even Numbers After Queries](./0985-sum-of-even-numbers-after-queries.js)|Easy| 989|[Add to Array-Form of Integer](./0989-add-to-array-form-of-integer.js)|Easy| 1009|[Complement of Base 10 Integer](./1009-complement-of-base-10-integer.js)|Easy| +1010|[Pairs of Songs With Total Durations Divisible by 60](./1010-pairs-of-songs-with-total-durations-divisible-by-60.js)|Medium| 1037|[Valid Boomerang](./1037-valid-boomerang.js)|Easy| 1103|[Distribute Candies to People](./1103-distribute-candies-to-people.js)|Easy| 1108|[Defanging an IP Address](./1108-defanging-an-ip-address.js)|Easy| From eb6c4e02ce60e814146b7bdc401826cee21a9e33 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 3 Jan 2022 19:03:29 -0500 Subject: [PATCH 227/919] Add solution #1920 --- 1920-build-array-from-permutation.js | 19 +++++++++++++++++++ README.md | 1 + 2 files changed, 20 insertions(+) create mode 100644 1920-build-array-from-permutation.js diff --git a/1920-build-array-from-permutation.js b/1920-build-array-from-permutation.js new file mode 100644 index 00000000..fff829fc --- /dev/null +++ b/1920-build-array-from-permutation.js @@ -0,0 +1,19 @@ +/** + * 1920. Build Array from Permutation + * https://leetcode.com/problems/build-array-from-permutation/ + * Difficulty: Easy + * + * Given a zero-based permutation nums (0-indexed), build an array ans of the same length + * where ans[i] = nums[nums[i]] for each 0 <= i < nums.length and return it. + * + * A zero-based permutation nums is an array of distinct integers from 0 to nums.length - 1 + * (inclusive). + */ + +/** + * @param {number[]} nums + * @return {number[]} + */ +var buildArray = function(nums) { + return nums.map(n => nums[n]); +}; diff --git a/README.md b/README.md index aee23be5..d147e737 100644 --- a/README.md +++ b/README.md @@ -212,6 +212,7 @@ 1672|[Richest Customer Wealth](./1672-richest-customer-wealth.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| +1920|[Build Array from Permutation](./1920-build-array-from-permutation.js)|Easy| 1929|[Concatenation of Array](./1929-concatenation-of-array.js)|Easy| 1935|[Maximum Number of Words You Can Type](./1935-maximum-number-of-words-you-can-type.js)|Easy| 1996|[The Number of Weak Characters in the Game](./1996-the-number-of-weak-characters-in-the-game.js)|Medium| From 6afb553486e7ce6eb6e4c58cfc23df876c8fe696 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 3 Jan 2022 19:04:59 -0500 Subject: [PATCH 228/919] Add solution #997 --- 0997-find-the-town-judge.js | 36 ++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 37 insertions(+) create mode 100644 0997-find-the-town-judge.js diff --git a/0997-find-the-town-judge.js b/0997-find-the-town-judge.js new file mode 100644 index 00000000..c4c67847 --- /dev/null +++ b/0997-find-the-town-judge.js @@ -0,0 +1,36 @@ +/** + * 997. Find the Town Judge + * https://leetcode.com/problems/find-the-town-judge/ + * Difficulty: Easy + * + * In a town, there are n people labeled from 1 to n. There is a rumor that one of these + * people is secretly the town judge. + * + * If the town judge exists, then: + * - The town judge trusts nobody. + * - Everybody (except for the town judge) trusts the town judge. + * - There is exactly one person that satisfies properties 1 and 2. + * + * You are given an array trust where trust[i] = [ai, bi] representing that the person labeled + * ai trusts the person labeled bi. + * + * Return the label of the town judge if the town judge exists and can be identified, or return + * -1 otherwise. + */ + +/** + * @param {number} n + * @param {number[][]} trust + * @return {number} + */ +var findJudge = function(n, trust) { + if (!trust.length) { + return n === 1 ? n : -1; + } + + const map = new Map(); + trust.forEach(([_, value]) => map.set(value, (map.get(value) || 0 ) + 1)); + + const [judge, count] = [...map].sort(([,a], [,b]) => b - a)[0]; + return count === n - 1 && !trust.find(([key]) => key === judge) ? judge : -1; +}; diff --git a/README.md b/README.md index d147e737..0ae3c587 100644 --- a/README.md +++ b/README.md @@ -144,6 +144,7 @@ 977|[Squares of a Sorted Array](./0977-squares-of-a-sorted-array.js)|Easy| 985|[Sum of Even Numbers After Queries](./0985-sum-of-even-numbers-after-queries.js)|Easy| 989|[Add to Array-Form of Integer](./0989-add-to-array-form-of-integer.js)|Easy| +997|[Find the Town Judge](./0997-find-the-town-judge.js)|Easy| 1009|[Complement of Base 10 Integer](./1009-complement-of-base-10-integer.js)|Easy| 1010|[Pairs of Songs With Total Durations Divisible by 60](./1010-pairs-of-songs-with-total-durations-divisible-by-60.js)|Medium| 1037|[Valid Boomerang](./1037-valid-boomerang.js)|Easy| From 30925dbdfe31bcd97aa301efb275ade93b8b63b2 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 4 Jan 2022 21:08:51 -0500 Subject: [PATCH 229/919] Add solution #15 --- 0015-3sum.js | 38 ++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 39 insertions(+) create mode 100644 0015-3sum.js diff --git a/0015-3sum.js b/0015-3sum.js new file mode 100644 index 00000000..a34d0eff --- /dev/null +++ b/0015-3sum.js @@ -0,0 +1,38 @@ +/** + * 15. 3Sum + * https://leetcode.com/problems/3sum/ + * Difficulty: Medium + * + * Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, + * i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. + * + * Notice that the solution set must not contain duplicate triplets. + */ + +/** + * @param {number[]} nums + * @return {number[][]} + */ +var threeSum = function(nums) { + const result = new Set(); + + nums.sort((a, b) => a - b); + + for (let i = 0; i < nums.length - 2; i++) { + let j = i + 1; + let k = nums.length - 1; + + while (j < k) { + const sum = nums[i] + nums[j] + nums[k]; + if (!sum) { + result.add(JSON.stringify([nums[i], nums[j++], nums[k--]])); + } else if (sum > 0) { + k--; + } else { + j++; + } + } + } + + return [...result].map(JSON.parse); +}; diff --git a/README.md b/README.md index 0ae3c587..89d64579 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ 12|[Integer to Roman](./0012-integer-to-roman.js)|Medium| 13|[Roman to Integer](./0013-roman-to-integer.js)|Easy| 14|[Longest Common Prefix](./0014-longest-common-prefix.js)|Easy| +15|[3Sum](./0015-3sum.js)|Medium| 17|[Letter Combinations of a Phone Number](./0017-letter-combinations-of-a-phone-number.js)|Medium| 19|[Remove Nth Node From End of List](./0019-remove-nth-node-from-end-of-list.js)|Medium| 20|[Valid Parentheses](./0020-valid-parentheses.js)|Easy| From 8a9a4fa9dcf8d02c0f8ca5efed0226a74945b45d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 4 Jan 2022 21:10:41 -0500 Subject: [PATCH 230/919] Add solution #16 --- 0016-3sum-closest.js | 40 ++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 41 insertions(+) create mode 100644 0016-3sum-closest.js diff --git a/0016-3sum-closest.js b/0016-3sum-closest.js new file mode 100644 index 00000000..a4fd4941 --- /dev/null +++ b/0016-3sum-closest.js @@ -0,0 +1,40 @@ +/** + * 16. 3Sum Closest + * https://leetcode.com/problems/3sum-closest/ + * Difficulty: Medium + * + * Given an integer array nums of length n and an integer target, find three integers + * in nums such that the sum is closest to target. + * + * Return the sum of the three integers. + * + * You may assume that each input would have exactly one solution. + */ + +/** + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +var threeSumClosest = function(nums, target) { + const sums = new Set(); + + nums.sort((a, b) => a - b); + + for (let i = 0; i < nums.length - 2; i++) { + let j = i + 1; + let k = nums.length - 1; + + while (j < k) { + const sum = nums[i] + nums[j] + nums[k]; + sums.add(sum); + if (sum > target) { + k--; + } else { + j++; + } + } + } + + return [...sums].reduce((p, c) => Math.abs(c - target) < Math.abs(p - target) ? c : p); +}; diff --git a/README.md b/README.md index 89d64579..41adf850 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ 13|[Roman to Integer](./0013-roman-to-integer.js)|Easy| 14|[Longest Common Prefix](./0014-longest-common-prefix.js)|Easy| 15|[3Sum](./0015-3sum.js)|Medium| +16|[3Sum Closest](./0016-3sum-closest.js)|Medium| 17|[Letter Combinations of a Phone Number](./0017-letter-combinations-of-a-phone-number.js)|Medium| 19|[Remove Nth Node From End of List](./0019-remove-nth-node-from-end-of-list.js)|Medium| 20|[Valid Parentheses](./0020-valid-parentheses.js)|Easy| From 8ef01d770037c5fa15dbc479ae85b16c2495694c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 4 Jan 2022 21:12:10 -0500 Subject: [PATCH 231/919] Add solution #167 --- 0167-two-sum-ii-input-array-is-sorted.js | 34 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 0167-two-sum-ii-input-array-is-sorted.js diff --git a/0167-two-sum-ii-input-array-is-sorted.js b/0167-two-sum-ii-input-array-is-sorted.js new file mode 100644 index 00000000..848bacf7 --- /dev/null +++ b/0167-two-sum-ii-input-array-is-sorted.js @@ -0,0 +1,34 @@ +/** + * 167. Two Sum II - Input Array Is Sorted + * https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/ + * Difficulty: Easy + * + * Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, + * find two numbers such that they add up to a specific target number. Let these two numbers + * be numbers[index1] and numbers[index2] where 1 <= index1 < index2 <= numbers.length. + * + * Return the indices of the two numbers, index1 and index2, added by one as an integer array + * [index1, index2] of length 2. + * + * The tests are generated such that there is exactly one solution. You may not use the same + * element twice. + */ + +/** + * @param {number[]} numbers + * @param {number} target + * @return {number[]} + */ +var twoSum = function(numbers, target) { + const map = new Map(); + + for (let i = 0; i < numbers.length; i++) { + const diff = target - numbers[i]; + + if (map.has(diff)) { + return [map.get(diff) + 1, i + 1]; + } + + map.set(numbers[i], i); + } +}; diff --git a/README.md b/README.md index 41adf850..b9f6ef31 100644 --- a/README.md +++ b/README.md @@ -73,6 +73,7 @@ 145|[Binary Tree Postorder Traversal](./0145-binary-tree-postorder-traversal.js)|Easy| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| +167|[Two Sum II - Input Array Is Sorted](./0167-two-sum-ii-input-array-is-sorted.js)|Easy| 169|[Majority Element](./0169-majority-element.js)|Easy| 179|[Largest Number](./0179-largest-number.js)|Medium| 191|[Number of 1 Bits](./0191-number-of-1-bits.js)|Easy| From 763b9b9f9624ba259c063681e6c45622a1703bb1 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 5 Jan 2022 21:51:57 -0500 Subject: [PATCH 232/919] Add solution #48 --- 0048-rotate-image.js | 27 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 28 insertions(+) create mode 100644 0048-rotate-image.js diff --git a/0048-rotate-image.js b/0048-rotate-image.js new file mode 100644 index 00000000..f4312bd7 --- /dev/null +++ b/0048-rotate-image.js @@ -0,0 +1,27 @@ +/** + * 48. Rotate Image + * https://leetcode.com/problems/rotate-image/ + * Difficulty: Medium + * + * You are given an n x n 2D matrix representing an image, rotate the image by + * 90 degrees (clockwise). + * + * You have to rotate the image in-place, which means you have to modify the input + * 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. + */ + +/** + * @param {number[][]} matrix + * @return {void} Do not return anything, modify matrix in-place instead. + */ +var rotate = function(matrix) { + matrix = matrix.reverse(); + + for (let i = 0; i < matrix.length; i++) { + for (let j = 0; j < i; j++) { + [matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]]; + } + } + + return matrix; +}; diff --git a/README.md b/README.md index b9f6ef31..edfe3b7d 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,7 @@ 42|[Trapping Rain Water](./0042-trapping-rain-water.js)|Hard| 43|[Multiply Strings](./0043-multiply-strings.js)|Medium| 46|[Permutations](./0046-permutations.js)|Medium| +48|[Rotate Image](./0048-rotate-image.js)|Medium| 49|[Group Anagrams](./0049-group-anagrams.js)|Medium| 50|[Pow(x, n)](./0050-powx-n.js)|Medium| 53|[Maximum Subarray](./0053-maximum-subarray.js)|Easy| From b4e392e75a78178db93000d834cff7d773b1a9a5 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 5 Jan 2022 21:53:12 -0500 Subject: [PATCH 233/919] Add solution #1886 --- ...ther-matrix-can-be-obtained-by-rotation.js | 35 +++++++++++++++++++ README.md | 1 + 2 files changed, 36 insertions(+) create mode 100644 1886-determine-whether-matrix-can-be-obtained-by-rotation.js diff --git a/1886-determine-whether-matrix-can-be-obtained-by-rotation.js b/1886-determine-whether-matrix-can-be-obtained-by-rotation.js new file mode 100644 index 00000000..2cfb38f0 --- /dev/null +++ b/1886-determine-whether-matrix-can-be-obtained-by-rotation.js @@ -0,0 +1,35 @@ +/** + * 1886. Determine Whether Matrix Can Be Obtained By Rotation + * https://leetcode.com/problems/determine-whether-matrix-can-be-obtained-by-rotation/ + * Difficulty: Easy + * + * Given two n x n binary matrices mat and target, return true if it is possible to make mat + * equal to target by rotating mat in 90-degree increments, or false otherwise. + */ + +/** + * @param {number[][]} mat + * @param {number[][]} target + * @return {boolean} + */ +var findRotation = function(mat, target) { + const goal = JSON.stringify(target); + for (let i = 0; i < 4; i++) { + if (JSON.stringify(rotate(mat)) === goal) { + return true; + } + } + return false; +}; + +function rotate(matrix) { + matrix = matrix.reverse(); + + for (let i = 0; i < matrix.length; i++) { + for (let j = 0; j < i; j++) { + [matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]]; + } + } + + return matrix; +} diff --git a/README.md b/README.md index edfe3b7d..a99d5113 100644 --- a/README.md +++ b/README.md @@ -217,6 +217,7 @@ 1672|[Richest Customer Wealth](./1672-richest-customer-wealth.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| +1886|[Determine Whether Matrix Can Be Obtained By Rotation](./1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| 1920|[Build Array from Permutation](./1920-build-array-from-permutation.js)|Easy| 1929|[Concatenation of Array](./1929-concatenation-of-array.js)|Easy| 1935|[Maximum Number of Words You Can Type](./1935-maximum-number-of-words-you-can-type.js)|Easy| From 0681b182e1979fe18db6098781a3db3a1b20979d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 5 Jan 2022 21:53:53 -0500 Subject: [PATCH 234/919] Add solution #557 --- 0557-reverse-words-in-a-string-iii.js | 16 ++++++++++++++++ README.md | 1 + 2 files changed, 17 insertions(+) create mode 100644 0557-reverse-words-in-a-string-iii.js diff --git a/0557-reverse-words-in-a-string-iii.js b/0557-reverse-words-in-a-string-iii.js new file mode 100644 index 00000000..60879f01 --- /dev/null +++ b/0557-reverse-words-in-a-string-iii.js @@ -0,0 +1,16 @@ +/** + * 557. Reverse Words in a String III + * https://leetcode.com/problems/reverse-words-in-a-string-iii/ + * Difficulty: Easy + * + * Given a string s, reverse the order of characters in each word within a sentence while + * still preserving whitespace and initial word order. + */ + +/** + * @param {string} str + * @return {string} + */ +var reverseWords = function(str) { + return str.split(/\s/).map(s => s.split('').reverse().join('')).join(' '); +}; diff --git a/README.md b/README.md index a99d5113..3a476b14 100644 --- a/README.md +++ b/README.md @@ -114,6 +114,7 @@ 506|[Relative Ranks](./0506-relative-ranks.js)|Easy| 541|[Reverse String II](./0541-reverse-string-ii.js)|Easy| 551|[Student Attendance Record I](./0551-student-attendance-record-i.js)|Easy| +557|[Reverse Words in a String III](./0557-reverse-words-in-a-string-iii.js)|Easy| 565|[Array Nesting](./0565-array-nesting.js)|Medium| 566|[Reshape the Matrix](./0566-reshape-the-matrix.js)|Easy| 606|[Construct String from Binary Tree](./0606-construct-string-from-binary-tree.js)|Easy| From e729699df0068a471bd446215e5e365b739900e6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 6 Jan 2022 23:53:43 -0500 Subject: [PATCH 235/919] Add solution #2114 --- ...imum-number-of-words-found-in-sentences.js | 19 +++++++++++++++++++ README.md | 1 + 2 files changed, 20 insertions(+) create mode 100644 2114-maximum-number-of-words-found-in-sentences.js diff --git a/2114-maximum-number-of-words-found-in-sentences.js b/2114-maximum-number-of-words-found-in-sentences.js new file mode 100644 index 00000000..b70c9f41 --- /dev/null +++ b/2114-maximum-number-of-words-found-in-sentences.js @@ -0,0 +1,19 @@ +/** + * 2114. Maximum Number of Words Found in Sentences + * https://leetcode.com/problems/maximum-number-of-words-found-in-sentences/ + * Difficulty: Easy + * + * A sentence is a list of words that are separated by a single space with no leading or trailing spaces. + * + * You are given an array of strings sentences, where each sentences[i] represents a single sentence. + * + * Return the maximum number of words that appear in a single sentence. + */ + +/** + * @param {string[]} sentences + * @return {number} + */ +var mostWordsFound = function(sentences) { + return sentences.reduce((max, str) => Math.max(max, str.split(/\s+/).length), 0); +}; diff --git a/README.md b/README.md index 3a476b14..fe3496bd 100644 --- a/README.md +++ b/README.md @@ -227,6 +227,7 @@ 2011|[Final Value of Variable After Performing Operations](./2011-final-value-of-variable-after-performing-operations.js)|Easy| 2016|[Maximum Difference Between Increasing Elements](./2016-maximum-difference-between-increasing-elements.js)|Easy| 2047|[Number of Valid Words in a Sentence](./2047-number-of-valid-words-in-a-sentence.js)|Easy| +2114|[Maximum Number of Words Found in Sentences](./2114-maximum-number-of-words-found-in-sentences.js)|Easy| ## License From ee08d2d63896762a42b684cc2179ad2926261e79 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 6 Jan 2022 23:54:43 -0500 Subject: [PATCH 236/919] Add solution #704 --- 0704-binary-search.js | 30 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 0704-binary-search.js diff --git a/0704-binary-search.js b/0704-binary-search.js new file mode 100644 index 00000000..a8cf2011 --- /dev/null +++ b/0704-binary-search.js @@ -0,0 +1,30 @@ +/** + * 704. Binary Search + * https://leetcode.com/problems/binary-search/ + * Difficulty: Easy + * + * Given an array of integers nums which is sorted in ascending order, and an + * integer target, write a function to search target in nums. If target exists, + * then return its index. Otherwise, return -1. + * + * You must write an algorithm with O(log n) runtime complexity. + */ + +/** + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +var search = function(nums, target) { + let left = 0; + let right = nums.length - 1; + + while (left <= right) { + const pivot = Math.floor((right + left) / 2); + if (nums[pivot] === target) return pivot; + if (target < nums[pivot]) right = pivot - 1; + else left = pivot + 1; + } + + return -1; +}; diff --git a/README.md b/README.md index fe3496bd..76543635 100644 --- a/README.md +++ b/README.md @@ -125,6 +125,7 @@ 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| 700|[Search in a Binary Search Tree](./0700-search-in-a-binary-search-tree.js)|Easy| 701|[Insert into a Binary Search Tree](./0701-insert-into-a-binary-search-tree.js)|Medium| +704|[Binary Search](./0704-binary-search.js)|Easy| 713|[Subarray Product Less Than K](./0713-subarray-product-less-than-k.js)|Medium| 722|[Remove Comments](./0722-remove-comments.js)|Medium| 739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium| From 54feb207a0f6b42b013eb3184fd3091f77aafeb6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 6 Jan 2022 23:57:01 -0500 Subject: [PATCH 237/919] Add solution #278 --- 0278-first-bad-version.js | 43 +++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 44 insertions(+) create mode 100644 0278-first-bad-version.js diff --git a/0278-first-bad-version.js b/0278-first-bad-version.js new file mode 100644 index 00000000..ca7b4599 --- /dev/null +++ b/0278-first-bad-version.js @@ -0,0 +1,43 @@ +/** + * 278. First Bad Version + * https://leetcode.com/problems/first-bad-version/ + * Difficulty: Medium + * + * You are a product manager and currently leading a team to develop a new product. + * Unfortunately, the latest version of your product fails the quality check. Since + * each version is developed based on the previous version, all the versions after + * a bad version are also bad. + * + * Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad + * one, which causes all the following ones to be bad. + * + * You are given an API bool isBadVersion(version) which returns whether version is + * bad. Implement a function to find the first bad version. You should minimize the + * number of calls to the API. + */ + +/** + * @param {function} isBadVersion() + * @return {function} + */ +var solution = function(isBadVersion) { + /** + * @param {integer} n Total versions + * @return {integer} The first bad version + */ + return n => { + let left = 1; + let right = n; + + while (left <= right) { + const pivot = Math.floor((right + left) / 2); + if (isBadVersion(pivot)) { + right = pivot - 1; + } else { + left = pivot + 1; + } + } + + return left; + }; +}; diff --git a/README.md b/README.md index 76543635..1534aa3e 100644 --- a/README.md +++ b/README.md @@ -96,6 +96,7 @@ 264|[Ugly Number II](./0264-ugly-number-ii.js)|Medium| 268|[Missing Number](./0268-missing-number.js)|Easy| 273|[Integer to English Words](./0273-integer-to-english-words.js)|Hard| +278|[First Bad Version](./0278-first-bad-version.js)|Medium| 283|[Move Zeroes](./0283-move-zeroes.js)|Easy| 326|[Power of Three](./0326-power-of-three.js)|Easy| 342|[Power of Four](./0342-power-of-four.js)|Easy| From 7f39db36ae64bbc48c87a3e97109f84d8ad79d8b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 7 Jan 2022 18:05:59 -0500 Subject: [PATCH 238/919] Add solution #567 --- 0567-permutation-in-string.js | 38 +++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 39 insertions(+) create mode 100644 0567-permutation-in-string.js diff --git a/0567-permutation-in-string.js b/0567-permutation-in-string.js new file mode 100644 index 00000000..20c61c88 --- /dev/null +++ b/0567-permutation-in-string.js @@ -0,0 +1,38 @@ +/** + * 567. Permutation in String + * https://leetcode.com/problems/permutation-in-string/ + * Difficulty: Medium + * + * Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise. + * + * In other words, return true if one of s1's permutations is the substring of s2. + */ + +/** + * @param {string} s1 + * @param {string} s2 + * @return {boolean} + */ +var checkInclusion = function(s1, s2) { + const getCharCode = c => c.charCodeAt() - 'a'.charCodeAt(); + const isMatch = (a1, a2) => a1.every((n, i) => a2[i] === n); + + if (s1.length > s2.length) { + return false; + } + + const map1 = new Array(26).fill(0); + const map2 = new Array(26).fill(0); + for (let i = 0; i < s1.length; i++) { + map1[getCharCode(s1[i])]++; + map2[getCharCode(s2[i])]++; + } + + for (let i = 0; i < s2.length - s1.length; i++) { + if (isMatch(map1, map2)) return true; + map2[getCharCode(s2[i + s1.length])]++; + map2[getCharCode(s2[i])]--; + } + + return isMatch(map1, map2); +}; diff --git a/README.md b/README.md index 1534aa3e..028e983e 100644 --- a/README.md +++ b/README.md @@ -118,6 +118,7 @@ 557|[Reverse Words in a String III](./0557-reverse-words-in-a-string-iii.js)|Easy| 565|[Array Nesting](./0565-array-nesting.js)|Medium| 566|[Reshape the Matrix](./0566-reshape-the-matrix.js)|Easy| +567|[Permutation in String](./0567-permutation-in-string.js)|Medium| 606|[Construct String from Binary Tree](./0606-construct-string-from-binary-tree.js)|Easy| 617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy| 628|[Maximum Product of Three Numbers](./0628-maximum-product-of-three-numbers.js)|Easy| From 1a7929dc6da80d29f5b63103346a31319f3fa540 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 7 Jan 2022 18:07:40 -0500 Subject: [PATCH 239/919] Add solution #733 --- 0733-flood-fill.js | 38 ++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 39 insertions(+) create mode 100644 0733-flood-fill.js diff --git a/0733-flood-fill.js b/0733-flood-fill.js new file mode 100644 index 00000000..58e04eb0 --- /dev/null +++ b/0733-flood-fill.js @@ -0,0 +1,38 @@ +/** + * 733. Flood Fill + * https://leetcode.com/problems/flood-fill/ + * Difficulty: Easy + * + * An image is represented by an m x n integer grid image where image[i][j] represents + * the pixel value of the image. + * + * You are also given three integers sr, sc, and newColor. You should perform a flood + * fill on the image starting from the pixel image[sr][sc]. + * + * To perform a flood fill, consider the starting pixel, plus any pixels connected + * 4-directionally to the starting pixel of the same color as the starting pixel, + * plus any pixels connected 4-directionally to those pixels (also with the same color), + * and so on. Replace the color of all of the aforementioned pixels with newColor. + * + * Return the modified image after performing the flood fill. + */ + +/** + * @param {number[][]} image + * @param {number} sr + * @param {number} sc + * @param {number} newColor + * @return {number[][]} + */ +var floodFill = function(image, sr, sc, newColor) { + fill(image, sr, sc, image[sr][sc], newColor); + return image; +}; + +function fill(image, x, y, initialColor, newColor) { + if (image[x] && image[x][y] === initialColor && initialColor !== newColor) { + image[x][y] = newColor; + [[x - 1, y], [x + 1, y], [x, y - 1], [x, y + 1]] + .forEach(([x, y]) => fill(image, x, y, initialColor, newColor)); + } +} diff --git a/README.md b/README.md index 028e983e..83b40dea 100644 --- a/README.md +++ b/README.md @@ -130,6 +130,7 @@ 704|[Binary Search](./0704-binary-search.js)|Easy| 713|[Subarray Product Less Than K](./0713-subarray-product-less-than-k.js)|Medium| 722|[Remove Comments](./0722-remove-comments.js)|Medium| +733|[Flood Fill](./0733-flood-fill.js)|Easy| 739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium| 791|[Custom Sort String](./0791-custom-sort-string.js)|Medium| 796|[Rotate String](./0796-rotate-string.js)|Easy| From dbcadaf80143a34a788e424d61d77eb13cb69c2b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 7 Jan 2022 18:08:32 -0500 Subject: [PATCH 240/919] Add solution #695 --- 0695-max-area-of-island.js | 41 ++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 42 insertions(+) create mode 100644 0695-max-area-of-island.js diff --git a/0695-max-area-of-island.js b/0695-max-area-of-island.js new file mode 100644 index 00000000..c8957edf --- /dev/null +++ b/0695-max-area-of-island.js @@ -0,0 +1,41 @@ +/** + * 695. Max Area of Island + * https://leetcode.com/problems/max-area-of-island/ + * Difficulty: Medium + * + * You are given an m x n binary matrix grid. An island is a group of 1's (representing land) + * connected 4-directionally (horizontal or vertical.) You may assume all four edges of the + * grid are surrounded by water. + * + * The area of an island is the number of cells with a value 1 in the island. + * + * Return the maximum area of an island in grid. If there is no island, return 0. + */ + +/** + * @param {number[][]} grid + * @return {number} + */ +var maxAreaOfIsland = function(grid) { + const cache = new Set(); + let max = 0; + + for (let i = 0; i < grid.length; i++) { + for (let j = 0; j < grid[0].length; j++) { + max = Math.max(max, traverse(grid, cache, i, j)); + } + } + + return max; +}; + +function traverse(grid, cache, x, y) { + let count = 0; + if (grid[x] && grid[x][y] === 1 && !cache.has(`${x},${y}`)) { + cache.add(`${x},${y}`); + count += [[x - 1, y], [x + 1, y], [x, y - 1], [x, y + 1]] + .map(([x, y]) => traverse(grid, cache, x, y)) + .reduce((sum, count) => sum + count, 0) + 1; + } + return count; +} diff --git a/README.md b/README.md index 83b40dea..a948962a 100644 --- a/README.md +++ b/README.md @@ -125,6 +125,7 @@ 648|[Replace Words](./0648-replace-words.js)|Medium| 653|[Two Sum IV - Input is a BST](./0653-two-sum-iv-input-is-a-bst.js)|Easy| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| +695|[Max Area of Island](./0695-max-area-of-island.js)|Medium| 700|[Search in a Binary Search Tree](./0700-search-in-a-binary-search-tree.js)|Easy| 701|[Insert into a Binary Search Tree](./0701-insert-into-a-binary-search-tree.js)|Medium| 704|[Binary Search](./0704-binary-search.js)|Easy| From d7df6faf03162e131cc403b7850bd42ca365ec0c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 8 Jan 2022 16:53:28 -0500 Subject: [PATCH 241/919] Add solution #189 --- 0189-rotate-array.js | 16 ++++++++++++++++ README.md | 1 + 2 files changed, 17 insertions(+) create mode 100644 0189-rotate-array.js diff --git a/0189-rotate-array.js b/0189-rotate-array.js new file mode 100644 index 00000000..b6bcc49a --- /dev/null +++ b/0189-rotate-array.js @@ -0,0 +1,16 @@ +/** + * 189. Rotate Array + * https://leetcode.com/problems/rotate-array/ + * Difficulty: Medium + * + * Given an array, rotate the array to the right by k steps, where k is non-negative. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {void} Do not return anything, modify nums in-place instead. + */ +var rotate = function(nums, k) { + nums.unshift(...nums.splice((k % nums.length) * -1)); +}; diff --git a/README.md b/README.md index a948962a..9849b1e8 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,7 @@ 167|[Two Sum II - Input Array Is Sorted](./0167-two-sum-ii-input-array-is-sorted.js)|Easy| 169|[Majority Element](./0169-majority-element.js)|Easy| 179|[Largest Number](./0179-largest-number.js)|Medium| +189|[Rotate Array](./0189-rotate-array.js)|Medium| 191|[Number of 1 Bits](./0191-number-of-1-bits.js)|Easy| 203|[Remove Linked List Elements](./0203-remove-linked-list-elements.js)|Easy| 206|[Reverse Linked List](./0206-reverse-linked-list.js)|Easy| From 2945e6482582d398b3c67cecf3e3653acd23efd2 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 8 Jan 2022 16:54:51 -0500 Subject: [PATCH 242/919] Add solution #374 --- 0374-guess-number-higher-or-lower.js | 46 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 47 insertions(+) create mode 100644 0374-guess-number-higher-or-lower.js diff --git a/0374-guess-number-higher-or-lower.js b/0374-guess-number-higher-or-lower.js new file mode 100644 index 00000000..6ebde407 --- /dev/null +++ b/0374-guess-number-higher-or-lower.js @@ -0,0 +1,46 @@ +/** + * 374. Guess Number Higher or Lower + * https://leetcode.com/problems/guess-number-higher-or-lower/ + * Difficulty: Medium + * + * We are playing the Guess Game. The game is as follows: + * + * I pick a number from 1 to n. You have to guess which number I picked. + * + * Every time you guess wrong, I will tell you whether the number I picked is higher + * or lower than your guess. + * + * You call a pre-defined API int guess(int num), which returns 3 possible results: + * - -1: The number I picked is lower than your guess (i.e. pick < num). + * - 1: The number I picked is higher than your guess (i.e. pick > num). + * - 0: The number I picked is equal to your guess (i.e. pick == num). + * + * Return the number that I picked. + */ + +/** + * Forward declaration of guess API. + * @param {number} num your guess + * @return -1 if num is lower than the guess number + * 1 if num is higher than the guess number + * otherwise return 0 + * var guess = function(num) {} + */ + +/** + * @param {number} n + * @return {number} + */ +var guessNumber = function(n) { + let left = 1; + let right = n; + + while (left <= right) { + const pivot = Math.floor((right + left) / 2); + switch (guess(pivot)) { + case -1: right = pivot - 1; break; + case 1: left = pivot + 1; break; + case 0: return pivot; + } + } +}; diff --git a/README.md b/README.md index 9849b1e8..1530905c 100644 --- a/README.md +++ b/README.md @@ -105,6 +105,7 @@ 347|[Top K Frequent Elements](./0347-top-k-frequent-elements.js)|Medium| 349|[Intersection of Two Arrays](./0349-intersection-of-two-arrays.js)|Easy| 350|[Intersection of Two Arrays II](./0350-intersection-of-two-arrays-ii.js)|Easy| +374|[Guess Number Higher or Lower](./0374-guess-number-higher-or-lower.js)|Medium| 383|[Ransom Note](./0383-ransom-note.js)|Easy| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| 442|[Find All Duplicates in an Array](./0442-find-all-duplicates-in-an-array.js)|Medium| From dc4f85e1337f2531bcba20239e946582fede8919 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 8 Jan 2022 16:55:20 -0500 Subject: [PATCH 243/919] Add solution #344 --- 0344-reverse-string.js | 20 ++++++++++++++++++++ README.md | 1 + 2 files changed, 21 insertions(+) create mode 100644 0344-reverse-string.js diff --git a/0344-reverse-string.js b/0344-reverse-string.js new file mode 100644 index 00000000..e459e954 --- /dev/null +++ b/0344-reverse-string.js @@ -0,0 +1,20 @@ +/** + * 344. Reverse String + * https://leetcode.com/problems/reverse-string/ + * Difficulty: Easy + * + * Write a function that reverses a string. The input string is given as an array + * of characters s. + * + * You must do this by modifying the input array in-place with O(1) extra memory. + */ + +/** + * @param {character[]} s + * @return {void} Do not return anything, modify s in-place instead. + */ +var reverseString = function(s) { + for (let i = 0; i < Math.floor(s.length / 2); i++) { + [s[s.length - 1 - i], s[i]] = [s[i], s[s.length - 1 - i]]; + } +}; diff --git a/README.md b/README.md index 1530905c..cd7fe430 100644 --- a/README.md +++ b/README.md @@ -101,6 +101,7 @@ 283|[Move Zeroes](./0283-move-zeroes.js)|Easy| 326|[Power of Three](./0326-power-of-three.js)|Easy| 342|[Power of Four](./0342-power-of-four.js)|Easy| +344|[Reverse String](./0344-reverse-string.js)|Easy| 345|[Reverse Vowels of a String](./0345-reverse-vowels-of-a-string.js)|Easy| 347|[Top K Frequent Elements](./0347-top-k-frequent-elements.js)|Medium| 349|[Intersection of Two Arrays](./0349-intersection-of-two-arrays.js)|Easy| From fc58fc83de93702a22fb1dfe114800651de4aa7e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 9 Jan 2022 21:41:17 -0600 Subject: [PATCH 244/919] Add solution #1748 --- 1748-sum-of-unique-elements.js | 23 +++++++++++++++++++++++ README.md | 1 + 2 files changed, 24 insertions(+) create mode 100644 1748-sum-of-unique-elements.js diff --git a/1748-sum-of-unique-elements.js b/1748-sum-of-unique-elements.js new file mode 100644 index 00000000..2329b9a4 --- /dev/null +++ b/1748-sum-of-unique-elements.js @@ -0,0 +1,23 @@ +/** + * 1748. Sum of Unique Elements + * https://leetcode.com/problems/sum-of-unique-elements/ + * Difficulty: Easy + * + * You are given an integer array nums. The unique elements of an array are the + * elements that appear exactly once in the array. + * + * Return the sum of all the unique elements of nums. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var sumOfUnique = function(nums) { + const map = new Map(); + nums.forEach(n => map.set(n, (map.get(n) || 0) + 1)); + + return [...map].reduce((sum, [key, value]) => { + return sum + (value === 1 ? key : 0); + }, 0); +}; diff --git a/README.md b/README.md index cd7fe430..30fe1aa0 100644 --- a/README.md +++ b/README.md @@ -224,6 +224,7 @@ 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1668|[Maximum Repeating Substring](./1668-maximum-repeating-substring.js)|Easy| 1672|[Richest Customer Wealth](./1672-richest-customer-wealth.js)|Easy| +1748|[Sum of Unique Elements](./1748-sum-of-unique-elements.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| From b3d127b09cd3cb564e775934ed2628353b0dba65 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 9 Jan 2022 21:42:20 -0600 Subject: [PATCH 245/919] Add solution #876 --- 0876-middle-of-the-linked-list.js | 32 +++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 0876-middle-of-the-linked-list.js diff --git a/0876-middle-of-the-linked-list.js b/0876-middle-of-the-linked-list.js new file mode 100644 index 00000000..f027270c --- /dev/null +++ b/0876-middle-of-the-linked-list.js @@ -0,0 +1,32 @@ +/** + * 876. Middle of the Linked List + * https://leetcode.com/problems/middle-of-the-linked-list/ + * Difficulty: Easy + * + * 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. + */ + +/** + * 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) { + let slow = head; + let fast = head; + + while (fast && fast.next) { + slow = slow.next; + fast = fast.next.next; + } + + return slow; +}; diff --git a/README.md b/README.md index 30fe1aa0..fc072e02 100644 --- a/README.md +++ b/README.md @@ -146,6 +146,7 @@ 844|[Backspace String Compare](./0844-backspace-string-compare.js)|Easy| 846|[Hand of Straights](./0846-hand-of-straights.js)|Medium| 867|[Transpose Matrix](./0867-transpose-matrix.js)|Easy| +876|[Middle of the Linked List](./0876-middle-of-the-linked-list.js)|Easy| 884|[Uncommon Words from Two Sentences](./0884-uncommon-words-from-two-sentences.js)|Easy| 890|[Find and Replace Pattern](./0890-find-and-replace-pattern.js)|Medium| 916|[Word Subsets](./0916-word-subsets.js)|Medium| From f39cf945fac02f71f533b45b55d015fde9e4a852 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 9 Jan 2022 21:43:26 -0600 Subject: [PATCH 246/919] Add solution #2095 --- ...delete-the-middle-node-of-a-linked-list.js | 42 +++++++++++++++++++ README.md | 1 + 2 files changed, 43 insertions(+) create mode 100644 2095-delete-the-middle-node-of-a-linked-list.js diff --git a/2095-delete-the-middle-node-of-a-linked-list.js b/2095-delete-the-middle-node-of-a-linked-list.js new file mode 100644 index 00000000..92ff7870 --- /dev/null +++ b/2095-delete-the-middle-node-of-a-linked-list.js @@ -0,0 +1,42 @@ +/** + * 2095. Delete the Middle Node of a Linked List + * https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/ + * Difficulty: Medium + * + * You are given the head of a linked list. Delete the middle node, and return the head + * of the modified linked list. + * + * The middle node of a linked list of size n is the ⌊n / 2⌋th node from the start using + * 0-based indexing, where ⌊x⌋ denotes the largest integer less than or equal to x. + * + * For n = 1, 2, 3, 4, and 5, the middle nodes are 0, 1, 1, 2, and 2, respectively. + */ + +/** + * 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 deleteMiddle = function(head) { + let slow = new ListNode(0, head); + let fast = head; + + if (!head.next) { + return null; + } + + while (fast && fast.next) { + slow = slow.next; + fast = fast.next.next; + } + + slow.next = slow.next.next; + + return head; +}; diff --git a/README.md b/README.md index fc072e02..f38371ae 100644 --- a/README.md +++ b/README.md @@ -237,6 +237,7 @@ 2011|[Final Value of Variable After Performing Operations](./2011-final-value-of-variable-after-performing-operations.js)|Easy| 2016|[Maximum Difference Between Increasing Elements](./2016-maximum-difference-between-increasing-elements.js)|Easy| 2047|[Number of Valid Words in a Sentence](./2047-number-of-valid-words-in-a-sentence.js)|Easy| +2095|[Delete the Middle Node of a Linked List](./2095-delete-the-middle-node-of-a-linked-list.js)|Medium| 2114|[Maximum Number of Words Found in Sentences](./2114-maximum-number-of-words-found-in-sentences.js)|Easy| ## License From 24f4e22106f5376205d91af7fcc932bd7beb8ba6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 10 Jan 2022 19:32:10 -0600 Subject: [PATCH 247/919] Add solution #542 --- 0542-01-matrix.js | 45 +++++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 46 insertions(+) create mode 100644 0542-01-matrix.js diff --git a/0542-01-matrix.js b/0542-01-matrix.js new file mode 100644 index 00000000..57045094 --- /dev/null +++ b/0542-01-matrix.js @@ -0,0 +1,45 @@ +/** + * 542. 01 Matrix + * https://leetcode.com/problems/01-matrix/ + * Difficulty: Medium + * + * Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell. + * + * The distance between two adjacent cells is 1. + */ + +/** + * @param {number[][]} matrix + * @return {number[][]} + */ +var updateMatrix = function(matrix) { + const queue = []; + + for (let i = 0; i < matrix.length; i++) { + for (let j = 0; j < matrix[0].length; j++) { + if (matrix[i][j] === 0) { + queue.push([i, j, 0]); + } else { + matrix[i][j] = Infinity; + } + } + } + + + while (queue.length) { + const [i, j, k] = queue.shift(); + if (matrix[i][j] > k) { + matrix[i][j] = k; + } + [[-1, 0], [1, 0], [0, -1], [0, 1]].forEach(p => { + const [x, y, z] = [i + p[0], j + p[1], k + 1]; + if (x > -1 && x < matrix.length && y > -1 && y < matrix[0].length) { + if (matrix[x][y] === Infinity) { + queue.push([x, y, z]); + } + } + }); + } + + return matrix; +}; diff --git a/README.md b/README.md index f38371ae..f986cca8 100644 --- a/README.md +++ b/README.md @@ -117,6 +117,7 @@ 500|[Keyboard Row](./0500-keyboard-row.js)|Easy| 506|[Relative Ranks](./0506-relative-ranks.js)|Easy| 541|[Reverse String II](./0541-reverse-string-ii.js)|Easy| +542|[01 Matrix](./0542-01-matrix.js)|Medium| 551|[Student Attendance Record I](./0551-student-attendance-record-i.js)|Easy| 557|[Reverse Words in a String III](./0557-reverse-words-in-a-string-iii.js)|Easy| 565|[Array Nesting](./0565-array-nesting.js)|Medium| From c90114620f9c1ab6237a2ff7a1e237c2faf19727 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 10 Jan 2022 19:33:04 -0600 Subject: [PATCH 248/919] Add solution #599 --- 0599-minimum-index-sum-of-two-lists.js | 28 ++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 29 insertions(+) create mode 100644 0599-minimum-index-sum-of-two-lists.js diff --git a/0599-minimum-index-sum-of-two-lists.js b/0599-minimum-index-sum-of-two-lists.js new file mode 100644 index 00000000..0723e369 --- /dev/null +++ b/0599-minimum-index-sum-of-two-lists.js @@ -0,0 +1,28 @@ +/** + * 599. Minimum Index Sum of Two Lists + * https://leetcode.com/problems/minimum-index-sum-of-two-lists/ + * Difficulty: Easy + * + * Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list + * of favorite restaurants represented by strings. + * + * You need to help them find out their common interest with the least list index sum. + * If there is a choice tie between answers, output all of them with no order requirement. + * You could assume there always exists an answer. + */ + +/** + * @param {string[]} list1 + * @param {string[]} list2 + * @return {string[]} + */ +var findRestaurant = function(list1, list2) { + const map = new Map(list1.map((str, index) => [str, index])); + + return list2 + .map((str, index) => map.has(str) ? [map.get(str) + index, str] : null) + .filter(Boolean) + .sort(([a], [b]) => a - b) + .filter(([sum], index, [[lowest]]) => sum === lowest) + .map(([, str]) => str); +}; diff --git a/README.md b/README.md index f986cca8..d1aac1d7 100644 --- a/README.md +++ b/README.md @@ -123,6 +123,7 @@ 565|[Array Nesting](./0565-array-nesting.js)|Medium| 566|[Reshape the Matrix](./0566-reshape-the-matrix.js)|Easy| 567|[Permutation in String](./0567-permutation-in-string.js)|Medium| +599|[Minimum Index Sum of Two Lists](./0599-minimum-index-sum-of-two-lists.js)|Easy| 606|[Construct String from Binary Tree](./0606-construct-string-from-binary-tree.js)|Easy| 617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy| 628|[Maximum Product of Three Numbers](./0628-maximum-product-of-three-numbers.js)|Easy| From 0effdb2ebcec6d0e03021903b938631dc794687c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 10 Jan 2022 19:33:54 -0600 Subject: [PATCH 249/919] Add solution #905 --- 0905-sort-array-by-parity.js | 18 ++++++++++++++++++ README.md | 1 + 2 files changed, 19 insertions(+) create mode 100644 0905-sort-array-by-parity.js diff --git a/0905-sort-array-by-parity.js b/0905-sort-array-by-parity.js new file mode 100644 index 00000000..a2d65e8c --- /dev/null +++ b/0905-sort-array-by-parity.js @@ -0,0 +1,18 @@ +/** + * 905. Sort Array By Parity + * https://leetcode.com/problems/sort-array-by-parity/ + * Difficulty: Easy + * + * Given an integer array nums, move all the even integers at the beginning of + * the array followed by all the odd integers. + * + * Return any array that satisfies this condition. + */ + +/** + * @param {number[]} nums + * @return {number[]} + */ +var sortArrayByParity = function(nums) { + return nums.sort((a, b) => a % 2 === 0 ? -1 : 1); +}; diff --git a/README.md b/README.md index d1aac1d7..5cfd1da0 100644 --- a/README.md +++ b/README.md @@ -151,6 +151,7 @@ 876|[Middle of the Linked List](./0876-middle-of-the-linked-list.js)|Easy| 884|[Uncommon Words from Two Sentences](./0884-uncommon-words-from-two-sentences.js)|Easy| 890|[Find and Replace Pattern](./0890-find-and-replace-pattern.js)|Medium| +905|[Sort Array By Parity](./0905-sort-array-by-parity.js)|Easy| 916|[Word Subsets](./0916-word-subsets.js)|Medium| 925|[Long Pressed Name](./0925-long-pressed-name.js)|Easy| 929|[Unique Email Addresses](./0929-unique-email-addresses.js)|Easy| From c7791c41cc3b71e20155b78a3a076ef948e50dd3 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 11 Jan 2022 20:02:15 -0600 Subject: [PATCH 250/919] Add solution #1041 --- 1041-robot-bounded-in-circle.js | 34 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 1041-robot-bounded-in-circle.js diff --git a/1041-robot-bounded-in-circle.js b/1041-robot-bounded-in-circle.js new file mode 100644 index 00000000..96c15d3e --- /dev/null +++ b/1041-robot-bounded-in-circle.js @@ -0,0 +1,34 @@ +/** + * 1041. Robot Bounded In Circle + * https://leetcode.com/problems/robot-bounded-in-circle/ + * Difficulty: Medium + * + * On an infinite plane, a robot initially stands at (0, 0) and faces north. + * The robot can receive one of three instructions: + * - "G": go straight 1 unit; + * - "L": turn 90 degrees to the left; + * - "R": turn 90 degrees to the right. + * + * The robot performs the instructions given in order, and repeats them forever. + * Return true if and only if there exists a circle in the plane such that the + * robot never leaves the circle. + */ + +/** + * @param {string} instructions + * @return {boolean} + */ +var isRobotBounded = function(instructions) { + let x = 0, y = 0; + let dx = 0, dy = 1; + + for (const direction of instructions) { + switch (direction) { + case 'R': [dx, dy] = [dy, -dx]; break; + case 'L': [dy, dx] = [dx, -dy]; break; + case 'G': [x, y] = [x + dx, y + dy]; break; + } + } + + return (x === 0 && y === 0) || dy !== 1; +} diff --git a/README.md b/README.md index 5cfd1da0..5e294db9 100644 --- a/README.md +++ b/README.md @@ -165,6 +165,7 @@ 1009|[Complement of Base 10 Integer](./1009-complement-of-base-10-integer.js)|Easy| 1010|[Pairs of Songs With Total Durations Divisible by 60](./1010-pairs-of-songs-with-total-durations-divisible-by-60.js)|Medium| 1037|[Valid Boomerang](./1037-valid-boomerang.js)|Easy| +1041|[Robot Bounded In Circle](./1041-robot-bounded-in-circle.js)|Medium| 1103|[Distribute Candies to People](./1103-distribute-candies-to-people.js)|Easy| 1108|[Defanging an IP Address](./1108-defanging-an-ip-address.js)|Easy| 1189|[Maximum Number of Balloons](./1189-maximum-number-of-balloons.js)|Easy| From 8fa8f28ba1a82ed609c07279c12c7f23bcf4fc51 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 11 Jan 2022 20:02:59 -0600 Subject: [PATCH 251/919] Add solution #922 --- 0922-sort-array-by-parity-ii.js | 36 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 37 insertions(+) create mode 100644 0922-sort-array-by-parity-ii.js diff --git a/0922-sort-array-by-parity-ii.js b/0922-sort-array-by-parity-ii.js new file mode 100644 index 00000000..ce626ff7 --- /dev/null +++ b/0922-sort-array-by-parity-ii.js @@ -0,0 +1,36 @@ +/** + * 922. Sort Array By Parity II + * https://leetcode.com/problems/sort-array-by-parity-ii/ + * Difficulty: Easy + * + * Given an array of integers nums, half of the integers in nums are odd, + * and the other half are even. + * + * Sort the array so that whenever nums[i] is odd, i is odd, and whenever + * nums[i] is even, i is even. + * + * Return any answer array that satisfies this condition. + */ + +/** + * @param {number[]} nums + * @return {number[]} + */ +var sortArrayByParityII = function(nums) { + let i = 0; + let j = 1; + + while (i < nums.length && j < nums.length) { + if (nums[i] % 2 === 0) { + i += 2; + } else if (nums[j] % 2 === 1) { + j += 2; + } else { + [nums[i], nums[j]] = [nums[j], nums[i]]; + i += 2; + j += 2; + } + } + + return nums; +}; diff --git a/README.md b/README.md index 5e294db9..c171c480 100644 --- a/README.md +++ b/README.md @@ -153,6 +153,7 @@ 890|[Find and Replace Pattern](./0890-find-and-replace-pattern.js)|Medium| 905|[Sort Array By Parity](./0905-sort-array-by-parity.js)|Easy| 916|[Word Subsets](./0916-word-subsets.js)|Medium| +922|[Sort Array By Parity II](./0922-sort-array-by-parity-ii.js)|Easy| 925|[Long Pressed Name](./0925-long-pressed-name.js)|Easy| 929|[Unique Email Addresses](./0929-unique-email-addresses.js)|Easy| 966|[Vowel Spellchecker](./0966-vowel-spellchecker.js)|Medium| From a82fa4226c7fb9b86d18414deaf18c9037144e7e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 11 Jan 2022 20:04:53 -0600 Subject: [PATCH 252/919] Add solution #706 --- 0706-design-hashmap.js | 54 ++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 55 insertions(+) create mode 100644 0706-design-hashmap.js diff --git a/0706-design-hashmap.js b/0706-design-hashmap.js new file mode 100644 index 00000000..1c2ee037 --- /dev/null +++ b/0706-design-hashmap.js @@ -0,0 +1,54 @@ +/** + * 706. Design HashMap + * https://leetcode.com/problems/design-hashmap/ + * Difficulty: Easy + * + * Design a HashMap without using any built-in hash table libraries. + * Implement the MyHashMap class: + * - MyHashMap() initializes the object with an empty map. + * - void put(int key, int value) inserts a (key, value) pair into the HashMap. + * If the key already exists in the map, update the corresponding value. + * - int get(int key) returns the value to which the specified key is mapped, + * or -1 if this map contains no mapping for the key. + * - void remove(key) removes the key and its corresponding value if the map + * contains the mapping for the key. + */ + + +var MyHashMap = function() { + this._keys = []; + this._values = []; +}; + +/** + * @param {number} key + * @param {number} value + * @return {void} + */ +MyHashMap.prototype.put = function(key, value) { + if (this._keys[key] === undefined) { + this._values.push(value); + this._keys[key] = this._values.length - 1; + } else { + this._values[this._keys[key]] = value; + } +}; + +/** + * @param {number} key + * @return {number} + */ +MyHashMap.prototype.get = function(key) { + const offset = this._keys[key]; + return offset === undefined ? -1 : this._values[offset]; +} +/** + * @param {number} key + * @return {void} + */ +MyHashMap.prototype.remove = function(key) { + if (this._keys[key] !== undefined) { + this._values[this._keys[key]] = undefined; + this._keys[key] = undefined; + } +}; diff --git a/README.md b/README.md index c171c480..69869db7 100644 --- a/README.md +++ b/README.md @@ -134,6 +134,7 @@ 700|[Search in a Binary Search Tree](./0700-search-in-a-binary-search-tree.js)|Easy| 701|[Insert into a Binary Search Tree](./0701-insert-into-a-binary-search-tree.js)|Medium| 704|[Binary Search](./0704-binary-search.js)|Easy| +706|[Design HashMap](./0706-design-hashmap.js)|Easy| 713|[Subarray Product Less Than K](./0713-subarray-product-less-than-k.js)|Medium| 722|[Remove Comments](./0722-remove-comments.js)|Medium| 733|[Flood Fill](./0733-flood-fill.js)|Easy| From daae2cdff5e3973c6198a26b3c2f80a18ade5024 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 12 Jan 2022 18:33:11 -0600 Subject: [PATCH 253/919] Add solution #705 --- 0705-design-hashset.js | 42 ++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 43 insertions(+) create mode 100644 0705-design-hashset.js diff --git a/0705-design-hashset.js b/0705-design-hashset.js new file mode 100644 index 00000000..23d1ea0a --- /dev/null +++ b/0705-design-hashset.js @@ -0,0 +1,42 @@ +/** + * 705. Design HashSet + * https://leetcode.com/problems/design-hashset/ + * Difficulty: Easy + * + * Design a HashSet without using any built-in hash table libraries. + * + * Implement MyHashSet class: + * - void add(key) Inserts the value key into the HashSet. + * - bool contains(key) Returns whether the value key exists in the + * HashSet or not. + * - void remove(key) Removes the value key in the HashSet. If key + * does not exist in the HashSet, do nothing. + */ + +var MyHashSet = function() { + this._keys = []; +}; + +/** + * @param {number} key + * @return {void} + */ +MyHashSet.prototype.add = function(key) { + this._keys[key] = 1; +}; + +/** + * @param {number} key + * @return {void} + */ +MyHashSet.prototype.remove = function(key) { + this._keys[key] = undefined; +}; + +/** + * @param {number} key + * @return {boolean} + */ +MyHashSet.prototype.contains = function(key) { + return this._keys[key] !== undefined; +}; diff --git a/README.md b/README.md index 69869db7..79e880c0 100644 --- a/README.md +++ b/README.md @@ -134,6 +134,7 @@ 700|[Search in a Binary Search Tree](./0700-search-in-a-binary-search-tree.js)|Easy| 701|[Insert into a Binary Search Tree](./0701-insert-into-a-binary-search-tree.js)|Medium| 704|[Binary Search](./0704-binary-search.js)|Easy| +705|[Design HashSet](./0705-design-hashset.js)|Easy| 706|[Design HashMap](./0706-design-hashmap.js)|Easy| 713|[Subarray Product Less Than K](./0713-subarray-product-less-than-k.js)|Medium| 722|[Remove Comments](./0722-remove-comments.js)|Medium| From 95b1a9a527eb2253fd773e7b3a94860f48a35123 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 12 Jan 2022 18:33:58 -0600 Subject: [PATCH 254/919] Add solution #2053 --- 2053-kth-distinct-string-in-an-array.js | 29 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 30 insertions(+) create mode 100644 2053-kth-distinct-string-in-an-array.js diff --git a/2053-kth-distinct-string-in-an-array.js b/2053-kth-distinct-string-in-an-array.js new file mode 100644 index 00000000..237b26d3 --- /dev/null +++ b/2053-kth-distinct-string-in-an-array.js @@ -0,0 +1,29 @@ +/** + * 2053. Kth Distinct String in an Array + * https://leetcode.com/problems/kth-distinct-string-in-an-array/ + * Difficulty: Medium + * + * A distinct string is a string that is present only once in an array. + * + * Given an array of strings arr, and an integer k, return the kth distinct + * string present in arr. If there are fewer than k distinct strings, return + * an empty string "". + * + * Note that the strings are considered in the order in which they appear in + * the array. + */ + +/** + * @param {string[]} arr + * @param {number} k + * @return {string} + */ +var kthDistinct = function(arr, k) { + const map = new Map(); + arr.forEach(n => map.set(n, (map.get(n) || 0) + 1)); + + const sorted = [...map].sort(([,a], [,b]) => a - b); + const [kth, count] = sorted[k - 1] || []; + + return count === 1 ? kth : ''; +}; diff --git a/README.md b/README.md index 79e880c0..078a97b9 100644 --- a/README.md +++ b/README.md @@ -244,6 +244,7 @@ 2011|[Final Value of Variable After Performing Operations](./2011-final-value-of-variable-after-performing-operations.js)|Easy| 2016|[Maximum Difference Between Increasing Elements](./2016-maximum-difference-between-increasing-elements.js)|Easy| 2047|[Number of Valid Words in a Sentence](./2047-number-of-valid-words-in-a-sentence.js)|Easy| +2053|[Kth Distinct String in an Array](./2053-kth-distinct-string-in-an-array.js)|Medium| 2095|[Delete the Middle Node of a Linked List](./2095-delete-the-middle-node-of-a-linked-list.js)|Medium| 2114|[Maximum Number of Words Found in Sentences](./2114-maximum-number-of-words-found-in-sentences.js)|Easy| From 3430070e38cc26c4c7036319728ce31ca9f56bff Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 12 Jan 2022 18:34:34 -0600 Subject: [PATCH 255/919] Add solution #2085 --- ...-count-common-words-with-one-occurrence.js | 22 +++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 2085-count-common-words-with-one-occurrence.js diff --git a/2085-count-common-words-with-one-occurrence.js b/2085-count-common-words-with-one-occurrence.js new file mode 100644 index 00000000..416258f7 --- /dev/null +++ b/2085-count-common-words-with-one-occurrence.js @@ -0,0 +1,22 @@ +/** + * 2085. Count Common Words With One Occurrence + * https://leetcode.com/problems/count-common-words-with-one-occurrence/ + * Difficulty: Easy + * + * Given two string arrays words1 and words2, return the number of strings + * that appear exactly once in each of the two arrays. + */ + +/** + * @param {string[]} words1 + * @param {string[]} words2 + * @return {number} + */ +var countWords = function(words1, words2) { + const map = new Map(); + words1.forEach(n => map.set(n, (map.get(n) || 0) + 1)); + [...map].forEach(([key, count]) => count !== 1 ? map.delete(key) : null); + words2.forEach(n => map.has(n) ? map.set(n, (map.get(n) || 0) + 1) : null); + + return [...map].filter(([, count]) => count === 2).length; +}; diff --git a/README.md b/README.md index 078a97b9..dc5f6498 100644 --- a/README.md +++ b/README.md @@ -245,6 +245,7 @@ 2016|[Maximum Difference Between Increasing Elements](./2016-maximum-difference-between-increasing-elements.js)|Easy| 2047|[Number of Valid Words in a Sentence](./2047-number-of-valid-words-in-a-sentence.js)|Easy| 2053|[Kth Distinct String in an Array](./2053-kth-distinct-string-in-an-array.js)|Medium| +2085|[Count Common Words With One Occurrence](./2085-count-common-words-with-one-occurrence.js)|Easy| 2095|[Delete the Middle Node of a Linked List](./2095-delete-the-middle-node-of-a-linked-list.js)|Medium| 2114|[Maximum Number of Words Found in Sentences](./2114-maximum-number-of-words-found-in-sentences.js)|Easy| From 280df67942fa12cfba2e4e6377c7adc76fddeb2d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 13 Jan 2022 21:04:44 -0600 Subject: [PATCH 256/919] Add solution #994 --- 0994-rotting-oranges.js | 50 +++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 51 insertions(+) create mode 100644 0994-rotting-oranges.js diff --git a/0994-rotting-oranges.js b/0994-rotting-oranges.js new file mode 100644 index 00000000..0f866273 --- /dev/null +++ b/0994-rotting-oranges.js @@ -0,0 +1,50 @@ +/** + * 994. Rotting Oranges + * https://leetcode.com/problems/rotting-oranges/ + * Difficulty: Medium + * + * You are given an m x n grid where each cell can have one of three values: + * - 0 representing an empty cell, + * - 1 representing a fresh orange, or + * - 2 representing a rotten orange. + * + * Every minute, any fresh orange that is 4-directionally adjacent to a rotten + * orange becomes rotten. + * + * Return the minimum number of minutes that must elapse until no cell has a + * fresh orange. If this is impossible, return -1. + */ + +/** + * @param {number[][]} grid + * @return {number} + */ +var orangesRotting = function(grid) { + const queue = []; + let count = 0; + + for (let i = 0; i < grid.length; i++) { + for (let j = 0; j < grid[0].length; j++) { + if (grid[i][j] === 2) { + queue.push([i, j, 0]); + } + } + } + + while (queue.length) { + const [i, j, k] = queue.shift(); + [[-1, 0], [1, 0], [0, -1], [0, 1]].forEach(p => { + const [x, y, z] = [i + p[0], j + p[1], k + 1]; + if (x > -1 && x < grid.length && y > -1 && y < grid[0].length) { + if (grid[x][y] === 1) { + grid[x][y] = 2; + count = Math.max(count, z); + queue.push([x, y, z]); + } + } + }); + } + + const isIncomplete = grid.some(row => row.some(n => n === 1)); + return isIncomplete ? -1 : count; +}; diff --git a/README.md b/README.md index dc5f6498..6eeb2790 100644 --- a/README.md +++ b/README.md @@ -164,6 +164,7 @@ 977|[Squares of a Sorted Array](./0977-squares-of-a-sorted-array.js)|Easy| 985|[Sum of Even Numbers After Queries](./0985-sum-of-even-numbers-after-queries.js)|Easy| 989|[Add to Array-Form of Integer](./0989-add-to-array-form-of-integer.js)|Easy| +994|[Rotting Oranges](./0994-rotting-oranges.js)|Medium| 997|[Find the Town Judge](./0997-find-the-town-judge.js)|Easy| 1009|[Complement of Base 10 Integer](./1009-complement-of-base-10-integer.js)|Easy| 1010|[Pairs of Songs With Total Durations Divisible by 60](./1010-pairs-of-songs-with-total-durations-divisible-by-60.js)|Medium| From e3a291eb401f141833e2ee05806198b3bbcb3b0b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 13 Jan 2022 21:06:21 -0600 Subject: [PATCH 257/919] Add solution #463 --- 0463-island-perimeter.js | 36 ++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 37 insertions(+) create mode 100644 0463-island-perimeter.js diff --git a/0463-island-perimeter.js b/0463-island-perimeter.js new file mode 100644 index 00000000..9860ffc2 --- /dev/null +++ b/0463-island-perimeter.js @@ -0,0 +1,36 @@ +/** + * 463. Island Perimeter + * https://leetcode.com/problems/island-perimeter/ + * Difficulty: Medium + * + * You are given row x col grid representing a map where grid[i][j] = 1 represents land and + * grid[i][j] = 0 represents water. + * + * Grid cells are connected horizontally/vertically (not diagonally). The grid is completely + * surrounded by water, and there is exactly one island (i.e., one or more connected land cells). + * + * The island doesn't have "lakes", meaning the water inside isn't connected to the water around + * the island. One cell is a square with side length 1. The grid is rectangular, width and height + * don't exceed 100. Determine the perimeter of the island. + */ + +/** + * @param {number[][]} grid + * @return {number} + */ +var islandPerimeter = function(grid) { + let island = 0; + let adjacent = 0; + + for (let i = 0; i < grid.length; i++) { + for (let j = 0; j < grid[0].length; j++) { + if (grid[i][j] === 1) { + island++; + if (i + 1 < grid.length && grid[i + 1][j] === 1) adjacent++; + if (j + 1 < grid[0].length && grid[i][j + 1] === 1) adjacent++; + } + } + } + + return island * 4 - adjacent * 2; +}; diff --git a/README.md b/README.md index 6eeb2790..1628e60e 100644 --- a/README.md +++ b/README.md @@ -113,6 +113,7 @@ 448|[Find All Numbers Disappeared in an Array](./0448-find-all-numbers-disappeared-in-an-array.js)|Easy| 451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| 459|[Repeated Substring Pattern](./0459-repeated-substring-pattern.js)|Easy| +463|[Island Perimeter](./0463-island-perimeter.js)|Medium| 476|[Number Complement](./0476-number-complement.js)|Easy| 500|[Keyboard Row](./0500-keyboard-row.js)|Easy| 506|[Relative Ranks](./0506-relative-ranks.js)|Easy| From 6ae10697e535273404bbad8630e16eb006cd2cfa Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 13 Jan 2022 21:07:07 -0600 Subject: [PATCH 258/919] Add solution #77 --- 0077-combinations.js | 31 +++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 0077-combinations.js diff --git a/0077-combinations.js b/0077-combinations.js new file mode 100644 index 00000000..5295f645 --- /dev/null +++ b/0077-combinations.js @@ -0,0 +1,31 @@ +/** + * 77. Combinations + * https://leetcode.com/problems/combinations/ + * Difficulty: Medium + * + * Given two integers n and k, return all possible combinations of k numbers + * out of the range [1, n]. + * + * You may return the answer in any order. + */ + +/** + * @param {number} n + * @param {number} k + * @return {number[][]} + */ +var combine = function(n, k) { + const result = []; + backtrack(result, n, k); + return result; +}; + +function backtrack(result, n, k, combination = [], offset = 1) { + if (combination.length === k) { + result.push(combination); + } else { + while (offset <= n) { + backtrack(result, n, k, [...combination, offset], ++offset); + } + } +} diff --git a/README.md b/README.md index 1628e60e..6eea46cc 100644 --- a/README.md +++ b/README.md @@ -53,6 +53,7 @@ 67|[Add Binary](./0067-add-binary.js)|Easy| 73|[Set Matrix Zeroes](./0073-set-matrix-zeroes.js)|Medium| 74|[Search a 2D Matrix](./0074-search-a-2d-matrix.js)|Medium| +77|[Combinations](./0077-combinations.js)|Medium| 83|[Remove Duplicates from Sorted List](./0083-remove-duplicates-from-sorted-list.js)|Easy| 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| 94|[Binary Tree Inorder Traversal](./0094-binary-tree-inorder-traversal.js)|Easy| From 7e9465a82d2a639f411a3815e0faf21db4e34705 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 14 Jan 2022 22:35:59 -0600 Subject: [PATCH 259/919] Add solution #39 --- 0039-combination-sum.js | 39 +++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 40 insertions(+) create mode 100644 0039-combination-sum.js diff --git a/0039-combination-sum.js b/0039-combination-sum.js new file mode 100644 index 00000000..967d7dd1 --- /dev/null +++ b/0039-combination-sum.js @@ -0,0 +1,39 @@ +/** + * 39. Combination Sum + * https://leetcode.com/problems/combination-sum/ + * Difficulty: Medium + * + * Given an array of distinct integers candidates and a target integer target, + * return a list of all unique combinations of candidates where the chosen + * numbers sum to target. You may return the combinations in any order. + * + * The same number may be chosen from candidates an unlimited number of times. + * Two combinations are unique if the frequency of at least one of the chosen + * numbers is different. + * + * It is guaranteed that the number of unique combinations that sum up to target + * is less than 150 combinations for the given input. + */ + +/** + * @param {number[]} candidates + * @param {number} target + * @return {number[][]} + */ +var combinationSum = function(candidates, target) { + const result = []; + backtrack(result, candidates, target); + return result; +}; + +function backtrack(result, candidates, target, combination = [], offset = 0) { + if (target < 0) { + return; + } else if (target === 0) { + result.push(combination); + } else { + for (let i = offset; i < candidates.length; i++) { + backtrack(result, candidates, target - candidates[i], [...combination, candidates[i]], i); + } + } +} diff --git a/README.md b/README.md index 6eea46cc..b89eed22 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,7 @@ 34|[Find First and Last Position of Element in Sorted Array](./0034-find-first-and-last-position-of-element-in-sorted-array.js)|Medium| 35|[Search Insert Position](./0035-search-insert-position.js)|Easy| 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| +39|[Combination Sum](./0039-combination-sum.js)|Medium| 41|[First Missing Positive](./0041-first-missing-positive.js)|Hard| 42|[Trapping Rain Water](./0042-trapping-rain-water.js)|Hard| 43|[Multiply Strings](./0043-multiply-strings.js)|Medium| From d0a3aa34371e9efa1b022a8627e3fd720a3b7efc Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 14 Jan 2022 22:36:51 -0600 Subject: [PATCH 260/919] Add solution #40 --- 0040-combination-sum-ii.js | 37 +++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 38 insertions(+) create mode 100644 0040-combination-sum-ii.js diff --git a/0040-combination-sum-ii.js b/0040-combination-sum-ii.js new file mode 100644 index 00000000..f38ed62e --- /dev/null +++ b/0040-combination-sum-ii.js @@ -0,0 +1,37 @@ +/** + * 40. Combination Sum II + * https://leetcode.com/problems/combination-sum-ii/ + * Difficulty: Medium + * + * Given a collection of candidate numbers (candidates) and a target number (target), + * find all unique combinations in candidates where the candidate numbers sum to target. + * + * Each number in candidates may only be used once in the combination. + * + * Note: The solution set must not contain duplicate combinations. + */ + +/** + * @param {number[]} candidates + * @param {number} target + * @return {number[][]} + */ +var combinationSum2 = function(candidates, target) { + const result = []; + candidates.sort((a, b) => a - b); + backtrack(result, candidates, target); + return result; +}; + +function backtrack(result, candidates, target, combination = [], offset = 0) { + if (target < 0) { + return; + } else if (target === 0) { + result.push(combination); + } else { + for (let i = offset; i < candidates.length; i++) { + if (i > offset && candidates[i] === candidates[i - 1]) continue; + backtrack(result, candidates, target - candidates[i], [...combination, candidates[i]], i + 1); + } + } +} diff --git a/README.md b/README.md index b89eed22..2ff10fce 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,7 @@ 35|[Search Insert Position](./0035-search-insert-position.js)|Easy| 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| 39|[Combination Sum](./0039-combination-sum.js)|Medium| +40|[Combination Sum II](./0040-combination-sum-ii.js)|Medium| 41|[First Missing Positive](./0041-first-missing-positive.js)|Hard| 42|[Trapping Rain Water](./0042-trapping-rain-water.js)|Hard| 43|[Multiply Strings](./0043-multiply-strings.js)|Medium| From dc0b75b148890c530723c6341b67ab58a85b8c72 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 14 Jan 2022 22:38:22 -0600 Subject: [PATCH 261/919] Add solution #1832 --- 1832-check-if-the-sentence-is-pangram.js | 19 +++++++++++++++++++ README.md | 1 + 2 files changed, 20 insertions(+) create mode 100644 1832-check-if-the-sentence-is-pangram.js diff --git a/1832-check-if-the-sentence-is-pangram.js b/1832-check-if-the-sentence-is-pangram.js new file mode 100644 index 00000000..2a50c935 --- /dev/null +++ b/1832-check-if-the-sentence-is-pangram.js @@ -0,0 +1,19 @@ +/** + * 1832. Check if the Sentence Is Pangram + * https://leetcode.com/problems/check-if-the-sentence-is-pangram/ + * Difficulty: Easy + * + * A pangram is a sentence where every letter of the English alphabet appears + * at least once. + * + * Given a string sentence containing only lowercase English letters, return + * true if sentence is a pangram, or false otherwise. + */ + +/** + * @param {string} sentence + * @return {boolean} + */ +var checkIfPangram = function(sentence) { + return new Set([...sentence]).size === 26; +}; diff --git a/README.md b/README.md index 2ff10fce..abd9609b 100644 --- a/README.md +++ b/README.md @@ -239,6 +239,7 @@ 1672|[Richest Customer Wealth](./1672-richest-customer-wealth.js)|Easy| 1748|[Sum of Unique Elements](./1748-sum-of-unique-elements.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| +1832|[Check if the Sentence Is Pangram](./1832-check-if-the-sentence-is-pangram.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| 1920|[Build Array from Permutation](./1920-build-array-from-permutation.js)|Easy| From ede1d129f344fa506e6f97bfd2bf0801f9873d37 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 15 Jan 2022 17:33:32 -0600 Subject: [PATCH 262/919] Add solution #784 --- 0784-letter-case-permutation.js | 35 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 36 insertions(+) create mode 100644 0784-letter-case-permutation.js diff --git a/0784-letter-case-permutation.js b/0784-letter-case-permutation.js new file mode 100644 index 00000000..67b389cd --- /dev/null +++ b/0784-letter-case-permutation.js @@ -0,0 +1,35 @@ +/** + * 784. Letter Case Permutation + * https://leetcode.com/problems/letter-case-permutation/ + * Difficulty: Medium + * + * Given a string s, you can transform every letter individually to be lowercase or uppercase + * to create another string. + * + * Return a list of all possible strings we could create. Return the output in any order. + */ + +/** + * @param {string} str + * @return {string[]} + */ +var letterCasePermutation = function(str) { + const result = []; + backtrack(result, str); + return result; +}; + +function backtrack(result, input, permutation = '', offset = 0) { + if (input.length === permutation.length) { + result.push(permutation); + } else { + const target = input[offset]; + if (isNaN(target)) { + [target.toLowerCase(), target.toUpperCase()].forEach(s => { + backtrack(result, input, permutation + s, offset + 1); + }); + } else { + backtrack(result, input, permutation + target, offset + 1); + } + } +} diff --git a/README.md b/README.md index abd9609b..2badda89 100644 --- a/README.md +++ b/README.md @@ -144,6 +144,7 @@ 722|[Remove Comments](./0722-remove-comments.js)|Medium| 733|[Flood Fill](./0733-flood-fill.js)|Easy| 739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium| +784|[Letter Case Permutation](./0784-letter-case-permutation.js)|Medium| 791|[Custom Sort String](./0791-custom-sort-string.js)|Medium| 796|[Rotate String](./0796-rotate-string.js)|Easy| 804|[Unique Morse Code Words](./0804-unique-morse-code-words.js)|Easy| From 8594f3814274f16b2c845dbf7fd5931968dd4c2d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 15 Jan 2022 17:34:39 -0600 Subject: [PATCH 263/919] Add solution #100 --- 0100-same-tree.js | 30 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 0100-same-tree.js diff --git a/0100-same-tree.js b/0100-same-tree.js new file mode 100644 index 00000000..e1ef3e3a --- /dev/null +++ b/0100-same-tree.js @@ -0,0 +1,30 @@ +/** + * 100. Same Tree + * https://leetcode.com/problems/same-tree/ + * Difficulty: Easy + * + * Given the roots of two binary trees p and q, write a function to check if they are + * the same or not. + * + * Two binary trees are considered the same if they are structurally identical, and + * the nodes have the same value. + */ + +/** + * 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} p + * @param {TreeNode} q + * @return {boolean} + */ +var isSameTree = function(p, q) { + const hasSameValue = p !== null && q !== null && p.val === q.val; + const hasSameTree = hasSameValue && isSameTree(p.left, q.left) && isSameTree(p.right, q.right); + return (p === null && q === null) || hasSameTree; +}; diff --git a/README.md b/README.md index 2badda89..5886d8cc 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,7 @@ 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| 94|[Binary Tree Inorder Traversal](./0094-binary-tree-inorder-traversal.js)|Easy| 98|[Validate Binary Search Tree](./0098-validate-binary-search-tree.js)|Medium| +100|[Same Tree](./0100-same-tree.js)|Easy| 101|[Symmetric Tree](./0101-symmetric-tree.js)|Easy| 102|[Binary Tree Level Order Traversal](./0102-binary-tree-level-order-traversal.js)|Medium| 104|[Maximum Depth of Binary Tree](./0104-maximum-depth-of-binary-tree.js)|Easy| From 2b9bfb2bed0d98e596fd987cc296302605ba91c5 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 15 Jan 2022 17:35:43 -0600 Subject: [PATCH 264/919] Add solution #1022 --- 1022-sum-of-root-to-leaf-binary-numbers.js | 41 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 42 insertions(+) create mode 100644 1022-sum-of-root-to-leaf-binary-numbers.js diff --git a/1022-sum-of-root-to-leaf-binary-numbers.js b/1022-sum-of-root-to-leaf-binary-numbers.js new file mode 100644 index 00000000..bfa8f868 --- /dev/null +++ b/1022-sum-of-root-to-leaf-binary-numbers.js @@ -0,0 +1,41 @@ +/** + * 1022. Sum of Root To Leaf Binary Numbers + * https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/ + * Difficulty: Easy + * + * You are given the root of a binary tree where each node has a value 0 or 1. Each root-to-leaf + * path represents a binary number starting with the most significant bit. + * + * For example, if the path is 0 -> 1 -> 1 -> 0 -> 1, then this could represent 01101 in binary, + * which is 13. + * + * For all leaves in the tree, consider the numbers represented by the path from the root to that + * leaf. Return the sum of these numbers. + * + * The test cases are generated so that the answer fits in a 32-bits integer. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number} + */ +var sumRootToLeaf = function(root) { + return dfs(root); +}; + +function dfs(node, str = '') { + if (!node) return 0; + str += node.val; + if (!node.left && !node.right) { + return parseInt(str, 2) + } + return dfs(node.left, str) + dfs(node.right, str); +} diff --git a/README.md b/README.md index 5886d8cc..4ca0887f 100644 --- a/README.md +++ b/README.md @@ -174,6 +174,7 @@ 997|[Find the Town Judge](./0997-find-the-town-judge.js)|Easy| 1009|[Complement of Base 10 Integer](./1009-complement-of-base-10-integer.js)|Easy| 1010|[Pairs of Songs With Total Durations Divisible by 60](./1010-pairs-of-songs-with-total-durations-divisible-by-60.js)|Medium| +1022|[Sum of Root To Leaf Binary Numbers](./1022-sum-of-root-to-leaf-binary-numbers.js)|Easy| 1037|[Valid Boomerang](./1037-valid-boomerang.js)|Easy| 1041|[Robot Bounded In Circle](./1041-robot-bounded-in-circle.js)|Medium| 1103|[Distribute Candies to People](./1103-distribute-candies-to-people.js)|Easy| From 65d7f3853ddea892ea5283f68c32d78016c41c00 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 16 Jan 2022 22:35:34 -0600 Subject: [PATCH 265/919] Add solution #1669 --- 1669-merge-in-between-linked-lists.js | 44 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 45 insertions(+) create mode 100644 1669-merge-in-between-linked-lists.js diff --git a/1669-merge-in-between-linked-lists.js b/1669-merge-in-between-linked-lists.js new file mode 100644 index 00000000..6a637b0a --- /dev/null +++ b/1669-merge-in-between-linked-lists.js @@ -0,0 +1,44 @@ +/** + * 1669. Merge In Between Linked Lists + * https://leetcode.com/problems/merge-in-between-linked-lists/ + * Difficulty: Medium + * + * You are given two linked lists: list1 and list2 of sizes n and m respectively. + * + * Remove list1's nodes from the ath node to the bth node, and put list2 in their place. + * + * The blue edges and nodes in the following figure indicate the result: + */ + +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} list1 + * @param {number} a + * @param {number} b + * @param {ListNode} list2 + * @return {ListNode} + */ +var mergeInBetween = function(list1, a, b, list2) { + const result = new ListNode(0, list1); + + for (let i = 1; i < a; i++) { + list1 = list1.next; + } + let tail = list1.next; + list1.next = list2; + for (let i = a; i < b; i++) { + tail = tail.next; + } + while (list1 && list1.next) { + list1 = list1.next; + } + list1.next = tail.next; + + return result.next; +}; diff --git a/README.md b/README.md index 4ca0887f..9ff1bd57 100644 --- a/README.md +++ b/README.md @@ -239,6 +239,7 @@ 1566|[Detect Pattern of Length M Repeated K or More Times](./1566-detect-pattern-of-length-m-repeated-k-or-more-times.js)|Easy| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1668|[Maximum Repeating Substring](./1668-maximum-repeating-substring.js)|Easy| +1669|[Merge In Between Linked Lists](./1669-merge-in-between-linked-lists.js)|Medium| 1672|[Richest Customer Wealth](./1672-richest-customer-wealth.js)|Easy| 1748|[Sum of Unique Elements](./1748-sum-of-unique-elements.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| From 09dd2fe9668970e72bb8cb4b40655d0df78fb290 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 16 Jan 2022 22:36:10 -0600 Subject: [PATCH 266/919] Add solution #1512 --- 1512-number-of-good-pairs.js | 18 ++++++++++++++++++ README.md | 1 + 2 files changed, 19 insertions(+) create mode 100644 1512-number-of-good-pairs.js diff --git a/1512-number-of-good-pairs.js b/1512-number-of-good-pairs.js new file mode 100644 index 00000000..eb5c60d8 --- /dev/null +++ b/1512-number-of-good-pairs.js @@ -0,0 +1,18 @@ +/** + * 1512. Number of Good Pairs + * https://leetcode.com/problems/number-of-good-pairs/ + * Difficulty: Easy + * + * Given an array of integers nums, return the number of good pairs. + * + * A pair (i, j) is called good if nums[i] == nums[j] and i < j. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var numIdenticalPairs = function(nums) { + const map = new Array(101).fill(0); + return nums.reduce((sum, n) => sum += map[n]++, 0); +}; diff --git a/README.md b/README.md index 9ff1bd57..cc692657 100644 --- a/README.md +++ b/README.md @@ -234,6 +234,7 @@ 1496|[Path Crossing](./1496-path-crossing.js)|Easy| 1502|[Can Make Arithmetic Progression From Sequence](./1502-can-make-arithmetic-progression-from-sequence.js)|Easy| 1507|[Reformat Date](./1507-reformat-date.js)|Easy| +1512|[Number of Good Pairs](./1512-number-of-good-pairs.js)|Easy| 1550|[Three Consecutive Odds](./1550-three-consecutive-odds.js)|Easy| 1551|[Minimum Operations to Make Array Equal](./1551-minimum-operations-to-make-array-equal.js)|Medium| 1566|[Detect Pattern of Length M Repeated K or More Times](./1566-detect-pattern-of-length-m-repeated-k-or-more-times.js)|Easy| From 24f6ea69cc4de9fd33e47d7367712e599c36bc1e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 16 Jan 2022 22:39:47 -0600 Subject: [PATCH 267/919] Add solution #645 --- 0645-set-mismatch.js | 40 ++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 41 insertions(+) create mode 100644 0645-set-mismatch.js diff --git a/0645-set-mismatch.js b/0645-set-mismatch.js new file mode 100644 index 00000000..8e60aa14 --- /dev/null +++ b/0645-set-mismatch.js @@ -0,0 +1,40 @@ +/** + * 645. Set Mismatch + * https://leetcode.com/problems/set-mismatch/ + * Difficulty: Medium + * + * You have a set of integers s, which originally contains all the numbers from 1 to n. + * Unfortunately, due to some error, one of the numbers in s got duplicated to another + * number in the set, which results in repetition of one number and loss of another number. + * + * You are given an integer array nums representing the data status of this set after + * the error. + * + * Find the number that occurs twice and the number that is missing and return them in + * the form of an array. + */ + +/** + * @param {number[]} nums + * @return {number[]} + */ +var findErrorNums = function(nums) { + const set = new Set(); + const result = []; + + for (const n of nums) { + if (set.has(n)) { + result.push(n); + } + set.add(n); + } + + for (let i = nums.length; i > 0; i--) { + if (!set.has(i)) { + result.push(i); + break; + } + } + + return result; +}; diff --git a/README.md b/README.md index cc692657..9c1592d7 100644 --- a/README.md +++ b/README.md @@ -132,6 +132,7 @@ 606|[Construct String from Binary Tree](./0606-construct-string-from-binary-tree.js)|Easy| 617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy| 628|[Maximum Product of Three Numbers](./0628-maximum-product-of-three-numbers.js)|Easy| +645|[Set Mismatch](./0645-set-mismatch.js)|Medium| 648|[Replace Words](./0648-replace-words.js)|Medium| 653|[Two Sum IV - Input is a BST](./0653-two-sum-iv-input-is-a-bst.js)|Easy| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| From 479bd6008f8767b6984feb276751f5d9c884aca0 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 17 Jan 2022 22:42:18 -0600 Subject: [PATCH 268/919] Add solution #190 --- 0190-reverse-bits.js | 15 +++++++++++++++ README.md | 1 + 2 files changed, 16 insertions(+) create mode 100644 0190-reverse-bits.js diff --git a/0190-reverse-bits.js b/0190-reverse-bits.js new file mode 100644 index 00000000..fef88995 --- /dev/null +++ b/0190-reverse-bits.js @@ -0,0 +1,15 @@ +/** + * 190. Reverse Bits + * https://leetcode.com/problems/reverse-bits/ + * Difficulty: Easy + * + * Reverse bits of a given 32 bits unsigned integer. + */ + +/** + * @param {number} n - a positive integer + * @return {number} - a positive integer + */ +var reverseBits = function(n) { + return parseInt([...n.toString(2)].reverse().join('').padEnd(32, '0'), 2); +}; diff --git a/README.md b/README.md index 9c1592d7..52feaf1c 100644 --- a/README.md +++ b/README.md @@ -82,6 +82,7 @@ 169|[Majority Element](./0169-majority-element.js)|Easy| 179|[Largest Number](./0179-largest-number.js)|Medium| 189|[Rotate Array](./0189-rotate-array.js)|Medium| +190|[Reverse Bits](./0190-reverse-bits.js)|Easy| 191|[Number of 1 Bits](./0191-number-of-1-bits.js)|Easy| 203|[Remove Linked List Elements](./0203-remove-linked-list-elements.js)|Easy| 206|[Reverse Linked List](./0206-reverse-linked-list.js)|Easy| From a22177360b19cf812931bfb146ab24eb045c42aa Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 17 Jan 2022 22:43:37 -0600 Subject: [PATCH 269/919] Add solution #1002 --- 1002-find-common-characters.js | 24 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 1002-find-common-characters.js diff --git a/1002-find-common-characters.js b/1002-find-common-characters.js new file mode 100644 index 00000000..89cfa794 --- /dev/null +++ b/1002-find-common-characters.js @@ -0,0 +1,24 @@ +/** + * 1002. Find Common Characters + * https://leetcode.com/problems/find-common-characters/ + * Difficulty: Easy + * + * Given a string array words, return an array of all characters that show up in all strings within + * the words (including duplicates). You may return the answer in any order. + */ + +/** + * @param {string[]} words + * @return {string[]} + */ +var commonChars = function(words) { + return words + .map(word => [...word]) + .reduce((common, word) => common.filter(s => { + const index = word.indexOf(s); + if (index !== -1) { + word.splice(index, 1); + } + return index !== -1; + }), [...words[0]]); +}; diff --git a/README.md b/README.md index 52feaf1c..8afa3b55 100644 --- a/README.md +++ b/README.md @@ -174,6 +174,7 @@ 989|[Add to Array-Form of Integer](./0989-add-to-array-form-of-integer.js)|Easy| 994|[Rotting Oranges](./0994-rotting-oranges.js)|Medium| 997|[Find the Town Judge](./0997-find-the-town-judge.js)|Easy| +1002|[Find Common Characters](./1002-find-common-characters.js)|Easy| 1009|[Complement of Base 10 Integer](./1009-complement-of-base-10-integer.js)|Easy| 1010|[Pairs of Songs With Total Durations Divisible by 60](./1010-pairs-of-songs-with-total-durations-divisible-by-60.js)|Medium| 1022|[Sum of Root To Leaf Binary Numbers](./1022-sum-of-root-to-leaf-binary-numbers.js)|Easy| From 55a25672c454e1bdc885088df9953422dd69d66f Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 17 Jan 2022 22:46:43 -0600 Subject: [PATCH 270/919] Add solution #70 --- 0070-climbing-stairs.js | 26 ++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 27 insertions(+) create mode 100644 0070-climbing-stairs.js diff --git a/0070-climbing-stairs.js b/0070-climbing-stairs.js new file mode 100644 index 00000000..1eff99b0 --- /dev/null +++ b/0070-climbing-stairs.js @@ -0,0 +1,26 @@ +/** + * 70. Climbing Stairs + * https://leetcode.com/problems/climbing-stairs/ + * Difficulty: Easy + * + * You are climbing a staircase. It takes n steps to reach the top. + * + * Each time you can either climb 1 or 2 steps. In how many distinct + * ways can you climb to the top? + */ + +/** + * @param {number} n + * @return {number} + */ +var climbStairs = function(n) { + const cache = new Map(); + const memo = n => { + if (n < 4) return n; + if (!cache.has(n)) { + cache.set(n, memo(n - 2) + memo(n - 1)); + } + return cache.get(n); + }; + return memo(n); +}; diff --git a/README.md b/README.md index 8afa3b55..504d0ed9 100644 --- a/README.md +++ b/README.md @@ -53,6 +53,7 @@ 58|[Length of Last Word](./0058-length-of-last-word.js)|Easy| 66|[Plus One](./0066-plus-one.js)|Easy| 67|[Add Binary](./0067-add-binary.js)|Easy| +70|[Climbing Stairs](./0070-climbing-stairs.js)|Easy| 73|[Set Matrix Zeroes](./0073-set-matrix-zeroes.js)|Medium| 74|[Search a 2D Matrix](./0074-search-a-2d-matrix.js)|Medium| 77|[Combinations](./0077-combinations.js)|Medium| From 3d07962263609222c9529ba23da17d2b8e100717 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 18 Jan 2022 23:27:19 -0600 Subject: [PATCH 271/919] Add solution #142 --- 0142-linked-list-cycle-ii.js | 39 ++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 40 insertions(+) create mode 100644 0142-linked-list-cycle-ii.js diff --git a/0142-linked-list-cycle-ii.js b/0142-linked-list-cycle-ii.js new file mode 100644 index 00000000..90af7780 --- /dev/null +++ b/0142-linked-list-cycle-ii.js @@ -0,0 +1,39 @@ +/** + * 142. Linked List Cycle II + * https://leetcode.com/problems/linked-list-cycle-ii/ + * Difficulty: Medium + * + * Given the head of a linked list, return the node where the cycle begins. + * If there is no cycle, return null. + * + * There is a cycle in a linked list if there is some node in the list that + * can be reached again by continuously following the next pointer. Internally, + * pos is used to denote the index of the node that tail's next pointer is + * connected to (0-indexed). It is -1 if there is no cycle. Note that pos is + * not passed as a parameter. + * + * Do not modify the linked list. + */ + +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ + +/** + * @param {ListNode} head + * @return {ListNode} + */ +var detectCycle = function(head) { + while (head) { + if (head.visited) { + return head; + } + head.visited = 1; + head = head.next; + } + return head; +}; diff --git a/README.md b/README.md index 504d0ed9..19a1364c 100644 --- a/README.md +++ b/README.md @@ -75,6 +75,7 @@ 133|[Clone Graph](./0133-clone-graph.js)|Medium| 136|[Single Number](./0136-single-number.js)|Easy| 141|[Linked List Cycle](./0141-linked-list-cycle.js)|Easy| +142|[Linked List Cycle II](./0142-linked-list-cycle-ii.js)|Medium| 144|[Binary Tree Preorder Traversal](./0144-binary-tree-preorder-traversal.js)|Easy| 145|[Binary Tree Postorder Traversal](./0145-binary-tree-postorder-traversal.js)|Easy| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| From e98e2ba5b8607f3da891e6628926978f21f0f020 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 18 Jan 2022 23:29:43 -0600 Subject: [PATCH 272/919] Add solution #198 --- 0198-house-robber.js | 30 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 0198-house-robber.js diff --git a/0198-house-robber.js b/0198-house-robber.js new file mode 100644 index 00000000..ab37ccec --- /dev/null +++ b/0198-house-robber.js @@ -0,0 +1,30 @@ +/** + * 198. House Robber + * https://leetcode.com/problems/house-robber/ + * Difficulty: Medium + * + * You are a professional robber planning to rob houses along a street. Each house has a certain + * amount of money stashed, the only constraint stopping you from robbing each of them is that + * adjacent houses have security systems connected and it will automatically contact the police + * if two adjacent houses were broken into on the same night. + * + * Given an integer array nums representing the amount of money of each house, return the maximum + * amount of money you can rob tonight without alerting the police. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var rob = function(nums) { + let previous = 0; + let current = 0; + + for (const n of nums) { + const temp = previous; + previous = current; + current = Math.max(temp + n, previous); + } + + return Math.max(current, previous); +}; diff --git a/README.md b/README.md index 19a1364c..032ca2a7 100644 --- a/README.md +++ b/README.md @@ -86,6 +86,7 @@ 189|[Rotate Array](./0189-rotate-array.js)|Medium| 190|[Reverse Bits](./0190-reverse-bits.js)|Easy| 191|[Number of 1 Bits](./0191-number-of-1-bits.js)|Easy| +198|[House Robber](./0198-house-robber.js)|Medium| 203|[Remove Linked List Elements](./0203-remove-linked-list-elements.js)|Easy| 206|[Reverse Linked List](./0206-reverse-linked-list.js)|Easy| 214|[Shortest Palindrome](./0214-shortest-palindrome.js)|Hard| From eeb074eaefc5f4f04b81a62416c20fd1373be8b0 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 18 Jan 2022 23:56:04 -0600 Subject: [PATCH 273/919] Add solution #213 --- 0213-house-robber-ii.js | 41 +++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 42 insertions(+) create mode 100644 0213-house-robber-ii.js diff --git a/0213-house-robber-ii.js b/0213-house-robber-ii.js new file mode 100644 index 00000000..9bed09ac --- /dev/null +++ b/0213-house-robber-ii.js @@ -0,0 +1,41 @@ +/** + * 213. House Robber II + * https://leetcode.com/problems/house-robber-ii/ + * Difficulty: Medium + * + * You are a professional robber planning to rob houses along a street. Each house has a certain + * amount of money stashed. All houses at this place are arranged in a circle. That means the + * first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system + * connected, and it will automatically contact the police if two adjacent houses were broken into + * on the same night. + * + * Given an integer array nums representing the amount of money of each house, return the maximum + * amount of money you can rob tonight without alerting the police. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var rob = function(nums) { + if (nums.length === 1) { + return nums[0]; + } + + return Math.max( + handlePermutation(nums, 0, nums.length - 1), + handlePermutation(nums, 1, nums.length) + ); +}; + +function handlePermutation(nums, start, end) { + let previous = 0, current = 0; + + for (let i = start; i < end; i++) { + const temp = previous; + previous = current; + current = Math.max(temp + nums[i], previous); + } + + return Math.max(current, previous); +} diff --git a/README.md b/README.md index 032ca2a7..8b48b911 100644 --- a/README.md +++ b/README.md @@ -89,6 +89,7 @@ 198|[House Robber](./0198-house-robber.js)|Medium| 203|[Remove Linked List Elements](./0203-remove-linked-list-elements.js)|Easy| 206|[Reverse Linked List](./0206-reverse-linked-list.js)|Easy| +213|[House Robber II](./0213-house-robber-ii.js)|Medium| 214|[Shortest Palindrome](./0214-shortest-palindrome.js)|Hard| 217|[Contains Duplicate](./0217-contains-duplicate.js)|Easy| 219|[Contains Duplicate II](./0219-contains-duplicate-ii.js)|Easy| From 985271d295c55cbb826aa58b67fcb551e4f791b7 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 19 Jan 2022 23:54:13 -0600 Subject: [PATCH 274/919] Add solution #120 --- 0120-triangle.js | 25 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 26 insertions(+) create mode 100644 0120-triangle.js diff --git a/0120-triangle.js b/0120-triangle.js new file mode 100644 index 00000000..6c2c41f9 --- /dev/null +++ b/0120-triangle.js @@ -0,0 +1,25 @@ +/** + * 120. Triangle + * https://leetcode.com/problems/triangle/ + * Difficulty: Medium + * + * Given a triangle array, return the minimum path sum from top to bottom. + * + * For each step, you may move to an adjacent number of the row below. More + * formally, if you are on index i on the current row, you may move to either + * index i or index i + 1 on the next row. + */ + +/** + * @param {number[][]} triangle + * @return {number} + */ +var minimumTotal = function(triangle) { + for (let i = triangle.length - 2; i > -1; i--) { + for (let j = 0; j < triangle[i].length; j++) { + triangle[i][j] += Math.min( triangle[i + 1][j], triangle[i + 1][j + 1]); + } + } + + return triangle[0][0]; +}; diff --git a/README.md b/README.md index 8b48b911..4882ee78 100644 --- a/README.md +++ b/README.md @@ -70,6 +70,7 @@ 116|[Populating Next Right Pointers in Each Node](./0116-populating-next-right-pointers-in-each-node.js)|Medium| 118|[Pascal's Triangle](./0118-pascals-triangle.js)|Easy| 119|[Pascal's Triangle II](./0119-pascals-triangle-ii.js)|Easy| +120|[Triangle](./0120-triangle.js)|Medium| 121|[Best Time to Buy and Sell Stock](./0121-best-time-to-buy-and-sell-stock.js)|Easy| 128|[Longest Consecutive Sequence](./0128-longest-consecutive-sequence.js)|Medium| 133|[Clone Graph](./0133-clone-graph.js)|Medium| From a6b0ee83063ff5b1eb4c00ea8cca89c4ede2586a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 20 Jan 2022 00:21:17 -0600 Subject: [PATCH 275/919] Add solution #1528 --- 1528-shuffle-string.js | 23 +++++++++++++++++++++++ README.md | 1 + 2 files changed, 24 insertions(+) create mode 100644 1528-shuffle-string.js diff --git a/1528-shuffle-string.js b/1528-shuffle-string.js new file mode 100644 index 00000000..ab185f8c --- /dev/null +++ b/1528-shuffle-string.js @@ -0,0 +1,23 @@ +/** + * 1528. Shuffle String + * https://leetcode.com/problems/shuffle-string/ + * Difficulty: Easy + * + * You are given a string s and an integer array indices of the same length. + * The string s will be shuffled such that the character at the ith position + * moves to indices[i] in the shuffled string. + * + * Return the shuffled string. + */ + +/** + * @param {string} s + * @param {number[]} indices + * @return {string} + */ +var restoreString = function(s, indices) { + return indices.reduce((result, index, offset) => { + result[index] = s[offset]; + return result; + }, new Array(indices.length)).join(''); +}; diff --git a/README.md b/README.md index 4882ee78..2bca2492 100644 --- a/README.md +++ b/README.md @@ -243,6 +243,7 @@ 1502|[Can Make Arithmetic Progression From Sequence](./1502-can-make-arithmetic-progression-from-sequence.js)|Easy| 1507|[Reformat Date](./1507-reformat-date.js)|Easy| 1512|[Number of Good Pairs](./1512-number-of-good-pairs.js)|Easy| +1528|[Shuffle String](./1528-shuffle-string.js)|Easy| 1550|[Three Consecutive Odds](./1550-three-consecutive-odds.js)|Easy| 1551|[Minimum Operations to Make Array Equal](./1551-minimum-operations-to-make-array-equal.js)|Medium| 1566|[Detect Pattern of Length M Repeated K or More Times](./1566-detect-pattern-of-length-m-repeated-k-or-more-times.js)|Easy| From ee118b0bf2159f8adc56534d4cf821ef19186d2d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 20 Jan 2022 00:47:10 -0600 Subject: [PATCH 276/919] Add solution #1576 --- ...-avoid-consecutive-repeating-characters.js | 39 +++++++++++++++++++ README.md | 1 + 2 files changed, 40 insertions(+) create mode 100644 1576-replace-all-s-to-avoid-consecutive-repeating-characters.js diff --git a/1576-replace-all-s-to-avoid-consecutive-repeating-characters.js b/1576-replace-all-s-to-avoid-consecutive-repeating-characters.js new file mode 100644 index 00000000..cc502651 --- /dev/null +++ b/1576-replace-all-s-to-avoid-consecutive-repeating-characters.js @@ -0,0 +1,39 @@ +/** + * 1576. Replace All ?'s to Avoid Consecutive Repeating Characters + * https://leetcode.com/problems/replace-all-s-to-avoid-consecutive-repeating-characters/ + * Difficulty: Medium + * + * Given a string s containing only lowercase English letters and the '?' character, convert all + * the '?' characters into lowercase letters such that the final string does not contain any + * consecutive repeating characters. You cannot modify the non '?' characters. + * + * It is guaranteed that there are no consecutive repeating characters in the given string except + * for '?'. + * + * Return the final string after all the conversions (possibly zero) have been made. If there is + * more than one solution, return any of them. It can be shown that an answer is always possible + * with the given constraints. + */ + +/** + * @param {string} s + * @return {string} + */ +var modifyString = function(s) { + const substitute = takenCharacteres => { + for (let charCode = 97; ; charCode++) { + const attempt = String.fromCharCode(charCode); + + if (!takenCharacteres.includes(attempt)) { + return attempt; + } + } + }; + + const result = [...s]; + for (let index = 0; index < s.length; index++) { + const takenCharacteres = [result[index - 1], result[index + 1]]; + result[index] = s[index] === '?' ? substitute(takenCharacteres) : s[index]; + } + return result.join(''); +}; diff --git a/README.md b/README.md index 2bca2492..1ad97805 100644 --- a/README.md +++ b/README.md @@ -247,6 +247,7 @@ 1550|[Three Consecutive Odds](./1550-three-consecutive-odds.js)|Easy| 1551|[Minimum Operations to Make Array Equal](./1551-minimum-operations-to-make-array-equal.js)|Medium| 1566|[Detect Pattern of Length M Repeated K or More Times](./1566-detect-pattern-of-length-m-repeated-k-or-more-times.js)|Easy| +1576|[Replace All ?'s to Avoid Consecutive Repeating Characters](./1576-replace-all-s-to-avoid-consecutive-repeating-characters.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| 1668|[Maximum Repeating Substring](./1668-maximum-repeating-substring.js)|Easy| 1669|[Merge In Between Linked Lists](./1669-merge-in-between-linked-lists.js)|Medium| From fc51da9f06f832016c416e17b507ccf59e594631 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 20 Jan 2022 23:53:08 -0600 Subject: [PATCH 277/919] Add solution #143 --- 0143-reorder-list.js | 57 ++++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 58 insertions(+) create mode 100644 0143-reorder-list.js diff --git a/0143-reorder-list.js b/0143-reorder-list.js new file mode 100644 index 00000000..e1739ce2 --- /dev/null +++ b/0143-reorder-list.js @@ -0,0 +1,57 @@ +/** + * 143. Reorder List + * https://leetcode.com/problems/reorder-list/ + * Difficulty: Medium + * + * You are given the head of a singly linked-list. The list can be represented as: + * + * L0 → L1 → … → Ln - 1 → Ln + * Reorder the list to be on the following form: + * + * L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → … + * You may not modify the values in the list's nodes. Only nodes themselves may be changed. + */ + +/** + * 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 {void} Do not return anything, modify head in-place instead. + */ +var reorderList = function(head) { + if (!head || !head.next || !head.next.next) { + return head; + } + + let list1 = head; + let list2 = head; + + while (list2.next && list2.next.next) { + list1 = list1.next; + list2 = list2.next.next; + } + + let center1 = list1; + let center2 = list1.next; + while (center2.next) { + const temp = center2.next; + center2.next = temp.next; + temp.next = center1.next; + center1.next = temp; + } + + list1 = head; + list2 = center1.next; + while (list1 != center1) { + center1.next = list2.next; + list2.next = list1.next; + list1.next = list2; + list1 = list2.next; + list2 = center1.next; + } +}; diff --git a/README.md b/README.md index 1ad97805..727be0b7 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,7 @@ 136|[Single Number](./0136-single-number.js)|Easy| 141|[Linked List Cycle](./0141-linked-list-cycle.js)|Easy| 142|[Linked List Cycle II](./0142-linked-list-cycle-ii.js)|Medium| +143|[Reorder List](./0143-reorder-list.js)|Medium| 144|[Binary Tree Preorder Traversal](./0144-binary-tree-preorder-traversal.js)|Easy| 145|[Binary Tree Postorder Traversal](./0145-binary-tree-postorder-traversal.js)|Easy| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| From 7a6694e488b0e6c7b00eae54ed4ab2409485fa7c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 20 Jan 2022 23:54:02 -0600 Subject: [PATCH 278/919] Add solution #1342 --- ...ber-of-steps-to-reduce-a-number-to-zero.js | 22 +++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 1342-number-of-steps-to-reduce-a-number-to-zero.js diff --git a/1342-number-of-steps-to-reduce-a-number-to-zero.js b/1342-number-of-steps-to-reduce-a-number-to-zero.js new file mode 100644 index 00000000..1b46d186 --- /dev/null +++ b/1342-number-of-steps-to-reduce-a-number-to-zero.js @@ -0,0 +1,22 @@ +/** + * 1342. Number of Steps to Reduce a Number to Zero + * https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/ + * Difficulty: Easy + * + * Given an integer num, return the number of steps to reduce it to zero. + * + * In one step, if the current number is even, you have to divide it by 2, + * otherwise, you have to subtract 1 from it. + */ + +/** + * @param {number} num + * @return {number} + */ +var numberOfSteps = function(num) { + let steps = 0; + while (num > 0 && ++steps) { + num = num % 2 === 0 ? num / 2 : num -1; + } + return steps; +}; diff --git a/README.md b/README.md index 727be0b7..e9c31fd7 100644 --- a/README.md +++ b/README.md @@ -210,6 +210,7 @@ 1324|[Print Words Vertically](./1324-print-words-vertically.js)|Medium| 1332|[Remove Palindromic Subsequences](./1332-remove-palindromic-subsequences.js)|Easy| 1333|[Filter Restaurants by Vegan-Friendly, Price and Distance](./1333-filter-restaurants-by-vegan-friendly-price-and-distance.js)|Medium| +1342|[Number of Steps to Reduce a Number to Zero](./1342-number-of-steps-to-reduce-a-number-to-zero.js)|Easy| 1351|[Count Negative Numbers in a Sorted Matrix](./1351-count-negative-numbers-in-a-sorted-matrix.js)|Easy| 1356|[Sort Integers by The Number of 1 Bits](./1356-sort-integers-by-the-number-of-1-bits.js)|Easy| 1360|[Number of Days Between Two Dates](./1360-number-of-days-between-two-dates.js)|Easy| From 3f91703206e47a8d5fcd93d6b68bd262b13e93be Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 21 Jan 2022 00:00:12 -0600 Subject: [PATCH 279/919] Add solution #1716 --- 1716-calculate-money-in-leetcode-bank.js | 26 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 27 insertions(+) create mode 100644 1716-calculate-money-in-leetcode-bank.js diff --git a/1716-calculate-money-in-leetcode-bank.js b/1716-calculate-money-in-leetcode-bank.js new file mode 100644 index 00000000..fc184df4 --- /dev/null +++ b/1716-calculate-money-in-leetcode-bank.js @@ -0,0 +1,26 @@ +/** + * 1716. Calculate Money in Leetcode Bank + * https://leetcode.com/problems/calculate-money-in-leetcode-bank/ + * Difficulty: Easy + * + * Hercy wants to save money for his first car. He puts money in the Leetcode bank every day. + * + * He starts by putting in $1 on Monday, the first day. Every day from Tuesday to Sunday, he will + * put in $1 more than the day before. On every subsequent Monday, he will put in $1 more than the + * previous Monday. Given n, return the total amount of money he will have in the Leetcode bank at + * the end of the nth day. + */ + +/** + * @param {number} n + * @return {number} + */ +var totalMoney = function(n) { + let mondayCount = Math.floor(n / 7); + let aggregate = (mondayCount ** 2 + 7 * mondayCount) / 2; + let result = aggregate * 7; + for (let i = 0; i < n - mondayCount * 7; i++) { + result += mondayCount + i + 1; + } + return result; +}; diff --git a/README.md b/README.md index e9c31fd7..3fc65544 100644 --- a/README.md +++ b/README.md @@ -254,6 +254,7 @@ 1668|[Maximum Repeating Substring](./1668-maximum-repeating-substring.js)|Easy| 1669|[Merge In Between Linked Lists](./1669-merge-in-between-linked-lists.js)|Medium| 1672|[Richest Customer Wealth](./1672-richest-customer-wealth.js)|Easy| +1716|[Calculate Money in Leetcode Bank](./1716-calculate-money-in-leetcode-bank.js)|Easy| 1748|[Sum of Unique Elements](./1748-sum-of-unique-elements.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| 1832|[Check if the Sentence Is Pangram](./1832-check-if-the-sentence-is-pangram.js)|Easy| From 9c3ed0b313bba3669628984f86149a054dd98a34 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 21 Jan 2022 22:13:40 -0600 Subject: [PATCH 280/919] Add solution #22 --- 0022-generate-parentheses.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/0022-generate-parentheses.js b/0022-generate-parentheses.js index d3264697..6c666c1e 100644 --- a/0022-generate-parentheses.js +++ b/0022-generate-parentheses.js @@ -18,7 +18,7 @@ var generateParenthesis = function(n) { }; function backtrack(result, str, open, close, max) { - if (str.length == max * 2){ + if (str.length === max * 2) { result.push(str); return; } From 8f0710f87eb6ea41afed36c5391380fe3b39eeb1 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 21 Jan 2022 23:53:32 -0600 Subject: [PATCH 281/919] Add solution #1791 --- 1791-find-center-of-star-graph.js | 28 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 29 insertions(+) create mode 100644 1791-find-center-of-star-graph.js diff --git a/1791-find-center-of-star-graph.js b/1791-find-center-of-star-graph.js new file mode 100644 index 00000000..04fb502a --- /dev/null +++ b/1791-find-center-of-star-graph.js @@ -0,0 +1,28 @@ +/** + * 1791. Find Center of Star Graph + * https://leetcode.com/problems/find-center-of-star-graph/ + * Difficulty: Easy + * + * There is an undirected star graph consisting of n nodes labeled from 1 to n. A star graph is a + * graph where there is one center node and exactly n - 1 edges that connect the center node with + * every other node. + * + * You are given a 2D integer array edges where each edges[i] = [ui, vi] indicates that there is an + * edge between the nodes ui and vi. Return the center of the given star graph. + */ + +/** + * @param {number[][]} edges + * @return {number} + */ +var findCenter = function(edges) { + const set = new Set(); + for (const edge of edges) { + for (const node of edge) { + if (set.has(node)) { + return node; + } + set.add(node); + } + } +}; diff --git a/README.md b/README.md index 3fc65544..28a7d8d7 100644 --- a/README.md +++ b/README.md @@ -257,6 +257,7 @@ 1716|[Calculate Money in Leetcode Bank](./1716-calculate-money-in-leetcode-bank.js)|Easy| 1748|[Sum of Unique Elements](./1748-sum-of-unique-elements.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| +1791|[Find Center of Star Graph](./1791-find-center-of-star-graph.js)|Easy| 1832|[Check if the Sentence Is Pangram](./1832-check-if-the-sentence-is-pangram.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| From 8c2f9ec25c58742d4bee46af6e722cd692faf1d6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 22 Jan 2022 23:57:52 -0600 Subject: [PATCH 282/919] Add solution #2099 --- ...quence-of-length-k-with-the-largest-sum.js | 36 +++++++++++++++++++ README.md | 1 + 2 files changed, 37 insertions(+) create mode 100644 2099-find-subsequence-of-length-k-with-the-largest-sum.js diff --git a/2099-find-subsequence-of-length-k-with-the-largest-sum.js b/2099-find-subsequence-of-length-k-with-the-largest-sum.js new file mode 100644 index 00000000..bb989697 --- /dev/null +++ b/2099-find-subsequence-of-length-k-with-the-largest-sum.js @@ -0,0 +1,36 @@ +/** + * 2099. Find Subsequence of Length K With the Largest Sum + * https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum/ + * Difficulty: Medium + * + * You are given an integer array nums and an integer k. You want to find a subsequence + * of nums of length k that has the largest sum. + * + * Return any such subsequence as an integer array of length k. + * + * A subsequence is an array that can be derived from another array by deleting some or + * no elements without changing the order of the remaining elements. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {number[]} + */ +var maxSubsequence = function(nums, k) { + const map = new Map(); + nums.slice() + .sort((a, b) => a - b) + .slice(-k) + .forEach(n => map.set(n, (map.get(n) || 0) + 1)); + + return nums.filter(n => { + const isInSubsequence = map.get(n); + + if (isInSubsequence) { + map.set(n, map.get(n) - 1); + } + + return isInSubsequence; + }); +}; diff --git a/README.md b/README.md index 28a7d8d7..aef3e643 100644 --- a/README.md +++ b/README.md @@ -272,6 +272,7 @@ 2053|[Kth Distinct String in an Array](./2053-kth-distinct-string-in-an-array.js)|Medium| 2085|[Count Common Words With One Occurrence](./2085-count-common-words-with-one-occurrence.js)|Easy| 2095|[Delete the Middle Node of a Linked List](./2095-delete-the-middle-node-of-a-linked-list.js)|Medium| +2099|[Find Subsequence of Length K With the Largest Sum](./2099-find-subsequence-of-length-k-with-the-largest-sum.js)|Medium| 2114|[Maximum Number of Words Found in Sentences](./2114-maximum-number-of-words-found-in-sentences.js)|Easy| ## License From 563927fb2df880ea9fdf8a32015b14a519fa3c4a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 23 Jan 2022 00:01:53 -0600 Subject: [PATCH 283/919] Add solution #215 --- 0215-kth-largest-element-in-an-array.js | 18 ++++++++++++++++++ README.md | 1 + 2 files changed, 19 insertions(+) create mode 100644 0215-kth-largest-element-in-an-array.js diff --git a/0215-kth-largest-element-in-an-array.js b/0215-kth-largest-element-in-an-array.js new file mode 100644 index 00000000..a41a489b --- /dev/null +++ b/0215-kth-largest-element-in-an-array.js @@ -0,0 +1,18 @@ +/** + * 215. Kth Largest Element in an Array + * https://leetcode.com/problems/kth-largest-element-in-an-array/ + * Difficulty: Medium + * + * Given an integer array nums and an integer k, return the kth largest element in the array. + * + * Note that it is the kth largest element in the sorted order, not the kth distinct element. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var findKthLargest = function(nums, k) { + return nums.sort((a, b) => a - b)[nums.length - k]; +}; diff --git a/README.md b/README.md index aef3e643..36b9687d 100644 --- a/README.md +++ b/README.md @@ -93,6 +93,7 @@ 206|[Reverse Linked List](./0206-reverse-linked-list.js)|Easy| 213|[House Robber II](./0213-house-robber-ii.js)|Medium| 214|[Shortest Palindrome](./0214-shortest-palindrome.js)|Hard| +215|[Kth Largest Element in an Array](./0215-kth-largest-element-in-an-array.js)|Medium| 217|[Contains Duplicate](./0217-contains-duplicate.js)|Easy| 219|[Contains Duplicate II](./0219-contains-duplicate-ii.js)|Easy| 225|[Implement Stack using Queues](./0225-implement-stack-using-queues.js)|Easy| From 4d63108dac14e439336c7f4fe7a0a32195b9ec1a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 23 Jan 2022 00:09:23 -0600 Subject: [PATCH 284/919] Add solution #414 --- 0414-third-maximum-number.js | 21 +++++++++++++++++++++ README.md | 1 + 2 files changed, 22 insertions(+) create mode 100644 0414-third-maximum-number.js diff --git a/0414-third-maximum-number.js b/0414-third-maximum-number.js new file mode 100644 index 00000000..816c3336 --- /dev/null +++ b/0414-third-maximum-number.js @@ -0,0 +1,21 @@ +/** + * 414. Third Maximum Number + * https://leetcode.com/problems/third-maximum-number/ + * Difficulty: Easy + * + * Given an integer array nums, return the third distinct maximum number in this array. + * If the third maximum does not exist, return the maximum number. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var thirdMax = function(nums) { + const sortedSet = [...new Set(nums)].sort((a, b) => a - b); + const thirdMax = sortedSet[sortedSet.length - 3]; + + return thirdMax !== undefined + ? thirdMax + : sortedSet[sortedSet.length - 1]; +}; diff --git a/README.md b/README.md index 36b9687d..fe2505b6 100644 --- a/README.md +++ b/README.md @@ -121,6 +121,7 @@ 374|[Guess Number Higher or Lower](./0374-guess-number-higher-or-lower.js)|Medium| 383|[Ransom Note](./0383-ransom-note.js)|Easy| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| +414|[Third Maximum Number](./0414-third-maximum-number.js)|Easy| 442|[Find All Duplicates in an Array](./0442-find-all-duplicates-in-an-array.js)|Medium| 448|[Find All Numbers Disappeared in an Array](./0448-find-all-numbers-disappeared-in-an-array.js)|Easy| 451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| From 0394fb2047c302645917ad6338a539658ff46617 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 23 Jan 2022 23:09:27 -0600 Subject: [PATCH 285/919] Add solution #204 --- 0204-count-primes.js | 25 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 26 insertions(+) create mode 100644 0204-count-primes.js diff --git a/0204-count-primes.js b/0204-count-primes.js new file mode 100644 index 00000000..681460c1 --- /dev/null +++ b/0204-count-primes.js @@ -0,0 +1,25 @@ +/** + * 204. Count Primes + * https://leetcode.com/problems/count-primes/ + * Difficulty: Medium + * + * Given an integer n, return the number of prime numbers that are strictly less than n. + */ + +/** + * @param {number} n + * @return {number} + */ +var countPrimes = function(n) { + const nonPrimes = []; + let result = 0; + for (let i = 2; i < n; i++) { + if (!nonPrimes[i]) { + result++; + for (let j = 2; i * j < n; j++) { + nonPrimes[i * j] = 1; + } + } + } + return result; +}; diff --git a/README.md b/README.md index fe2505b6..69cffdad 100644 --- a/README.md +++ b/README.md @@ -90,6 +90,7 @@ 191|[Number of 1 Bits](./0191-number-of-1-bits.js)|Easy| 198|[House Robber](./0198-house-robber.js)|Medium| 203|[Remove Linked List Elements](./0203-remove-linked-list-elements.js)|Easy| +204|[Count Primes](./0204-count-primes.js)|Medium| 206|[Reverse Linked List](./0206-reverse-linked-list.js)|Easy| 213|[House Robber II](./0213-house-robber-ii.js)|Medium| 214|[Shortest Palindrome](./0214-shortest-palindrome.js)|Hard| From 942b6730e1799cb755568bbbe3b68629438eeea5 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 23 Jan 2022 23:14:08 -0600 Subject: [PATCH 286/919] Add solution #520 --- 0520-detect-capital.js | 21 +++++++++++++++++++++ README.md | 1 + 2 files changed, 22 insertions(+) create mode 100644 0520-detect-capital.js diff --git a/0520-detect-capital.js b/0520-detect-capital.js new file mode 100644 index 00000000..639780b8 --- /dev/null +++ b/0520-detect-capital.js @@ -0,0 +1,21 @@ +/** + * 520. Detect Capital + * https://leetcode.com/problems/detect-capital/ + * Difficulty: Easy + * + * We define the usage of capitals in a word to be right when one of the following + * cases holds: + * - All letters in this word are capitals, like "USA". + * - All letters in this word are not capitals, like "leetcode". + * - Only the first letter in this word is capital, like "Google". + * + * Given a string word, return true if the usage of capitals in it is right. + */ + +/** + * @param {string} word + * @return {boolean} + */ +var detectCapitalUse = function(word) { + return /^[A-Z]?[a-z]+$|^[A-Z]+$/.test(word); +}; diff --git a/README.md b/README.md index 69cffdad..36325adf 100644 --- a/README.md +++ b/README.md @@ -131,6 +131,7 @@ 476|[Number Complement](./0476-number-complement.js)|Easy| 500|[Keyboard Row](./0500-keyboard-row.js)|Easy| 506|[Relative Ranks](./0506-relative-ranks.js)|Easy| +520|[Detect Capital](./0520-detect-capital.js)|Easy| 541|[Reverse String II](./0541-reverse-string-ii.js)|Easy| 542|[01 Matrix](./0542-01-matrix.js)|Medium| 551|[Student Attendance Record I](./0551-student-attendance-record-i.js)|Easy| From 83440f4a982d5730de051b5e81455696b928e2d3 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 24 Jan 2022 23:48:10 -0600 Subject: [PATCH 287/919] Add solution #18 --- 0018-4sum.js | 59 ++++++++++++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 60 insertions(+) create mode 100644 0018-4sum.js diff --git a/0018-4sum.js b/0018-4sum.js new file mode 100644 index 00000000..ab1a8592 --- /dev/null +++ b/0018-4sum.js @@ -0,0 +1,59 @@ +/** + * 18. 4Sum + * https://leetcode.com/problems/4sum/ + * Difficulty: Medium + * + * Given an array nums of n integers, return an array of all the unique + * quadruplets [nums[a], nums[b], nums[c], nums[d]] such that: + * - 0 <= a, b, c, d < n + * - a, b, c, and d are distinct. + * - nums[a] + nums[b] + nums[c] + nums[d] == target + * + * You may return the answer in any order. + */ + +/** + * @param {number[]} nums + * @param {number} target + * @return {number[][]} + */ +var fourSum = function(nums, target) { + const result = []; + + nums.sort((a, b) => a - b); + + for (let i = 0; i < nums.length - 3; i++) { + for (let j = i + 1; j < nums.length - 2; j++) { + let high = nums.length - 1; + let low = j + 1; + + while (low < high) { + const sum = nums[i] + nums[j] + nums[low] + nums[high]; + + if (sum === target) { + result.push([nums[i], nums[j], nums[low], nums[high]]); + while (nums[low] === nums[low + 1]) { + low++; + } + while (nums[high] === nums[high - 1]) { + high--; + } + low++; + high--; + } else if (sum < target) { + low++; + } else { + high--; + } + } + while (nums[j] === nums[j + 1]) { + j++; + } + } + while (nums[i] === nums[i + 1]) { + i++; + } + } + + return result; +}; diff --git a/README.md b/README.md index 36325adf..d29098d2 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ 15|[3Sum](./0015-3sum.js)|Medium| 16|[3Sum Closest](./0016-3sum-closest.js)|Medium| 17|[Letter Combinations of a Phone Number](./0017-letter-combinations-of-a-phone-number.js)|Medium| +18|[4Sum](./0018-4sum.js)|Medium| 19|[Remove Nth Node From End of List](./0019-remove-nth-node-from-end-of-list.js)|Medium| 20|[Valid Parentheses](./0020-valid-parentheses.js)|Easy| 21|[Merge Two Sorted Lists](./0021-merge-two-sorted-lists.js)|Easy| From 47908370043c163b88715a2045c2b6859e7528de Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 24 Jan 2022 23:56:12 -0600 Subject: [PATCH 288/919] Add solution #2129 --- 2129-capitalize-the-title.js | 22 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 2129-capitalize-the-title.js diff --git a/2129-capitalize-the-title.js b/2129-capitalize-the-title.js new file mode 100644 index 00000000..8a9760f4 --- /dev/null +++ b/2129-capitalize-the-title.js @@ -0,0 +1,22 @@ +/** + * 2129. Capitalize the Title + * https://leetcode.com/problems/capitalize-the-title/ + * Difficulty: Easy + * + * You are given a string title consisting of one or more words separated by a single space, + * where each word consists of English letters. Capitalize the string by changing the + * capitalization of each word such that: + * - If the length of the word is 1 or 2 letters, change all letters to lowercase. + * - Otherwise, change the first letter to uppercase and the remaining letters to lowercase. + * Return the capitalized title. + */ + +/** + * @param {string} title + * @return {string} + */ +var capitalizeTitle = function(title) { + return title.split(/\s+/).map(word => { + return word.toLowerCase().replace(/^\w/, l => word.length > 2 ? l.toUpperCase() : l); + }).join(' '); +}; diff --git a/README.md b/README.md index d29098d2..41f01a05 100644 --- a/README.md +++ b/README.md @@ -279,6 +279,7 @@ 2095|[Delete the Middle Node of a Linked List](./2095-delete-the-middle-node-of-a-linked-list.js)|Medium| 2099|[Find Subsequence of Length K With the Largest Sum](./2099-find-subsequence-of-length-k-with-the-largest-sum.js)|Medium| 2114|[Maximum Number of Words Found in Sentences](./2114-maximum-number-of-words-found-in-sentences.js)|Easy| +2129|[Capitalize the Title](./2129-capitalize-the-title.js)|Easy| ## License From 15e6f2a73e6d3ad858c3caaab967b8a28c5af69e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 1 Jan 2023 17:06:40 -0600 Subject: [PATCH 289/919] Add solution #290 --- 0290-word-pattern.js | 29 +++++++++++++++++++++++++++++ README.md | 3 ++- 2 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 0290-word-pattern.js diff --git a/0290-word-pattern.js b/0290-word-pattern.js new file mode 100644 index 00000000..293062d4 --- /dev/null +++ b/0290-word-pattern.js @@ -0,0 +1,29 @@ +/** + * 290. Word Pattern + * https://leetcode.com/problems/word-pattern/ + * Difficulty: Easy + * + * Given a pattern and a string s, find if s follows the same pattern. + * + * Here follow means a full match, such that there is a bijection between + * a letter in pattern and a non-empty word in s. + */ + +/** + * @param {string} pattern + * @param {string} s + * @return {boolean} + */ +var wordPattern = function(pattern, s) { + const words = s.split(/\s+/); + const map = new Map(); + + return words.every((word, index) => { + const offset = pattern.length === words.length ? index + 1 : words.length / pattern.length; + const sequence = pattern.slice(index, offset); + if (!map.has(sequence) && !Array.from(map.values()).includes(word)) { + map.set(sequence, word); + } + return map.get(sequence) === word && pattern.length <= words.length; + }); +}; diff --git a/README.md b/README.md index 41f01a05..94f18d5b 100644 --- a/README.md +++ b/README.md @@ -113,6 +113,7 @@ 273|[Integer to English Words](./0273-integer-to-english-words.js)|Hard| 278|[First Bad Version](./0278-first-bad-version.js)|Medium| 283|[Move Zeroes](./0283-move-zeroes.js)|Easy| +290|[Word Pattern](./0290-word-pattern.js)|Easy| 326|[Power of Three](./0326-power-of-three.js)|Easy| 342|[Power of Four](./0342-power-of-four.js)|Easy| 344|[Reverse String](./0344-reverse-string.js)|Easy| @@ -285,4 +286,4 @@ [MIT License](https://opensource.org/licenses/MIT) -Copyright (c) 2019-2022 [Josh Crozier](https://joshcrozier.com) +Copyright (c) 2019-2023 [Josh Crozier](https://joshcrozier.com) From a488d646528307cb2e3290f1ed5ba2f048436623 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 1 Jan 2023 17:14:52 -0600 Subject: [PATCH 290/919] Add solution #2427 --- 2427-number-of-common-factors.js | 22 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 2427-number-of-common-factors.js diff --git a/2427-number-of-common-factors.js b/2427-number-of-common-factors.js new file mode 100644 index 00000000..03ba1993 --- /dev/null +++ b/2427-number-of-common-factors.js @@ -0,0 +1,22 @@ +/** + * 2427. Number of Common Factors + * https://leetcode.com/problems/number-of-common-factors/ + * Difficulty: Easy + * + * Given two positive integers a and b, return the number of common factors of a and b. + * + * An integer x is a common factor of a and b if x divides both a and b. + */ + +/** + * @param {number} a + * @param {number} b + * @return {number} + */ +var commonFactors = function(a, b) { + let count = 0; + for (let i = Math.min(a, b); i > 0; i--) { + if (a % i === 0 && b % i === 0) count++; + } + return count; +}; diff --git a/README.md b/README.md index 94f18d5b..07aea69e 100644 --- a/README.md +++ b/README.md @@ -281,6 +281,7 @@ 2099|[Find Subsequence of Length K With the Largest Sum](./2099-find-subsequence-of-length-k-with-the-largest-sum.js)|Medium| 2114|[Maximum Number of Words Found in Sentences](./2114-maximum-number-of-words-found-in-sentences.js)|Easy| 2129|[Capitalize the Title](./2129-capitalize-the-title.js)|Easy| +2427|[Number of Common Factors](./2427-number-of-common-factors.js)|Easy| ## License From b39c80d7e03b5689677ee5f0d2dc4bead39b9e7b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 1 Jan 2023 17:36:55 -0600 Subject: [PATCH 291/919] Add solution #1812 --- ...-determine-color-of-a-chessboard-square.js | 22 +++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 1812-determine-color-of-a-chessboard-square.js diff --git a/1812-determine-color-of-a-chessboard-square.js b/1812-determine-color-of-a-chessboard-square.js new file mode 100644 index 00000000..ca7bb3dd --- /dev/null +++ b/1812-determine-color-of-a-chessboard-square.js @@ -0,0 +1,22 @@ +/** + * 1812. Determine Color of a Chessboard Square + * https://leetcode.com/problems/determine-color-of-a-chessboard-square/ + * Difficulty: Easy + * + * You are given coordinates, a string that represents the coordinates of a square of + * the chessboard. Below is a chessboard for your reference. + * + * Return true if the square is white, and false if the square is black. + * + * The coordinate will always represent a valid chessboard square. The coordinate will + * always have the letter first, and the number second. + */ + +/** + * @param {string} coordinates + * @return {boolean} + */ +var squareIsWhite = function(coordinates) { + const [x, y] = coordinates; + return (x.charCodeAt() + +y) % 2 !== 0; +}; diff --git a/README.md b/README.md index 07aea69e..ab1585b3 100644 --- a/README.md +++ b/README.md @@ -264,6 +264,7 @@ 1748|[Sum of Unique Elements](./1748-sum-of-unique-elements.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| 1791|[Find Center of Star Graph](./1791-find-center-of-star-graph.js)|Easy| +1812|[Determine Color of a Chessboard Square](./1812-determine-color-of-a-chessboard-square.js)|Easy| 1832|[Check if the Sentence Is Pangram](./1832-check-if-the-sentence-is-pangram.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| From 3b2f1f734ce413cf1dd2de1a3979e2285c92f552 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 2 Jan 2023 17:15:49 -0600 Subject: [PATCH 292/919] Add solution #316 --- 0316-remove-duplicate-letters.js | 29 +++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 30 insertions(+) create mode 100644 0316-remove-duplicate-letters.js diff --git a/0316-remove-duplicate-letters.js b/0316-remove-duplicate-letters.js new file mode 100644 index 00000000..f33d96e6 --- /dev/null +++ b/0316-remove-duplicate-letters.js @@ -0,0 +1,29 @@ +/** + * 316. Remove Duplicate Letters + * https://leetcode.com/problems/remove-duplicate-letters/ + * Difficulty: Medium + * + * Given a string s, remove duplicate letters so that every letter appears once and only once. You must make sure your result is + * the smallest in lexicographical order among all possible results. + */ + +/** + * @param {string} s + * @return {string} + */ +var removeDuplicateLetters = function(s) { + const stack = []; + + for (let i = 0; i < s.length; i++) { + const letter = s[i]; + if (stack.indexOf(letter) > -1) { + continue; + } + while (stack.length > 0 && stack[stack.length - 1] > letter && s.indexOf(stack[stack.length - 1], i) > i) { + stack.pop(); + } + stack.push(letter); + } + + return stack.join(''); +}; diff --git a/README.md b/README.md index ab1585b3..b581bf0d 100644 --- a/README.md +++ b/README.md @@ -114,6 +114,7 @@ 278|[First Bad Version](./0278-first-bad-version.js)|Medium| 283|[Move Zeroes](./0283-move-zeroes.js)|Easy| 290|[Word Pattern](./0290-word-pattern.js)|Easy| +316|[Remove Duplicate Letters](./0316-remove-duplicate-letters.js)|Medium| 326|[Power of Three](./0326-power-of-three.js)|Easy| 342|[Power of Four](./0342-power-of-four.js)|Easy| 344|[Reverse String](./0344-reverse-string.js)|Easy| From 30d77fb185ab60d8d3814ab630294c49866be72f Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 2 Jan 2023 17:17:27 -0600 Subject: [PATCH 293/919] Add solution #1081 --- ...lest-subsequence-of-distinct-characters.js | 29 +++++++++++++++++++ README.md | 1 + 2 files changed, 30 insertions(+) create mode 100644 1081-smallest-subsequence-of-distinct-characters.js diff --git a/1081-smallest-subsequence-of-distinct-characters.js b/1081-smallest-subsequence-of-distinct-characters.js new file mode 100644 index 00000000..9ecfe62d --- /dev/null +++ b/1081-smallest-subsequence-of-distinct-characters.js @@ -0,0 +1,29 @@ +/** + * 1081. Smallest Subsequence of Distinct Characters + * https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/ + * Difficulty: Medium + * + * Given a string s, return the lexicographically smallest subsequence + * of s that contains all the distinct characters of s exactly once. + */ + +/** + * @param {string} s + * @return {string} + */ +var smallestSubsequence = function(s) { + const stack = []; + + for (let i = 0; i < s.length; i++) { + const letter = s[i]; + if (stack.indexOf(letter) > -1) { + continue; + } + while (stack.length > 0 && stack[stack.length - 1] > letter && s.indexOf(stack[stack.length - 1], i) > i) { + stack.pop(); + } + stack.push(letter); + } + + return stack.join(''); +}; diff --git a/README.md b/README.md index b581bf0d..a642140e 100644 --- a/README.md +++ b/README.md @@ -193,6 +193,7 @@ 1022|[Sum of Root To Leaf Binary Numbers](./1022-sum-of-root-to-leaf-binary-numbers.js)|Easy| 1037|[Valid Boomerang](./1037-valid-boomerang.js)|Easy| 1041|[Robot Bounded In Circle](./1041-robot-bounded-in-circle.js)|Medium| +1081|[Smallest Subsequence of Distinct Characters](./1081-smallest-subsequence-of-distinct-characters.js)|Medium| 1103|[Distribute Candies to People](./1103-distribute-candies-to-people.js)|Easy| 1108|[Defanging an IP Address](./1108-defanging-an-ip-address.js)|Easy| 1189|[Maximum Number of Balloons](./1189-maximum-number-of-balloons.js)|Easy| From 4d67380ace68de3586e3535970f3791bd0397439 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 2 Jan 2023 17:25:24 -0600 Subject: [PATCH 294/919] Add solution #2027 --- 2027-minimum-moves-to-convert-string.js | 21 +++++++++++++++++++++ README.md | 1 + 2 files changed, 22 insertions(+) create mode 100644 2027-minimum-moves-to-convert-string.js diff --git a/2027-minimum-moves-to-convert-string.js b/2027-minimum-moves-to-convert-string.js new file mode 100644 index 00000000..cde8e1b1 --- /dev/null +++ b/2027-minimum-moves-to-convert-string.js @@ -0,0 +1,21 @@ +/** + * 2027. Minimum Moves to Convert String + * https://leetcode.com/problems/minimum-moves-to-convert-string/ + * Difficulty: Easy + * + * You are given a string s consisting of n characters which are either 'X' or 'O'. + * + * A move is defined as selecting three consecutive characters of s and converting them + * to 'O'. Note that if a move is applied to the character 'O', it will stay the same. + * + * Return the minimum number of moves required so that all the characters of s are + * converted ]to 'O'. + */ + +/** + * @param {string} s + * @return {number} + */ +var minimumMoves = function(s) { + return s.match(/X.{0,2}/g)?.length ?? 0; +}; diff --git a/README.md b/README.md index a642140e..a2f0fb80 100644 --- a/README.md +++ b/README.md @@ -277,6 +277,7 @@ 2000|[Reverse Prefix of Word](./2000-reverse-prefix-of-word.js)|Easy| 2011|[Final Value of Variable After Performing Operations](./2011-final-value-of-variable-after-performing-operations.js)|Easy| 2016|[Maximum Difference Between Increasing Elements](./2016-maximum-difference-between-increasing-elements.js)|Easy| +2027|[Minimum Moves to Convert String](./2027-minimum-moves-to-convert-string.js)|Easy| 2047|[Number of Valid Words in a Sentence](./2047-number-of-valid-words-in-a-sentence.js)|Easy| 2053|[Kth Distinct String in an Array](./2053-kth-distinct-string-in-an-array.js)|Medium| 2085|[Count Common Words With One Occurrence](./2085-count-common-words-with-one-occurrence.js)|Easy| From 672f4100ba6e4463e0faa08215c1f78715674fc2 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 3 Jan 2023 19:18:40 -0600 Subject: [PATCH 295/919] Add solution #2244 --- 2244-minimum-rounds-to-complete-all-tasks.js | 31 ++++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 2244-minimum-rounds-to-complete-all-tasks.js diff --git a/2244-minimum-rounds-to-complete-all-tasks.js b/2244-minimum-rounds-to-complete-all-tasks.js new file mode 100644 index 00000000..9aa85e1f --- /dev/null +++ b/2244-minimum-rounds-to-complete-all-tasks.js @@ -0,0 +1,31 @@ +/** + * 2244. Minimum Rounds to Complete All Tasks + * https://leetcode.com/problems/minimum-rounds-to-complete-all-tasks/ + * Difficulty: Medium + * + * You are given a 0-indexed integer array tasks, where tasks[i] represents the difficulty level + * of a task. In each round, you can complete either 2 or 3 tasks of the same difficulty level. + * + * Return the minimum rounds required to complete all the tasks, or -1 if it is not possible to + * complete all the tasks. + */ + +/** + * @param {number[]} tasks + * @return {number} + */ +var minimumRounds = function(tasks) { + const map = new Map(); + let result = 0; + + tasks.forEach(task => map.set(task, map.has(task) ? map.get(task) + 1 : 1)); + + for (const count of map.values()) { + if (count < 2) { + return -1; + } + result += Math.floor(count / 3) + (count % 3 === 0 ? 0 : 1); + } + + return result; +}; diff --git a/README.md b/README.md index a2f0fb80..eb72c08f 100644 --- a/README.md +++ b/README.md @@ -285,6 +285,7 @@ 2099|[Find Subsequence of Length K With the Largest Sum](./2099-find-subsequence-of-length-k-with-the-largest-sum.js)|Medium| 2114|[Maximum Number of Words Found in Sentences](./2114-maximum-number-of-words-found-in-sentences.js)|Easy| 2129|[Capitalize the Title](./2129-capitalize-the-title.js)|Easy| +2244|[Minimum Rounds to Complete All Tasks](./2244-minimum-rounds-to-complete-all-tasks.js)|Medium| 2427|[Number of Common Factors](./2427-number-of-common-factors.js)|Easy| ## License From 86c1964141711ea46ebf7d10072e277ab668398e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 3 Jan 2023 19:25:37 -0600 Subject: [PATCH 296/919] Add solution #762 --- ...er-of-set-bits-in-binary-representation.js | 30 +++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 0762-prime-number-of-set-bits-in-binary-representation.js diff --git a/0762-prime-number-of-set-bits-in-binary-representation.js b/0762-prime-number-of-set-bits-in-binary-representation.js new file mode 100644 index 00000000..7b929382 --- /dev/null +++ b/0762-prime-number-of-set-bits-in-binary-representation.js @@ -0,0 +1,30 @@ +/** + * 762. Prime Number of Set Bits in Binary Representation + * https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation/ + * Difficulty: Easy + * + * Given two integers left and right, return the count of numbers in the inclusive range [left, right] having + * a prime number of set bits in their binary representation. + * + * Recall that the number of set bits an integer has is the number of 1's present when written in binary. + * + * For example, 21 written in binary is 10101, which has 3 set bits. + */ + +/** + * @param {number} left + * @param {number} right + * @return {number} + */ +var countPrimeSetBits = function(left, right) { + const primes = new Set([2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]); + let result = 0; + + for (let i = left; i <= right; i++) { + if (primes.has(i.toString(2).replace(/0+/g, '').length)) { + result++; + } + } + + return result; +}; diff --git a/README.md b/README.md index eb72c08f..9df21fc5 100644 --- a/README.md +++ b/README.md @@ -160,6 +160,7 @@ 722|[Remove Comments](./0722-remove-comments.js)|Medium| 733|[Flood Fill](./0733-flood-fill.js)|Easy| 739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium| +762|[Prime Number of Set Bits in Binary Representation](./0762-prime-number-of-set-bits-in-binary-representation.js)|Easy| 784|[Letter Case Permutation](./0784-letter-case-permutation.js)|Medium| 791|[Custom Sort String](./0791-custom-sort-string.js)|Medium| 796|[Rotate String](./0796-rotate-string.js)|Easy| From 922bd2a5841b222f29acc57937acf980e0b520ca Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 3 Jan 2023 19:44:44 -0600 Subject: [PATCH 297/919] Add solution #746 --- 0746-min-cost-climbing-stairs.js | 28 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 29 insertions(+) create mode 100644 0746-min-cost-climbing-stairs.js diff --git a/0746-min-cost-climbing-stairs.js b/0746-min-cost-climbing-stairs.js new file mode 100644 index 00000000..65b22d5d --- /dev/null +++ b/0746-min-cost-climbing-stairs.js @@ -0,0 +1,28 @@ +/** + * 746. Min Cost Climbing Stairs + * https://leetcode.com/problems/min-cost-climbing-stairs/ + * Difficulty: Easy + * + * You are given an integer array cost where cost[i] is the cost of ith step on a staircase. + * Once you pay the cost, you can either climb one or two steps. + * + * You can either start from the step with index 0, or the step with index 1. + * + * Return the minimum cost to reach the top of the floor. + */ + +/** + * @param {number[]} cost + * @return {number} + */ +var minCostClimbingStairs = function(cost) { + let [first, second] = cost; + + for (let index = 2; index < cost.length; index++) { + const cursor = cost[index] + Math.min(first, second); + first = second; + second = cursor; + } + + return Math.min(first, second); +}; diff --git a/README.md b/README.md index 9df21fc5..a8369120 100644 --- a/README.md +++ b/README.md @@ -160,6 +160,7 @@ 722|[Remove Comments](./0722-remove-comments.js)|Medium| 733|[Flood Fill](./0733-flood-fill.js)|Easy| 739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium| +746|[Min Cost Climbing Stairs](./0746-min-cost-climbing-stairs.js)|Easy| 762|[Prime Number of Set Bits in Binary Representation](./0762-prime-number-of-set-bits-in-binary-representation.js)|Easy| 784|[Letter Case Permutation](./0784-letter-case-permutation.js)|Medium| 791|[Custom Sort String](./0791-custom-sort-string.js)|Medium| From dc44d7e2087a4afb39fc0e399fe31715ce512549 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 4 Jan 2023 17:34:51 -0600 Subject: [PATCH 298/919] Add solution #747 --- ...largest-number-at-least-twice-of-others.js | 20 +++++++++++++++++++ README.md | 1 + 2 files changed, 21 insertions(+) create mode 100644 0747-largest-number-at-least-twice-of-others.js diff --git a/0747-largest-number-at-least-twice-of-others.js b/0747-largest-number-at-least-twice-of-others.js new file mode 100644 index 00000000..9a0f6feb --- /dev/null +++ b/0747-largest-number-at-least-twice-of-others.js @@ -0,0 +1,20 @@ +/** + * 747. Largest Number At Least Twice of Others + * https://leetcode.com/problems/largest-number-at-least-twice-of-others/ + * Difficulty: Easy + * + * You are given an integer array nums where the largest integer is unique. + * + * Determine whether the largest element in the array is at least twice as much + * as every other number in the array. If it is, return the index of the largest + * element, or return -1 otherwise. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var dominantIndex = function(nums) { + const max = Math.max(...nums); + return nums.find(n => n !== max && n > max / 2) ? -1 : nums.indexOf(max); +}; diff --git a/README.md b/README.md index a8369120..7d1afeac 100644 --- a/README.md +++ b/README.md @@ -161,6 +161,7 @@ 733|[Flood Fill](./0733-flood-fill.js)|Easy| 739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium| 746|[Min Cost Climbing Stairs](./0746-min-cost-climbing-stairs.js)|Easy| +747|[Largest Number At Least Twice of Others](./0747-largest-number-at-least-twice-of-others.js)|Easy| 762|[Prime Number of Set Bits in Binary Representation](./0762-prime-number-of-set-bits-in-binary-representation.js)|Easy| 784|[Letter Case Permutation](./0784-letter-case-permutation.js)|Medium| 791|[Custom Sort String](./0791-custom-sort-string.js)|Medium| From be50f60cba89f94a51bca8831827bfd7fc33e7c1 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 4 Jan 2023 18:07:09 -0600 Subject: [PATCH 299/919] Add solution #38 --- 0038-count-and-say.js | 35 +++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 36 insertions(+) create mode 100644 0038-count-and-say.js diff --git a/0038-count-and-say.js b/0038-count-and-say.js new file mode 100644 index 00000000..cca4fe01 --- /dev/null +++ b/0038-count-and-say.js @@ -0,0 +1,35 @@ +/** + * 38. Count and Say + * https://leetcode.com/problems/count-and-say/ + * Difficulty: Medium + * + * The count-and-say sequence is a sequence of digit strings defined by the recursive formula: + * - countAndSay(1) = "1" + * - countAndSay(n) is the way you would "say" the digit string from countAndSay(n-1), which is + * then converted into a different digit string. + * + * To determine how you "say" a digit string, split it into the minimal number of substrings such + * that each substring contains exactly one unique digit. Then for each substring, say the number + * of digits, then say the digit. Finally, concatenate every said digit. + * + * For example, the saying and conversion for digit string "3322251": + * Given a positive integer n, return the nth term of the count-and-say sequence. + */ + +/** + * @param {number} n + * @return {string} + */ +var countAndSay = function(n) { + let result = '1'; + + for (let i = 1; i < n; i++) { + result = result.replace(/((\d)\2*)/g, '$1—') + .split('—') + .map(s => s ? `${s.length}${s[0]}` : '') + .join(''); + } + + return result; +}; + diff --git a/README.md b/README.md index 7d1afeac..23ebcb9c 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,7 @@ 34|[Find First and Last Position of Element in Sorted Array](./0034-find-first-and-last-position-of-element-in-sorted-array.js)|Medium| 35|[Search Insert Position](./0035-search-insert-position.js)|Easy| 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| +38|[Count and Say](./0038-count-and-say.js)|Medium| 39|[Combination Sum](./0039-combination-sum.js)|Medium| 40|[Combination Sum II](./0040-combination-sum-ii.js)|Medium| 41|[First Missing Positive](./0041-first-missing-positive.js)|Hard| From ca9359080c8f9a86e4194f4ef5d376ca23366e26 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 4 Jan 2023 18:16:46 -0600 Subject: [PATCH 300/919] Add solution #2154 --- 2154-keep-multiplying-found-values-by-two.js | 25 ++++++++++++++++++++ README.md | 1 + 2 files changed, 26 insertions(+) create mode 100644 2154-keep-multiplying-found-values-by-two.js diff --git a/2154-keep-multiplying-found-values-by-two.js b/2154-keep-multiplying-found-values-by-two.js new file mode 100644 index 00000000..bdf79461 --- /dev/null +++ b/2154-keep-multiplying-found-values-by-two.js @@ -0,0 +1,25 @@ +/** + * 2154. Keep Multiplying Found Values by Two + * https://leetcode.com/problems/keep-multiplying-found-values-by-two/ + * Difficulty: Easy + * + * You are given an array of integers nums. You are also given an integer original which + * is the first number that needs to be searched for in nums. + * + * You then do the following steps: + * If original is found in nums, multiply it by two (i.e., set original = 2 * original). + * Otherwise, stop the process. + * Repeat this process with the new number as long as you keep finding the number. + * Return the final value of original. + */ + +/** + * @param {number[]} nums + * @param {number} original + * @return {number} + */ +var findFinalValue = function(nums, original) { + return nums + .sort((a, b) => a - b) + .reduce((result, n) => result *= n === result ? 2 : 1, original); +}; diff --git a/README.md b/README.md index 23ebcb9c..69ea77a9 100644 --- a/README.md +++ b/README.md @@ -289,6 +289,7 @@ 2099|[Find Subsequence of Length K With the Largest Sum](./2099-find-subsequence-of-length-k-with-the-largest-sum.js)|Medium| 2114|[Maximum Number of Words Found in Sentences](./2114-maximum-number-of-words-found-in-sentences.js)|Easy| 2129|[Capitalize the Title](./2129-capitalize-the-title.js)|Easy| +2154|[Keep Multiplying Found Values by Two](./2154-keep-multiplying-found-values-by-two.js)|Easy| 2244|[Minimum Rounds to Complete All Tasks](./2244-minimum-rounds-to-complete-all-tasks.js)|Medium| 2427|[Number of Common Factors](./2427-number-of-common-factors.js)|Easy| From 78e9815d4164f1e1498f037f3344e076c6d0d616 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 5 Jan 2023 17:47:23 -0600 Subject: [PATCH 301/919] Add solution #78 --- 0078-subsets.js | 27 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 28 insertions(+) create mode 100644 0078-subsets.js diff --git a/0078-subsets.js b/0078-subsets.js new file mode 100644 index 00000000..d1e23dd7 --- /dev/null +++ b/0078-subsets.js @@ -0,0 +1,27 @@ +/** + * 78. Subsets + * https://leetcode.com/problems/subsets/ + * Difficulty: Medium + * + * Given an integer array nums of unique elements, return all possible subsets (the power set). + * + * The solution set must not contain duplicate subsets. Return the solution in any order. + */ + +/** + * @param {number[]} nums + * @return {number[][]} + */ +var subsets = function(nums) { + const result = []; + dfs([], 0); + + function dfs(subset, start) { + result.push(subset); + for (let index = start; index < nums.length; index++) { + dfs([...subset, nums[index]], index + 1); + } + } + + return result; +}; diff --git a/README.md b/README.md index 69ea77a9..d566f272 100644 --- a/README.md +++ b/README.md @@ -59,6 +59,7 @@ 73|[Set Matrix Zeroes](./0073-set-matrix-zeroes.js)|Medium| 74|[Search a 2D Matrix](./0074-search-a-2d-matrix.js)|Medium| 77|[Combinations](./0077-combinations.js)|Medium| +78|[Subsets](./0078-subsets.js)|Medium| 83|[Remove Duplicates from Sorted List](./0083-remove-duplicates-from-sorted-list.js)|Easy| 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| 94|[Binary Tree Inorder Traversal](./0094-binary-tree-inorder-traversal.js)|Easy| From 374d4ee473da399072db13dde0a9c0cef8862a0b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 5 Jan 2023 17:50:54 -0600 Subject: [PATCH 302/919] Add solution #452 --- ...imum-number-of-arrows-to-burst-balloons.js | 42 +++++++++++++++++++ README.md | 1 + 2 files changed, 43 insertions(+) create mode 100644 0452-minimum-number-of-arrows-to-burst-balloons.js diff --git a/0452-minimum-number-of-arrows-to-burst-balloons.js b/0452-minimum-number-of-arrows-to-burst-balloons.js new file mode 100644 index 00000000..ab5f6dfe --- /dev/null +++ b/0452-minimum-number-of-arrows-to-burst-balloons.js @@ -0,0 +1,42 @@ +/** + * 452. Minimum Number of Arrows to Burst Balloons + * https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/ + * Difficulty: Medium + * + * There are some spherical balloons taped onto a flat wall that represents the XY-plane. + * The balloons are represented as a 2D integer array points where points[i] = [xstart, xend] + * denotes a balloon whose horizontal diameter stretches between xstart and xend. You do not + * know the exact y-coordinates of the balloons. + * + * Arrows can be shot up directly vertically (in the positive y-direction) from different points + * along the x-axis. A balloon with xstart and xend is burst by an arrow shot at x if + * x(start) <= x <= x(end). There is no limit to the number of arrows that can be shot. A shot + * arrow keeps traveling up infinitely, bursting any balloons in its path. + * + * Given the array points, return the minimum number of arrows that must be shot to burst all + * balloons. + */ + +/** + * @param {number[][]} points + * @return {number} + */ +var findMinArrowShots = function(points) { + let result = 0; + let i = 0; + + points.sort(([a], [b]) => a - b); + + while (i < points.length) { + let [left, right] = points[i]; + i++; + while (i < points.length && points[i][0] <= right && points[i][1] >= left) { + left = Math.max(left, points[i][0]); + right = Math.min(right, points[i][1]); + i++; + } + result++; + } + + return result; +}; diff --git a/README.md b/README.md index d566f272..d8a1952c 100644 --- a/README.md +++ b/README.md @@ -131,6 +131,7 @@ 442|[Find All Duplicates in an Array](./0442-find-all-duplicates-in-an-array.js)|Medium| 448|[Find All Numbers Disappeared in an Array](./0448-find-all-numbers-disappeared-in-an-array.js)|Easy| 451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| +452|[Minimum Number of Arrows to Burst Balloons](./0452-minimum-number-of-arrows-to-burst-balloons.js)|Medium| 459|[Repeated Substring Pattern](./0459-repeated-substring-pattern.js)|Easy| 463|[Island Perimeter](./0463-island-perimeter.js)|Medium| 476|[Number Complement](./0476-number-complement.js)|Easy| From f5362f35720efd47263ea0eb3e96b0755f7689e6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 5 Jan 2023 17:52:50 -0600 Subject: [PATCH 303/919] Add solution #69 --- 0069-sqrtx.js | 24 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 0069-sqrtx.js diff --git a/0069-sqrtx.js b/0069-sqrtx.js new file mode 100644 index 00000000..cfd60912 --- /dev/null +++ b/0069-sqrtx.js @@ -0,0 +1,24 @@ +/** + * 69. Sqrt(x) + * https://leetcode.com/problems/sqrtx/ + * Difficulty: Medium + * + * Given a non-negative integer x, return the square root of x rounded down to the nearest + * integer. The returned integer should be non-negative as well. + * + * You must not use any built-in exponent function or operator. + */ + +/** + * @param {number} x + * @return {number} + */ +var mySqrt = function(x) { + let result = 1; + + while (result * result <= x) { + result++; + } + + return result - 1; +}; diff --git a/README.md b/README.md index d8a1952c..c1c10d46 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,7 @@ 58|[Length of Last Word](./0058-length-of-last-word.js)|Easy| 66|[Plus One](./0066-plus-one.js)|Easy| 67|[Add Binary](./0067-add-binary.js)|Easy| +69|[Sqrt(x)](./0069-sqrtx.js)|Medium| 70|[Climbing Stairs](./0070-climbing-stairs.js)|Easy| 73|[Set Matrix Zeroes](./0073-set-matrix-zeroes.js)|Medium| 74|[Search a 2D Matrix](./0074-search-a-2d-matrix.js)|Medium| From 984c931c00c87e6c76fcf20f9bfb36fcbbd9687f Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 6 Jan 2023 20:16:54 -0600 Subject: [PATCH 304/919] Add solution #134 --- 0134-gas-station.js | 34 ++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 0134-gas-station.js diff --git a/0134-gas-station.js b/0134-gas-station.js new file mode 100644 index 00000000..de7b5b6d --- /dev/null +++ b/0134-gas-station.js @@ -0,0 +1,34 @@ +/** + * 134. Gas Station + * https://leetcode.com/problems/gas-station/ + * Difficulty: Medium + * + * There are n gas stations along a circular route, where the amount of gas at the ith station is gas[i]. + * + * You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from the ith station to + * its next (i + 1)th station. You begin the journey with an empty tank at one of the gas stations. + * + * Given two integer arrays gas and cost, return the starting gas station's index if you can travel around + * the circuit once in the clockwise direction, otherwise return -1. If there exists a solution, it is + * guaranteed to be unique + */ + +/** + * @param {number[]} gas + * @param {number[]} cost + * @return {number} + */ +var canCompleteCircuit = function(gas, cost) { + let total = 0, tank = 0, index = 0; + + for (let i = 0; i < gas.length; i++) { + tank += gas[i] - cost[i]; + total += gas[i] - cost[i]; + if (tank < 0) { + tank = 0; + index = i + 1; + } + } + + return total >= 0 ? index : -1; +}; diff --git a/README.md b/README.md index c1c10d46..71c6c2f6 100644 --- a/README.md +++ b/README.md @@ -78,6 +78,7 @@ 121|[Best Time to Buy and Sell Stock](./0121-best-time-to-buy-and-sell-stock.js)|Easy| 128|[Longest Consecutive Sequence](./0128-longest-consecutive-sequence.js)|Medium| 133|[Clone Graph](./0133-clone-graph.js)|Medium| +134|[Gas Station](./0134-gas-station.js)|Medium| 136|[Single Number](./0136-single-number.js)|Easy| 141|[Linked List Cycle](./0141-linked-list-cycle.js)|Easy| 142|[Linked List Cycle II](./0142-linked-list-cycle-ii.js)|Medium| From 18a6904c2032772a32a1e48258909ee507430c02 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 6 Jan 2023 20:18:10 -0600 Subject: [PATCH 305/919] Add solution #90 --- 0090-subsets-ii.js | 32 ++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 0090-subsets-ii.js diff --git a/0090-subsets-ii.js b/0090-subsets-ii.js new file mode 100644 index 00000000..45e2dec0 --- /dev/null +++ b/0090-subsets-ii.js @@ -0,0 +1,32 @@ +/** + * 90. Subsets II + * https://leetcode.com/problems/subsets-ii/ + * Difficulty: Medium + * + * Given an integer array nums that may contain duplicates, return all possible subsets (the power set). + * + * The solution set must not contain duplicate subsets. Return the solution in any order. + */ + +/** + * @param {number[]} nums + * @return {number[][]} + */ +var subsetsWithDup = function(nums) { + const seen = new Set(); + const result = []; + dfs([], 0); + + function dfs(subset, start) { + const key = subset.sort((a, b) => a - b).join(''); + if (!seen.has(key)) { + result.push(subset); + seen.add(key); + } + for (let index = start; index < nums.length; index++) { + dfs([...subset, nums[index]], index + 1); + } + } + + return result; +}; diff --git a/README.md b/README.md index 71c6c2f6..41c7cd10 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,7 @@ 78|[Subsets](./0078-subsets.js)|Medium| 83|[Remove Duplicates from Sorted List](./0083-remove-duplicates-from-sorted-list.js)|Easy| 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| +90|[Subsets II](./0090-subsets-ii.js)|Medium| 94|[Binary Tree Inorder Traversal](./0094-binary-tree-inorder-traversal.js)|Easy| 98|[Validate Binary Search Tree](./0098-validate-binary-search-tree.js)|Medium| 100|[Same Tree](./0100-same-tree.js)|Easy| From c4bda1b83efbe5fe257b1aa82b114bf657cc65a1 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 6 Jan 2023 20:25:22 -0600 Subject: [PATCH 306/919] Add solution #367 --- 0367-valid-perfect-square.js | 30 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 0367-valid-perfect-square.js diff --git a/0367-valid-perfect-square.js b/0367-valid-perfect-square.js new file mode 100644 index 00000000..22e6f2a2 --- /dev/null +++ b/0367-valid-perfect-square.js @@ -0,0 +1,30 @@ +/** + * 367. Valid Perfect Square + * https://leetcode.com/problems/valid-perfect-square/ + * Difficulty: Easy + * + * Given a positive integer num, return true if num is a perfect square or false otherwise. + * + * A perfect square is an integer that is the square of an integer. In other words, it is the + * product of some integer with itself. + * + * You must not use any built-in library function, such as sqrt. + */ + +/** + * @param {number} num + * @return {boolean} + */ +var isPerfectSquare = function(num) { + let i = 1; + + while (num > 0) { + num -= i; + i += 2; + if (num === 0) { + return true; + } + } + + return false; +}; diff --git a/README.md b/README.md index 41c7cd10..0f27309c 100644 --- a/README.md +++ b/README.md @@ -127,6 +127,7 @@ 347|[Top K Frequent Elements](./0347-top-k-frequent-elements.js)|Medium| 349|[Intersection of Two Arrays](./0349-intersection-of-two-arrays.js)|Easy| 350|[Intersection of Two Arrays II](./0350-intersection-of-two-arrays-ii.js)|Easy| +367|[Valid Perfect Square](./0367-valid-perfect-square.js)|Easy| 374|[Guess Number Higher or Lower](./0374-guess-number-higher-or-lower.js)|Medium| 383|[Ransom Note](./0383-ransom-note.js)|Easy| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| From 6d748c2f39cbc4d62befc4eb1d2288e27d3c09ac Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 7 Jan 2023 17:06:50 -0600 Subject: [PATCH 307/919] Add solution #135 --- 0135-candy.js | 37 +++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 38 insertions(+) create mode 100644 0135-candy.js diff --git a/0135-candy.js b/0135-candy.js new file mode 100644 index 00000000..d9e373c0 --- /dev/null +++ b/0135-candy.js @@ -0,0 +1,37 @@ +/** + * 135. Candy + * https://leetcode.com/problems/candy/ + * Difficulty: Hard + * + * There are n children standing in a line. Each child is assigned a rating value given + * in the integer array ratings. + * + * You are giving candies to these children subjected to the following requirements: + * - Each child must have at least one candy. + * - Children with a higher rating get more candies than their neighbors. + * + * Return the minimum number of candies you need to have to distribute the candies to + * the children. + */ + +/** + * @param {number[]} ratings + * @return {number} + */ +var candy = function(ratings) { + const data = new Array(ratings.length).fill(1); + + for (let i = 1; i < ratings.length; i++) { + if (ratings[i - 1] < ratings[i]) { + data[i] = data[i - 1] + 1; + } + } + + for (let i = ratings.length - 1; i > 0; i--) { + if (ratings[i - 1] > ratings[i]) { + data[i - 1] = data[i - 1] > data[i] + 1 ? data[i - 1] : data[i] + 1; + } + } + + return data.reduce((sum, n) => sum + n, 0); +}; diff --git a/README.md b/README.md index 0f27309c..502adf81 100644 --- a/README.md +++ b/README.md @@ -80,6 +80,7 @@ 128|[Longest Consecutive Sequence](./0128-longest-consecutive-sequence.js)|Medium| 133|[Clone Graph](./0133-clone-graph.js)|Medium| 134|[Gas Station](./0134-gas-station.js)|Medium| +135|[Candy](./0135-candy.js)|Hard| 136|[Single Number](./0136-single-number.js)|Easy| 141|[Linked List Cycle](./0141-linked-list-cycle.js)|Easy| 142|[Linked List Cycle II](./0142-linked-list-cycle-ii.js)|Medium| From b2f838a6ead47852e6552b31f063638fd911566d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 7 Jan 2023 17:09:06 -0600 Subject: [PATCH 308/919] Add solution #2469 --- 2469-convert-the-temperature.js | 21 +++++++++++++++++++++ README.md | 1 + 2 files changed, 22 insertions(+) create mode 100644 2469-convert-the-temperature.js diff --git a/2469-convert-the-temperature.js b/2469-convert-the-temperature.js new file mode 100644 index 00000000..8e0c2f47 --- /dev/null +++ b/2469-convert-the-temperature.js @@ -0,0 +1,21 @@ +/** + * 2469. Convert the Temperature + * https://leetcode.com/problems/convert-the-temperature/ + * Difficulty: Easy + * + * You are given a non-negative floating point number rounded to two decimal places celsius, + * that denotes the temperature in Celsius. + * + * You should convert Celsius into Kelvin and Fahrenheit and return it as an array + * ans = [kelvin, fahrenheit]. + * + * Return the array ans. Answers within 10-5 of the actual answer will be accepted. + */ + +/** + * @param {number} celsius + * @return {number[]} + */ +var convertTemperature = function(celsius) { + return [celsius + 273.15, celsius * 1.80 + 32]; +}; diff --git a/README.md b/README.md index 502adf81..1972c5a3 100644 --- a/README.md +++ b/README.md @@ -299,6 +299,7 @@ 2154|[Keep Multiplying Found Values by Two](./2154-keep-multiplying-found-values-by-two.js)|Easy| 2244|[Minimum Rounds to Complete All Tasks](./2244-minimum-rounds-to-complete-all-tasks.js)|Medium| 2427|[Number of Common Factors](./2427-number-of-common-factors.js)|Easy| +2469|[Convert the Temperature](./2469-convert-the-temperature.js)|Easy| ## License From 19fa98ebd4ca7db1606399788883e0b94a41f5f9 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 7 Jan 2023 17:10:33 -0600 Subject: [PATCH 309/919] Add solution #137 --- 0137-single-number-ii.js | 26 ++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 27 insertions(+) create mode 100644 0137-single-number-ii.js diff --git a/0137-single-number-ii.js b/0137-single-number-ii.js new file mode 100644 index 00000000..4031d398 --- /dev/null +++ b/0137-single-number-ii.js @@ -0,0 +1,26 @@ +/** + * 137. Single Number II + * https://leetcode.com/problems/single-number-ii/ + * Difficulty: Medium + * + * Given an integer array nums where every element appears three times except for one, which appears + * exactly once. Find the single element and return it. + * + * You must implement a solution with a linear runtime complexity and use only constant extra space. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var singleNumber = function(nums) { + let a = 0, b = 0; + + nums.forEach(c => { + const offset = (~a & b & c) | (a & ~b & ~c); + b = (~a & ~b & c) | (~a & b & ~c); + a = offset; + }); + + return a | b; +}; diff --git a/README.md b/README.md index 1972c5a3..559b88e1 100644 --- a/README.md +++ b/README.md @@ -82,6 +82,7 @@ 134|[Gas Station](./0134-gas-station.js)|Medium| 135|[Candy](./0135-candy.js)|Hard| 136|[Single Number](./0136-single-number.js)|Easy| +137|[Single Number II](./0137-single-number-ii.js)|Medium| 141|[Linked List Cycle](./0141-linked-list-cycle.js)|Easy| 142|[Linked List Cycle II](./0142-linked-list-cycle-ii.js)|Medium| 143|[Reorder List](./0143-reorder-list.js)|Medium| From e6678862b46f52fa5829f0abce86f730eb0c9983 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 8 Jan 2023 15:14:45 -0600 Subject: [PATCH 310/919] Add solution #2235 --- 2235-add-two-integers.js | 16 ++++++++++++++++ README.md | 1 + 2 files changed, 17 insertions(+) create mode 100644 2235-add-two-integers.js diff --git a/2235-add-two-integers.js b/2235-add-two-integers.js new file mode 100644 index 00000000..ab31d2c9 --- /dev/null +++ b/2235-add-two-integers.js @@ -0,0 +1,16 @@ +/** + * 2235. Add Two Integers + * https://leetcode.com/problems/add-two-integers/ + * Difficulty: Easy + * + * Given two integers num1 and num2, return the sum of the two integers. + */ + +/** + * @param {number} num1 + * @param {number} num2 + * @return {number} + */ +var sum = function(num1, num2) { + return num1 + num2; +}; diff --git a/README.md b/README.md index 559b88e1..034234ce 100644 --- a/README.md +++ b/README.md @@ -298,6 +298,7 @@ 2114|[Maximum Number of Words Found in Sentences](./2114-maximum-number-of-words-found-in-sentences.js)|Easy| 2129|[Capitalize the Title](./2129-capitalize-the-title.js)|Easy| 2154|[Keep Multiplying Found Values by Two](./2154-keep-multiplying-found-values-by-two.js)|Easy| +2235|[Add Two Integers](./2235-add-two-integers.js)|Easy| 2244|[Minimum Rounds to Complete All Tasks](./2244-minimum-rounds-to-complete-all-tasks.js)|Medium| 2427|[Number of Common Factors](./2427-number-of-common-factors.js)|Easy| 2469|[Convert the Temperature](./2469-convert-the-temperature.js)|Easy| From c70d72225d780bfb53cd293d9788c6a2413034c6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 8 Jan 2023 15:16:22 -0600 Subject: [PATCH 311/919] Add solution #149 --- 0149-max-points-on-a-line.js | 29 +++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 30 insertions(+) create mode 100644 0149-max-points-on-a-line.js diff --git a/0149-max-points-on-a-line.js b/0149-max-points-on-a-line.js new file mode 100644 index 00000000..003f8bb8 --- /dev/null +++ b/0149-max-points-on-a-line.js @@ -0,0 +1,29 @@ +/** + * 149. Max Points on a Line + * https://leetcode.com/problems/max-points-on-a-line/ + * Difficulty: Hard + * + * Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane, + * return the maximum number of points that lie on the same straight line. + */ + +/** + * @param {number[][]} points + * @return {number} + */ +var maxPoints = function(points) { + let max = 0; + + points.forEach(x => { + const slopes = new Map(); + + points.forEach(y => { + if (x === y) return; + const slope = y[0] - x[0] !== 0 ? (y[1] - x[1]) / (y[0] - x[0]) : Infinity; + slopes.set(slope, (slopes.get(slope) || 0) + 1); + max = Math.max(max, slopes.get(slope)); + }); + }); + + return max + 1; +}; diff --git a/README.md b/README.md index 034234ce..32d3e1d5 100644 --- a/README.md +++ b/README.md @@ -88,6 +88,7 @@ 143|[Reorder List](./0143-reorder-list.js)|Medium| 144|[Binary Tree Preorder Traversal](./0144-binary-tree-preorder-traversal.js)|Easy| 145|[Binary Tree Postorder Traversal](./0145-binary-tree-postorder-traversal.js)|Easy| +149|[Max Points on a Line](./0149-max-points-on-a-line.js)|Hard| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| 167|[Two Sum II - Input Array Is Sorted](./0167-two-sum-ii-input-array-is-sorted.js)|Easy| From efc9a1b79212f50e5a599516e0c465635c99cb72 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 8 Jan 2023 15:17:40 -0600 Subject: [PATCH 312/919] Add solution #509 --- 0509-fibonacci-number.js | 25 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 26 insertions(+) create mode 100644 0509-fibonacci-number.js diff --git a/0509-fibonacci-number.js b/0509-fibonacci-number.js new file mode 100644 index 00000000..2c4db308 --- /dev/null +++ b/0509-fibonacci-number.js @@ -0,0 +1,25 @@ +/** + * 509. Fibonacci Number + * https://leetcode.com/problems/fibonacci-number/ + * Difficulty: Easy + * + * The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, + * such that each number is the sum of the two preceding ones, starting from 0 and 1. That is: + * - F(0) = 0, F(1) = 1 + * - F(n) = F(n - 1) + F(n - 2), for n > 1. + * Given n, calculate F(n). + */ + +/** + * @param {number} n + * @return {number} + */ +var fib = function(n) { + const nums = [0, 1]; + + for (let i = 2; i <= n; i++) { + nums.push(nums[i - 2] + nums[i - 1]); + } + + return nums[n]; +}; diff --git a/README.md b/README.md index 32d3e1d5..8b24869d 100644 --- a/README.md +++ b/README.md @@ -144,6 +144,7 @@ 476|[Number Complement](./0476-number-complement.js)|Easy| 500|[Keyboard Row](./0500-keyboard-row.js)|Easy| 506|[Relative Ranks](./0506-relative-ranks.js)|Easy| +509|[Fibonacci Number](./0509-fibonacci-number.js)|Easy| 520|[Detect Capital](./0520-detect-capital.js)|Easy| 541|[Reverse String II](./0541-reverse-string-ii.js)|Easy| 542|[01 Matrix](./0542-01-matrix.js)|Medium| From 9e9c133a8981873da98d99b4697171138b390cc2 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 9 Jan 2023 22:26:37 -0600 Subject: [PATCH 313/919] Add solution #1331 --- 1331-rank-transform-of-an-array.js | 25 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 26 insertions(+) create mode 100644 1331-rank-transform-of-an-array.js diff --git a/1331-rank-transform-of-an-array.js b/1331-rank-transform-of-an-array.js new file mode 100644 index 00000000..40bb5243 --- /dev/null +++ b/1331-rank-transform-of-an-array.js @@ -0,0 +1,25 @@ +/** + * 1331. Rank Transform of an Array + * https://leetcode.com/problems/rank-transform-of-an-array/ + * Difficulty: Easy + * + * Given an array of integers arr, replace each element with its rank. + * + * The rank represents how large the element is. The rank has the following rules: + * - Rank is an integer starting from 1. + * - The larger the element, the larger the rank. If two elements are equal, their + * rank must be the same. + * - Rank should be as small as possible. + */ + +/** + * @param {number[]} arr + * @return {number[]} + */ +var arrayRankTransform = function(arr) { + const ranks = [...new Set(arr)] + .sort((a, b) => a - b) + .reduce((map, value, index) => map.set(value, index + 1), new Map()); + + return arr.map(rank => ranks.get(rank)); +}; diff --git a/README.md b/README.md index 8b24869d..10f0d3d0 100644 --- a/README.md +++ b/README.md @@ -230,6 +230,7 @@ 1318|[Minimum Flips to Make a OR b Equal to c](./1318-minimum-flips-to-make-a-or-b-equal-to-c.js)|Medium| 1323|[Maximum 69 Number](./1323-maximum-69-number.js)|Easy| 1324|[Print Words Vertically](./1324-print-words-vertically.js)|Medium| +1331|[Rank Transform of an Array](./1331-rank-transform-of-an-array.js)|Easy| 1332|[Remove Palindromic Subsequences](./1332-remove-palindromic-subsequences.js)|Easy| 1333|[Filter Restaurants by Vegan-Friendly, Price and Distance](./1333-filter-restaurants-by-vegan-friendly-price-and-distance.js)|Medium| 1342|[Number of Steps to Reduce a Number to Zero](./1342-number-of-steps-to-reduce-a-number-to-zero.js)|Easy| From 6ac75eb58555642226c71c066ea3a980cc56ea9e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 9 Jan 2023 22:28:03 -0600 Subject: [PATCH 314/919] Add solution #1817 --- 1817-finding-the-users-active-minutes.js | 39 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 40 insertions(+) create mode 100644 1817-finding-the-users-active-minutes.js diff --git a/1817-finding-the-users-active-minutes.js b/1817-finding-the-users-active-minutes.js new file mode 100644 index 00000000..2988b8af --- /dev/null +++ b/1817-finding-the-users-active-minutes.js @@ -0,0 +1,39 @@ +/** + * 1817. Finding the Users Active Minutes + * https://leetcode.com/problems/finding-the-users-active-minutes/ + * Difficulty: Medium + * + * You are given the logs for users' actions on LeetCode, and an integer k. The logs are represented + * by a 2D integer array logs where each logs[i] = [IDi, timei] indicates that the user with IDi + * performed an action at the minute timei. + * + * Multiple users can perform actions simultaneously, and a single user can perform multiple actions + * in the same minute. + * + * The user active minutes (UAM) for a given user is defined as the number of unique minutes in which + * the user performed an action on LeetCode. A minute can only be counted once, even if multiple actions + * occur during it. + * + * You are to calculate a 1-indexed array answer of size k such that, for each j (1 <= j <= k), answer[j] + * is the number of users whose UAM equals j. + * + * Return the array answer as described above. + */ + +/** + * @param {number[][]} logs + * @param {number} k + * @return {number[]} + */ +var findingUsersActiveMinutes = function(logs, k) { + const map = new Map(); + logs.forEach(([id, time]) => { + map.set(id, map.get(id) || new Set()); + map.get(id).add(time); + }); + + const result = new Array(k).fill(0); + [...map.values()].forEach(({ size }) => result[size - 1]++); + + return result; +}; diff --git a/README.md b/README.md index 10f0d3d0..9e76a33f 100644 --- a/README.md +++ b/README.md @@ -282,6 +282,7 @@ 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| 1791|[Find Center of Star Graph](./1791-find-center-of-star-graph.js)|Easy| 1812|[Determine Color of a Chessboard Square](./1812-determine-color-of-a-chessboard-square.js)|Easy| +1817|[Finding the Users Active Minutes](./1817-finding-the-users-active-minutes.js)|Medium| 1832|[Check if the Sentence Is Pangram](./1832-check-if-the-sentence-is-pangram.js)|Easy| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| From 965432a9c8b7255af2f0f4172a84b7daf9f7a1ee Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 9 Jan 2023 22:29:21 -0600 Subject: [PATCH 315/919] Add solution #2482 --- ...etween-ones-and-zeros-in-row-and-column.js | 36 +++++++++++++++++++ README.md | 1 + 2 files changed, 37 insertions(+) create mode 100644 2482-difference-between-ones-and-zeros-in-row-and-column.js diff --git a/2482-difference-between-ones-and-zeros-in-row-and-column.js b/2482-difference-between-ones-and-zeros-in-row-and-column.js new file mode 100644 index 00000000..67116974 --- /dev/null +++ b/2482-difference-between-ones-and-zeros-in-row-and-column.js @@ -0,0 +1,36 @@ +/** + * 2482. Difference Between Ones and Zeros in Row and Column + * https://leetcode.com/problems/difference-between-ones-and-zeros-in-row-and-column/ + * Difficulty: Medium + * + * You are given a 0-indexed m x n binary matrix grid. + * + * A 0-indexed m x n difference matrix diff is created with the following procedure: + * - Let the number of ones in the ith row be onesRowi. + * - Let the number of ones in the jth column be onesColj. + * - Let the number of zeros in the ith row be zerosRowi. + * - Let the number of zeros in the jth column be zerosColj. + * - diff[i][j] = onesRowi + onesColj - zerosRowi - zerosColj + * + * Return the difference matrix diff. + */ + +/** + * @param {number[][]} grid + * @return {number[][]} + */ +var onesMinusZeros = function(grid) { + const rows = new Array(grid.length).fill(0); + const columns = new Array(grid[0].length).fill(0); + + grid.forEach((row, r) => row.forEach((value, c) => { + rows[r] += value; + columns[c] += value; + })); + + grid.forEach((row, r) => row.forEach((value, c) => { + grid[r][c] = 2 * rows[r] - grid.length + 2 * columns[c] - row.length; + })); + + return grid; +}; diff --git a/README.md b/README.md index 9e76a33f..88403308 100644 --- a/README.md +++ b/README.md @@ -306,6 +306,7 @@ 2244|[Minimum Rounds to Complete All Tasks](./2244-minimum-rounds-to-complete-all-tasks.js)|Medium| 2427|[Number of Common Factors](./2427-number-of-common-factors.js)|Easy| 2469|[Convert the Temperature](./2469-convert-the-temperature.js)|Easy| +2482|[Difference Between Ones and Zeros in Row and Column](./2482-difference-between-ones-and-zeros-in-row-and-column.js)|Medium| ## License From 7eadee93e7f39c04cf20342d8166fee344770248 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 10 Jan 2023 18:28:31 -0600 Subject: [PATCH 316/919] Add solution #80 --- ...-remove-duplicates-from-sorted-array-ii.js | 36 +++++++++++++++++++ README.md | 1 + 2 files changed, 37 insertions(+) create mode 100644 0080-remove-duplicates-from-sorted-array-ii.js diff --git a/0080-remove-duplicates-from-sorted-array-ii.js b/0080-remove-duplicates-from-sorted-array-ii.js new file mode 100644 index 00000000..361d4910 --- /dev/null +++ b/0080-remove-duplicates-from-sorted-array-ii.js @@ -0,0 +1,36 @@ +/** + * 80. Remove Duplicates from Sorted Array II + * https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/ + * Difficulty: Medium + * + * Given an integer array nums sorted in non-decreasing order, remove some duplicates in-place such + * that each unique element appears at most twice. The relative order of the elements should be kept + * the same. + * + * Since it is impossible to change the length of the array in some languages, you must instead have + * the result be placed in the first part of the array nums. More formally, if there are k elements + * after removing the duplicates, then the first k elements of nums should hold the final result. + * It does not matter what you leave beyond the first k elements. + * + * Return k after placing the final result in the first k slots of nums. + * + * Do not allocate extra space for another array. You must do this by modifying the input array + * in-place with O(1) extra memory. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var removeDuplicates = function(nums) { + let offset = 2; + + for (let i = 2; i < nums.length; i++) { + if (nums[i] !== nums[offset - 2]) { + nums[offset] = nums[i]; + offset++; + } + } + + return offset; +}; diff --git a/README.md b/README.md index 88403308..2db72f65 100644 --- a/README.md +++ b/README.md @@ -61,6 +61,7 @@ 74|[Search a 2D Matrix](./0074-search-a-2d-matrix.js)|Medium| 77|[Combinations](./0077-combinations.js)|Medium| 78|[Subsets](./0078-subsets.js)|Medium| +80|[Remove Duplicates from Sorted Array II](./0080-remove-duplicates-from-sorted-array-ii.js)|Medium| 83|[Remove Duplicates from Sorted List](./0083-remove-duplicates-from-sorted-list.js)|Easy| 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| 90|[Subsets II](./0090-subsets-ii.js)|Medium| From 442871f1eefdc501c361647b08d671b1ce1eb44d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 10 Jan 2023 18:29:39 -0600 Subject: [PATCH 317/919] Add solution #1443 --- ...um-time-to-collect-all-apples-in-a-tree.js | 43 +++++++++++++++++++ README.md | 1 + 2 files changed, 44 insertions(+) create mode 100644 1443-minimum-time-to-collect-all-apples-in-a-tree.js diff --git a/1443-minimum-time-to-collect-all-apples-in-a-tree.js b/1443-minimum-time-to-collect-all-apples-in-a-tree.js new file mode 100644 index 00000000..9ceb713c --- /dev/null +++ b/1443-minimum-time-to-collect-all-apples-in-a-tree.js @@ -0,0 +1,43 @@ +/** + * 1443. Minimum Time to Collect All Apples in a Tree + * https://leetcode.com/problems/minimum-time-to-collect-all-apples-in-a-tree/ + * Difficulty: Medium + * + * Given an undirected tree consisting of n vertices numbered from 0 to n-1, which has some apples + * in their vertices. You spend 1 second to walk over one edge of the tree. Return the minimum time + * in seconds you have to spend to collect all apples in the tree, starting at vertex 0 and coming + * back to this vertex. + * + * The edges of the undirected tree are given in the array edges, where edges[i] = [ai, bi] means + * that exists an edge connecting the vertices ai and bi. Additionally, there is a boolean array + * hasApple, where hasApple[i] = true means that vertex i has an apple; otherwise, it does not + * have any apple. + */ + +/** + * @param {number} n + * @param {number[][]} edges + * @param {boolean[]} hasApple + * @return {number} + */ +var minTime = function(n, edges, hasApple) { + const map = new Map(); + const seen = new Set(); + let time = 0; + + edges.forEach(([value, key]) => map.set(key, value)); + for (let i = n - 1; i >= 0; i--) { + if (hasApple[i]) { + dfs(i); + } + } + + function dfs(key) { + if (key === 0 || seen.has(key)) return; + seen.add(key); + time += 2; + dfs(map.get(key)); + } + + return time; +}; diff --git a/README.md b/README.md index 2db72f65..5cc13328 100644 --- a/README.md +++ b/README.md @@ -248,6 +248,7 @@ 1431|[Kids With the Greatest Number of Candies](./1431-kids-with-the-greatest-number-of-candies.js)|Easy| 1436|[Destination City](./1436-destination-city.js)|Easy| 1437|[Check If All 1's Are at Least Length K Places Away](./1437-check-if-all-1s-are-at-least-length-k-places-away.js)|Easy| +1443|[Minimum Time to Collect All Apples in a Tree](./1443-minimum-time-to-collect-all-apples-in-a-tree.js)|Medium| 1446|[Consecutive Characters](./1446-consecutive-characters.js)|Easy| 1447|[Simplified Fractions](./1447-simplified-fractions.js)|Medium| 1450|[Number of Students Doing Homework at a Given Time](./1450-number-of-students-doing-homework-at-a-given-time.js)|Easy| From e1d6259835d1a13a0d3a091b9b15513285eacc5c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 10 Jan 2023 18:32:14 -0600 Subject: [PATCH 318/919] Add solution #2490 --- 2490-circular-sentence.js | 32 ++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 2490-circular-sentence.js diff --git a/2490-circular-sentence.js b/2490-circular-sentence.js new file mode 100644 index 00000000..fefe5145 --- /dev/null +++ b/2490-circular-sentence.js @@ -0,0 +1,32 @@ +/** + * 2490. Circular Sentence + * https://leetcode.com/problems/circular-sentence/ + * Difficulty: Easy + * + * A sentence is a list of words that are separated by a single space with no leading or trailing spaces. + * + * For example, "Hello World", "HELLO", "hello world hello world" are all sentences. + * Words consist of only uppercase and lowercase English letters. Uppercase and lowercase English letters + * are considered different. + * + * A sentence is circular if: + * - The last character of a word is equal to the first character of the next word. + * - The last character of the last word is equal to the first character of the first word. + * + * For example, "leetcode exercises sound delightful", "eetcode", "leetcode eats soul" are all circular + * sentences. However, "Leetcode is cool", "happy Leetcode", "Leetcode" and "I like Leetcode" are not + * circular sentences. + * + * Given a string sentence, return true if it is circular. Otherwise, return false. + */ + +/** + * @param {string} sentence + * @return {boolean} + */ +var isCircularSentence = function(sentence) { + const match = sentence.match(/^\w$|^(\w).*\1$/) !== null; + const count = sentence.match(/(\w)(?=\s\1)/g)?.length || 0; + + return match && count === sentence.split(/\s/).length - 1; +}; diff --git a/README.md b/README.md index 5cc13328..76cb0048 100644 --- a/README.md +++ b/README.md @@ -309,6 +309,7 @@ 2427|[Number of Common Factors](./2427-number-of-common-factors.js)|Easy| 2469|[Convert the Temperature](./2469-convert-the-temperature.js)|Easy| 2482|[Difference Between Ones and Zeros in Row and Column](./2482-difference-between-ones-and-zeros-in-row-and-column.js)|Medium| +2490|[Circular Sentence](./2490-circular-sentence.js)|Easy| ## License From e6238b24eafa001d7b8fa7b6207b50dee9c3dc8f Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 11 Jan 2023 22:50:06 -0600 Subject: [PATCH 319/919] Add solution #419 --- 0419-battleships-in-a-board.js | 31 +++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 0419-battleships-in-a-board.js diff --git a/0419-battleships-in-a-board.js b/0419-battleships-in-a-board.js new file mode 100644 index 00000000..59585443 --- /dev/null +++ b/0419-battleships-in-a-board.js @@ -0,0 +1,31 @@ +/** + * 419. Battleships in a Board + * https://leetcode.com/problems/battleships-in-a-board/ + * Difficulty: Medium + * + * Given an m x n matrix board where each cell is a battleship 'X' or empty '.', return the + * number of the battleships on board. + * + * Battleships can only be placed horizontally or vertically on board. In other words, they + * can only be made of the shape 1 x k (1 row, k columns) or k x 1 (k rows, 1 column), where + * k can be of any size. At least one horizontal or vertical cell separates between two + * battleships (i.e., there are no adjacent battleships). + */ + +/** + * @param {character[][]} boardx + * @return {number} + */ +var countBattleships = function(board) { + let count = 0; + + for (let i = 0; i < board.length; i++) { + for (let j = 0; j < board[i].length; j++) { + if (board[i][j] === 'X' && board[i][j - 1] !== 'X' && (!board[i - 1] || board[i - 1][j] !== 'X')) { + count++; + } + } + } + + return count; +}; diff --git a/README.md b/README.md index 76cb0048..70895a77 100644 --- a/README.md +++ b/README.md @@ -136,6 +136,7 @@ 383|[Ransom Note](./0383-ransom-note.js)|Easy| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| 414|[Third Maximum Number](./0414-third-maximum-number.js)|Easy| +419|[Battleships in a Board](./0419-battleships-in-a-board.js)|Medium| 442|[Find All Duplicates in an Array](./0442-find-all-duplicates-in-an-array.js)|Medium| 448|[Find All Numbers Disappeared in an Array](./0448-find-all-numbers-disappeared-in-an-array.js)|Easy| 451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| From c68c6fc9307e2c231c75d93b936dcb05d95022ff Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 11 Jan 2023 22:51:25 -0600 Subject: [PATCH 320/919] Add solution #30 --- ...bstring-with-concatenation-of-all-words.js | 54 +++++++++++++++++++ README.md | 1 + 2 files changed, 55 insertions(+) create mode 100644 0030-substring-with-concatenation-of-all-words.js diff --git a/0030-substring-with-concatenation-of-all-words.js b/0030-substring-with-concatenation-of-all-words.js new file mode 100644 index 00000000..1e121f31 --- /dev/null +++ b/0030-substring-with-concatenation-of-all-words.js @@ -0,0 +1,54 @@ +/** + * 30. Substring with Concatenation of All Words + * https://leetcode.com/problems/substring-with-concatenation-of-all-words/ + * Difficulty: Hard + * + * You are given a string s and an array of strings words. All the strings of words are of the same + * length. + * + * A concatenated substring in s is a substring that contains all the strings of any permutation of + * words concatenated. + * + * - For example, if words = ["ab","cd","ef"], then "abcdef", "abefcd", "cdabef", "cdefab", "efabcd", + * and "efcdab" are all concatenated strings. "acdbef" is not a concatenated substring because it is + * not the concatenation of any permutation of words. + * + * Return the starting indices of all the concatenated substrings in s. You can return the answer in + * any order. + */ + +/** + * @param {string} s + * @param {string[]} words + * @return {number[]} + */ +var findSubstring = function(s, words) { + if (!words || words.length === 0) { + return []; + } + + const result = []; + const map = {}; + const count = words[0].length; + + words.forEach(word => map[word] = ~~map[word] + 1); + + for (let i = 0; i < s.length - words.length * count + 1; i++) { + const temp = Object.assign({}, map); + + for (let j = i; j < i + words.length * count; j += count) { + const key = s.slice(j, j + count); + if (!temp[key]) { + break; + } else if (--temp[key] === 0) { + delete temp[key]; + } + } + + if (Object.keys(temp).length === 0) { + result.push(i); + } + } + + return result; +}; diff --git a/README.md b/README.md index 70895a77..f1add769 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,7 @@ 27|[Remove Element](./0027-remove-element.js)|Easy| 28|[Implement strStr()](./0028-implement-strstr.js)|Easy| 29|[Divide Two Integers](./0029-divide-two-integers.js)|Medium| +30|[Substring with Concatenation of All Words](./0030-substring-with-concatenation-of-all-words.js)|Hard| 31|[Next Permutation](./0031-next-permutation.js)|Medium| 33|[Search in Rotated Sorted Array](./0033-search-in-rotated-sorted-array.js)|Medium| 34|[Find First and Last Position of Element in Sorted Array](./0034-find-first-and-last-position-of-element-in-sorted-array.js)|Medium| From 25877d861de8e1147253a12166b916d4e4cc0a6d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 11 Jan 2023 22:52:14 -0600 Subject: [PATCH 321/919] Add solution #461 --- 0461-hamming-distance.js | 19 +++++++++++++++++++ README.md | 1 + 2 files changed, 20 insertions(+) create mode 100644 0461-hamming-distance.js diff --git a/0461-hamming-distance.js b/0461-hamming-distance.js new file mode 100644 index 00000000..f27d3cd9 --- /dev/null +++ b/0461-hamming-distance.js @@ -0,0 +1,19 @@ +/** + * 461. Hamming Distance + * https://leetcode.com/problems/hamming-distance/ + * Difficulty: Easy + * + * The Hamming distance between two integers is the number of positions at which the corresponding + * bits are different. + * + * Given two integers x and y, return the Hamming distance between them. + */ + +/** + * @param {number} x + * @param {number} y + * @return {number} + */ +var hammingDistance = function(x, y) { + return (x ^ y).toString(2).replace(/0+/g, '').length; +}; diff --git a/README.md b/README.md index f1add769..86b50fe2 100644 --- a/README.md +++ b/README.md @@ -143,6 +143,7 @@ 451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| 452|[Minimum Number of Arrows to Burst Balloons](./0452-minimum-number-of-arrows-to-burst-balloons.js)|Medium| 459|[Repeated Substring Pattern](./0459-repeated-substring-pattern.js)|Easy| +461|[Hamming Distance](./0461-hamming-distance.js)|Easy| 463|[Island Perimeter](./0463-island-perimeter.js)|Medium| 476|[Number Complement](./0476-number-complement.js)|Easy| 500|[Keyboard Row](./0500-keyboard-row.js)|Easy| From 5a7315857a7d0d0a25ca26912aa904370ab1665e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 12 Jan 2023 18:07:09 -0600 Subject: [PATCH 322/919] Add solution #2396 --- 2396-strictly-palindromic-number.js | 20 ++++++++++++++++++++ README.md | 1 + 2 files changed, 21 insertions(+) create mode 100644 2396-strictly-palindromic-number.js diff --git a/2396-strictly-palindromic-number.js b/2396-strictly-palindromic-number.js new file mode 100644 index 00000000..39833aee --- /dev/null +++ b/2396-strictly-palindromic-number.js @@ -0,0 +1,20 @@ +/** + * 2396. Strictly Palindromic Number + * https://leetcode.com/problems/strictly-palindromic-number/ + * Difficulty: Medium + * + * An integer n is strictly palindromic if, for every base b between 2 and n - 2 (inclusive), + * the string representation of the integer n in base b is palindromic. + * + * Given an integer n, return true if n is strictly palindromic and false otherwise. + * + * A string is palindromic if it reads the same forward and backward. + */ + +/** + * @param {number} n + * @return {boolean} + */ +var isStrictlyPalindromic = function(n) { + return false; +}; diff --git a/README.md b/README.md index 86b50fe2..b1b668cf 100644 --- a/README.md +++ b/README.md @@ -309,6 +309,7 @@ 2154|[Keep Multiplying Found Values by Two](./2154-keep-multiplying-found-values-by-two.js)|Easy| 2235|[Add Two Integers](./2235-add-two-integers.js)|Easy| 2244|[Minimum Rounds to Complete All Tasks](./2244-minimum-rounds-to-complete-all-tasks.js)|Medium| +2396|[Strictly Palindromic Number](./2396-strictly-palindromic-number.js)|Medium| 2427|[Number of Common Factors](./2427-number-of-common-factors.js)|Easy| 2469|[Convert the Temperature](./2469-convert-the-temperature.js)|Easy| 2482|[Difference Between Ones and Zeros in Row and Column](./2482-difference-between-ones-and-zeros-in-row-and-column.js)|Medium| From 41e21e481cf710c517d917d9ad0d5310402f55ed Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 12 Jan 2023 18:12:34 -0600 Subject: [PATCH 323/919] Add solution #2413 --- 2413-smallest-even-multiple.js | 15 +++++++++++++++ README.md | 1 + 2 files changed, 16 insertions(+) create mode 100644 2413-smallest-even-multiple.js diff --git a/2413-smallest-even-multiple.js b/2413-smallest-even-multiple.js new file mode 100644 index 00000000..657f2de5 --- /dev/null +++ b/2413-smallest-even-multiple.js @@ -0,0 +1,15 @@ +/** + * 2413. Smallest Even Multiple + * https://leetcode.com/problems/smallest-even-multiple/ + * Difficulty: Easy + * + * Given a positive integer n, return the smallest positive integer that is a multiple of both 2 and n. + */ + +/** + * @param {number} n + * @return {number} + */ +var smallestEvenMultiple = function(n) { + return n * (n % 2 + 1); +}; diff --git a/README.md b/README.md index b1b668cf..02517e84 100644 --- a/README.md +++ b/README.md @@ -310,6 +310,7 @@ 2235|[Add Two Integers](./2235-add-two-integers.js)|Easy| 2244|[Minimum Rounds to Complete All Tasks](./2244-minimum-rounds-to-complete-all-tasks.js)|Medium| 2396|[Strictly Palindromic Number](./2396-strictly-palindromic-number.js)|Medium| +2413|[Smallest Even Multiple](./2413-smallest-even-multiple.js)|Easy| 2427|[Number of Common Factors](./2427-number-of-common-factors.js)|Easy| 2469|[Convert the Temperature](./2469-convert-the-temperature.js)|Easy| 2482|[Difference Between Ones and Zeros in Row and Column](./2482-difference-between-ones-and-zeros-in-row-and-column.js)|Medium| From 9037a4cd68d9f08e912219e9e00a6ec8742353fc Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 12 Jan 2023 18:14:27 -0600 Subject: [PATCH 324/919] Add solution #138 --- 0138-copy-list-with-random-pointer.js | 61 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 62 insertions(+) create mode 100644 0138-copy-list-with-random-pointer.js diff --git a/0138-copy-list-with-random-pointer.js b/0138-copy-list-with-random-pointer.js new file mode 100644 index 00000000..9edefa18 --- /dev/null +++ b/0138-copy-list-with-random-pointer.js @@ -0,0 +1,61 @@ +/** + * 138. Copy List with Random Pointer + * https://leetcode.com/problems/copy-list-with-random-pointer/ + * Difficulty: Medium + * + * A linked list of length n is given such that each node contains an additional random pointer, + * which could point to any node in the list, or null. + * + * Construct a deep copy of the list. The deep copy should consist of exactly n brand new nodes, + * where each new node has its value set to the value of its corresponding original node. Both + * the next and random pointer of the new nodes should point to new nodes in the copied list such + * that the pointers in the original list and copied list represent the same list state. None of + * the pointers in the new list should point to nodes in the original list. + * + * For example, if there are two nodes X and Y in the original list, where X.random --> Y, then + * for the corresponding two nodes x and y in the copied list, x.random --> y. + * + * Return the head of the copied linked list. + * + * The linked list is represented in the input/output as a list of n nodes. Each node is + * represented as a pair of [val, random_index] where: + * - val: an integer representing Node.val + * - random_index: the index of the node (range from 0 to n-1) that the random pointer points + * to, or null if it does not point to any node. + * + * Your code will only be given the head of the original linked list. + */ + +/** + * // Definition for a Node. + * function Node(val, next, random) { + * this.val = val; + * this.next = next; + * this.random = random; + * }; + */ + +/** + * @param {Node} head + * @return {Node} + */ +var copyRandomList = function(head) { + const map = new Map(); + + function copy(reference) { + if (reference === null) return null; + const instance = map.get(reference); + if (instance) { + return instance; + } + + const node = new Node(reference.val); + map.set(reference, node); + node.next = copy(reference.next); + node.random = copy(reference.random); + + return node; + } + + return copy(head); +}; diff --git a/README.md b/README.md index 02517e84..4204ff9c 100644 --- a/README.md +++ b/README.md @@ -85,6 +85,7 @@ 135|[Candy](./0135-candy.js)|Hard| 136|[Single Number](./0136-single-number.js)|Easy| 137|[Single Number II](./0137-single-number-ii.js)|Medium| +138|[Copy List with Random Pointer](./0138-copy-list-with-random-pointer.js)|Medium| 141|[Linked List Cycle](./0141-linked-list-cycle.js)|Easy| 142|[Linked List Cycle II](./0142-linked-list-cycle-ii.js)|Medium| 143|[Reorder List](./0143-reorder-list.js)|Medium| From aa0dcf7e9ba2352eba0937768b7ed89c52883242 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 13 Jan 2023 20:47:06 -0600 Subject: [PATCH 325/919] Add solution #125 --- 0125-valid-palindrome.js | 20 ++++++++++++++++++++ README.md | 1 + 2 files changed, 21 insertions(+) create mode 100644 0125-valid-palindrome.js diff --git a/0125-valid-palindrome.js b/0125-valid-palindrome.js new file mode 100644 index 00000000..74ad00f1 --- /dev/null +++ b/0125-valid-palindrome.js @@ -0,0 +1,20 @@ +/** + * 125. Valid Palindrome + * https://leetcode.com/problems/valid-palindrome/ + * Difficulty: Easy + * + * A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and + * removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric + * characters include letters and numbers. + * + * Given a string s, return true if it is a palindrome, or false otherwise. + */ + +/** + * @param {string} s + * @return {boolean} + */ +var isPalindrome = function(s) { + const string = s.replace(/[^A-Z\d]+/ig, '').toLowerCase(); + return string.split('').reverse().join('') === string; +}; diff --git a/README.md b/README.md index 4204ff9c..89ef5665 100644 --- a/README.md +++ b/README.md @@ -79,6 +79,7 @@ 119|[Pascal's Triangle II](./0119-pascals-triangle-ii.js)|Easy| 120|[Triangle](./0120-triangle.js)|Medium| 121|[Best Time to Buy and Sell Stock](./0121-best-time-to-buy-and-sell-stock.js)|Easy| +125|[Valid Palindrome](./0125-valid-palindrome.js)|Easy| 128|[Longest Consecutive Sequence](./0128-longest-consecutive-sequence.js)|Medium| 133|[Clone Graph](./0133-clone-graph.js)|Medium| 134|[Gas Station](./0134-gas-station.js)|Medium| From fe4ecbbcbd172c2062520bfb27e1906d7b06812e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 13 Jan 2023 20:48:45 -0600 Subject: [PATCH 326/919] Add solution #680 --- 0680-valid-palindrome-ii.js | 34 ++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 0680-valid-palindrome-ii.js diff --git a/0680-valid-palindrome-ii.js b/0680-valid-palindrome-ii.js new file mode 100644 index 00000000..9a827b99 --- /dev/null +++ b/0680-valid-palindrome-ii.js @@ -0,0 +1,34 @@ +/** + * 680. Valid Palindrome II + * https://leetcode.com/problems/valid-palindrome-ii/ + * Difficulty: Easy + * + * Given a string s, return true if the s can be palindrome after deleting at most one + * character from it. + */ + +/** + * @param {string} s + * @return {boolean} + */ +var validPalindrome = function(s) { + for (let left = 0, right = s.length - 1; left < right; left++, right--) { + if (s[left] !== s[right]) { + return isPalindrome(s, left + 1, right) || isPalindrome(s, left, right - 1); + } + } + + return true; +}; + +function isPalindrome(s, left, right) { + while (left < right) { + if (s[left] !== s[right]) { + return false; + } + right--; + left++; + } + + return true; +} diff --git a/README.md b/README.md index 89ef5665..3887c09d 100644 --- a/README.md +++ b/README.md @@ -166,6 +166,7 @@ 645|[Set Mismatch](./0645-set-mismatch.js)|Medium| 648|[Replace Words](./0648-replace-words.js)|Medium| 653|[Two Sum IV - Input is a BST](./0653-two-sum-iv-input-is-a-bst.js)|Easy| +680|[Valid Palindrome II](./0680-valid-palindrome-ii.js)|Easy| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| 695|[Max Area of Island](./0695-max-area-of-island.js)|Medium| 700|[Search in a Binary Search Tree](./0700-search-in-a-binary-search-tree.js)|Easy| From d430920e633ff435768a18ce029bd603761f3190 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 13 Jan 2023 20:49:17 -0600 Subject: [PATCH 327/919] Add solution #139 --- 0139-word-break.js | 30 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 0139-word-break.js diff --git a/0139-word-break.js b/0139-word-break.js new file mode 100644 index 00000000..1ce1830b --- /dev/null +++ b/0139-word-break.js @@ -0,0 +1,30 @@ +/** + * 139. Word Break + * https://leetcode.com/problems/word-break/ + * Difficulty: Medium + * + * Given a string s and a dictionary of strings wordDict, return true if s can be segmented into + * a space-separated sequence of one or more dictionary words. + * + * Note that the same word in the dictionary may be reused multiple times in the segmentation. + */ + +/** + * @param {string} s + * @param {string[]} wordDict + * @return {boolean} + */ +var wordBreak = function(s, wordDict) { + const result = [1, ...new Array(s.length + 1).fill(0)]; + + for (let i = 1; i <= s.length; i++) { + for (let j = 0; j < i; j++) { + if (result[j] && wordDict.includes(s.slice(j, i))) { + result[i] = 1; + break; + } + } + } + + return result[s.length]; +}; diff --git a/README.md b/README.md index 3887c09d..a1051836 100644 --- a/README.md +++ b/README.md @@ -87,6 +87,7 @@ 136|[Single Number](./0136-single-number.js)|Easy| 137|[Single Number II](./0137-single-number-ii.js)|Medium| 138|[Copy List with Random Pointer](./0138-copy-list-with-random-pointer.js)|Medium| +139|[Word Break](./0139-word-break.js)|Medium| 141|[Linked List Cycle](./0141-linked-list-cycle.js)|Easy| 142|[Linked List Cycle II](./0142-linked-list-cycle-ii.js)|Medium| 143|[Reorder List](./0143-reorder-list.js)|Medium| From 8f178f608ec85bf65da2109766bf64ffed216741 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 14 Jan 2023 21:45:20 -0600 Subject: [PATCH 328/919] Add solution #202 --- 0202-happy-number.js | 29 +++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 30 insertions(+) create mode 100644 0202-happy-number.js diff --git a/0202-happy-number.js b/0202-happy-number.js new file mode 100644 index 00000000..c6b10fa3 --- /dev/null +++ b/0202-happy-number.js @@ -0,0 +1,29 @@ +/** + * 202. Happy Number + * https://leetcode.com/problems/happy-number/ + * Difficulty: Easy + * + * Write an algorithm to determine if a number n is happy. + * + * A happy number is a number defined by the following process: + * - Starting with any positive integer, replace the number by the sum of the squares of its digits. + * - Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a + * cycle which does not include 1. + * - Those numbers for which this process ends in 1 are happy. + * + * Return true if n is a happy number, and false if not. + */ + +/** + * @param {number} n + * @return {boolean} + */ +var isHappy = function(n) { + while (n !== 1) { + n = [...String(n)].reduce((sum, digit) => sum + digit ** 2, 0); + if (n === 4) { + return false; + } + } + return true; +}; diff --git a/README.md b/README.md index a1051836..a63507b9 100644 --- a/README.md +++ b/README.md @@ -103,6 +103,7 @@ 190|[Reverse Bits](./0190-reverse-bits.js)|Easy| 191|[Number of 1 Bits](./0191-number-of-1-bits.js)|Easy| 198|[House Robber](./0198-house-robber.js)|Medium| +202|[Happy Number](./0202-happy-number.js)|Easy| 203|[Remove Linked List Elements](./0203-remove-linked-list-elements.js)|Easy| 204|[Count Primes](./0204-count-primes.js)|Medium| 206|[Reverse Linked List](./0206-reverse-linked-list.js)|Easy| From 12f366606a3246c59fca7deb112ed64ed067c060 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 14 Jan 2023 21:46:47 -0600 Subject: [PATCH 329/919] Add solution #62 --- 0062-unique-paths.js | 34 ++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 0062-unique-paths.js diff --git a/0062-unique-paths.js b/0062-unique-paths.js new file mode 100644 index 00000000..205f9601 --- /dev/null +++ b/0062-unique-paths.js @@ -0,0 +1,34 @@ +/** + * 62. Unique Paths + * https://leetcode.com/problems/unique-paths/ + * Difficulty: Medium + * + * There is a robot on an m x n grid. The robot is initially located at the top-left + * corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner + * (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any + * point in time. + * + * Given the two integers m and n, return the number of possible unique paths that + * the robot can take to reach the bottom-right corner. + */ + +/** + * @param {number} m + * @param {number} n + * @return {number} + */ +var uniquePaths = function(m, n) { + const row = new Array(n); + + for (let i = 0; i < n; i++) { + row[i] = 1; + } + + for (let i = 1; i < m; i++) { + for (let j = 1; j < n; j++) { + row[j] += row[j - 1]; + } + } + + return row[n - 1]; +}; diff --git a/README.md b/README.md index a63507b9..92bdb536 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,7 @@ 53|[Maximum Subarray](./0053-maximum-subarray.js)|Easy| 54|[Spiral Matrix](./0054-spiral-matrix.js)|Medium| 58|[Length of Last Word](./0058-length-of-last-word.js)|Easy| +62|[Unique Paths](./0062-unique-paths.js)|Medium| 66|[Plus One](./0066-plus-one.js)|Easy| 67|[Add Binary](./0067-add-binary.js)|Easy| 69|[Sqrt(x)](./0069-sqrtx.js)|Medium| From e173bbfcaf7bb7bf78f1e25e829b6b024fbe7d24 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 14 Jan 2023 21:47:47 -0600 Subject: [PATCH 330/919] Add solution #207 --- 0207-course-schedule.js | 49 +++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 50 insertions(+) create mode 100644 0207-course-schedule.js diff --git a/0207-course-schedule.js b/0207-course-schedule.js new file mode 100644 index 00000000..7a19f7d4 --- /dev/null +++ b/0207-course-schedule.js @@ -0,0 +1,49 @@ +/** + * 207. Course Schedule + * https://leetcode.com/problems/course-schedule/ + * Difficulty: Medium + * + * There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. + * You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you + * must take course bi first if you want to take course ai. + * + * For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1. + * + * Return true if you can finish all courses. Otherwise, return false. + */ + +/** + * @param {number} numCourses + * @param {number[][]} prerequisites + * @return {boolean} + */ +var canFinish = function(numCourses, prerequisites) { + const graph = new Map(); + const seen = new Set(); + + prerequisites.forEach(([course, prerequisite]) => { + graph.set(course, graph.get(course) || []); + graph.get(course).push(prerequisite); + }); + + function dfs(course) { + if (seen.has(course)) { + return false; + } + seen.add(course); + for (const prerequisite of graph.get(course) || []) { + if (!dfs(prerequisite)) return false; + } + seen.delete(course); + graph.set(course, []); + return true; + } + + for (let i = 0; i < numCourses; i++) { + if (!dfs(i)) { + return false; + } + } + + return true; +}; diff --git a/README.md b/README.md index 92bdb536..117f8019 100644 --- a/README.md +++ b/README.md @@ -108,6 +108,7 @@ 203|[Remove Linked List Elements](./0203-remove-linked-list-elements.js)|Easy| 204|[Count Primes](./0204-count-primes.js)|Medium| 206|[Reverse Linked List](./0206-reverse-linked-list.js)|Easy| +207|[Course Schedule](./0207-course-schedule.js)|Medium| 213|[House Robber II](./0213-house-robber-ii.js)|Medium| 214|[Shortest Palindrome](./0214-shortest-palindrome.js)|Hard| 215|[Kth Largest Element in an Array](./0215-kth-largest-element-in-an-array.js)|Medium| From 401dd659c398d2d4341b30e367726638838f89ba Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 15 Jan 2023 17:40:56 -0600 Subject: [PATCH 331/919] Add solution #32 --- 0032-longest-valid-parentheses.js | 36 +++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 37 insertions(+) create mode 100644 0032-longest-valid-parentheses.js diff --git a/0032-longest-valid-parentheses.js b/0032-longest-valid-parentheses.js new file mode 100644 index 00000000..6424b108 --- /dev/null +++ b/0032-longest-valid-parentheses.js @@ -0,0 +1,36 @@ +/** + * 32. Longest Valid Parentheses + * https://leetcode.com/problems/longest-valid-parentheses/ + * Difficulty: Hard + * + * Given a string containing just the characters '(' and ')', return the + * length of the longest valid (well-formed) parentheses substring. + */ + +/** + * @param {string} s + * @return {number} + */ +var longestValidParentheses = function(s) { + if (!s.length) { + return 0; + } + + const stack = [-1]; + let max = 0; + + for (let i = 0; i < s.length; i++) { + if (s[i] === '(') { + stack.push(i); + } else { + stack.pop(); + if (!stack.length) { + stack.push(i); + } else { + max = Math.max(max, i - stack[stack.length - 1]); + } + } + } + + return max; +}; diff --git a/README.md b/README.md index 117f8019..92bcef88 100644 --- a/README.md +++ b/README.md @@ -37,6 +37,7 @@ 29|[Divide Two Integers](./0029-divide-two-integers.js)|Medium| 30|[Substring with Concatenation of All Words](./0030-substring-with-concatenation-of-all-words.js)|Hard| 31|[Next Permutation](./0031-next-permutation.js)|Medium| +32|[Longest Valid Parentheses](./0032-longest-valid-parentheses.js)|Hard| 33|[Search in Rotated Sorted Array](./0033-search-in-rotated-sorted-array.js)|Medium| 34|[Find First and Last Position of Element in Sorted Array](./0034-find-first-and-last-position-of-element-in-sorted-array.js)|Medium| 35|[Search Insert Position](./0035-search-insert-position.js)|Easy| From 02d7600ba57504e23cbb438d55a0d236abbf5611 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 15 Jan 2023 17:45:25 -0600 Subject: [PATCH 332/919] Add solution #140 --- 0140-word-break-ii.js | 41 +++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 42 insertions(+) create mode 100644 0140-word-break-ii.js diff --git a/0140-word-break-ii.js b/0140-word-break-ii.js new file mode 100644 index 00000000..d8e00206 --- /dev/null +++ b/0140-word-break-ii.js @@ -0,0 +1,41 @@ +/** + * 140. Word Break II + * https://leetcode.com/problems/word-break-ii/ + * Difficulty: Hard + * + * Given a string s and a dictionary of strings wordDict, add spaces in s to + * construct a sentence where each word is a valid dictionary word. Return + * all such possible sentences in any order. + * + * Note that the same word in the dictionary may be reused multiple times in + * the segmentation. + */ + +/** + * @param {string} s + * @param {string[]} wordDict + * @return {string[]} + */ +var wordBreak = function(s, wordDict) { + const result = []; + backtrack(result, s, wordDict, ''); + return result; +}; + +function backtrack(result, s, wordDict, substr) { + if (!s.length) { + result.push(substr); + return; + } + + wordDict.forEach(word => { + if (s.length >= word.length && word === s.substring(0, word.length)) { + backtrack( + result, + s.substring(word.length), + wordDict, + substr.length ? `${substr} ${word}` : word, + ); + } + }); +} diff --git a/README.md b/README.md index 92bcef88..852215b2 100644 --- a/README.md +++ b/README.md @@ -90,6 +90,7 @@ 137|[Single Number II](./0137-single-number-ii.js)|Medium| 138|[Copy List with Random Pointer](./0138-copy-list-with-random-pointer.js)|Medium| 139|[Word Break](./0139-word-break.js)|Medium| +140|[Word Break II](./0140-word-break-ii.js)|Hard| 141|[Linked List Cycle](./0141-linked-list-cycle.js)|Easy| 142|[Linked List Cycle II](./0142-linked-list-cycle-ii.js)|Medium| 143|[Reorder List](./0143-reorder-list.js)|Medium| From 8b8cdaf266c323fd63468a6417d26cbdd0fc3b34 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 15 Jan 2023 17:46:58 -0600 Subject: [PATCH 333/919] Add solution #160 --- 0160-intersection-of-two-linked-lists.js | 40 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 41 insertions(+) create mode 100644 0160-intersection-of-two-linked-lists.js diff --git a/0160-intersection-of-two-linked-lists.js b/0160-intersection-of-two-linked-lists.js new file mode 100644 index 00000000..f005bebc --- /dev/null +++ b/0160-intersection-of-two-linked-lists.js @@ -0,0 +1,40 @@ +/** + * 160. Intersection of Two Linked Lists + * https://leetcode.com/problems/intersection-of-two-linked-lists/ + * Difficulty: Medium + * + * Given the heads of two singly linked-lists headA and headB, return the + * node at which the two lists intersect. If the two linked lists have no + * intersection at all, return null. + * + * For example, the following two linked lists begin to intersect at node c1: + */ + +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ + +/** + * @param {ListNode} headA + * @param {ListNode} headB + * @return {ListNode} + */ +var getIntersectionNode = function(headA, headB) { + if (!headA || !headB) { + return null; + } + + let a = headA; + let b = headB; + + while (a !== b) { + a = a === null ? headB : a.next; + b = b === null ? headA : b.next; + } + + return a; +}; diff --git a/README.md b/README.md index 852215b2..2ed45be0 100644 --- a/README.md +++ b/README.md @@ -99,6 +99,7 @@ 149|[Max Points on a Line](./0149-max-points-on-a-line.js)|Hard| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| +160|[Intersection of Two Linked Lists](./0160-intersection-of-two-linked-lists.js)|Medium| 167|[Two Sum II - Input Array Is Sorted](./0167-two-sum-ii-input-array-is-sorted.js)|Easy| 169|[Majority Element](./0169-majority-element.js)|Easy| 179|[Largest Number](./0179-largest-number.js)|Medium| From e776ebeee8f35ed5db6baaeb7126d7b4e9454cec Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 16 Jan 2023 17:41:27 -0600 Subject: [PATCH 334/919] Add solution #47 --- 0047-permutations-ii.js | 32 ++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 0047-permutations-ii.js diff --git a/0047-permutations-ii.js b/0047-permutations-ii.js new file mode 100644 index 00000000..cb3c1e35 --- /dev/null +++ b/0047-permutations-ii.js @@ -0,0 +1,32 @@ +/** + * 47. Permutations II + * https://leetcode.com/problems/permutations-ii/ + * Difficulty: Medium + * + * Given a collection of numbers, nums, that might contain duplicates, + * return all possible unique permutations in any order. + */ + +/** + * @param {number[]} nums + * @return {number[][]} + */ +var permuteUnique = function(nums) { + const result = new Set(); + backtrack(result, nums); + return Array.from(result).map(s => s.split(',')); +}; + +function backtrack(result, nums, order = []) { + if (!nums.length) { + result.add(order.join()); + } else { + for (let i = 0; i < nums.length; i++) { + backtrack( + result, + [...nums.slice(0, i), ...nums.slice(i + 1)], + [...order, nums[i]], + ); + } + } +} diff --git a/README.md b/README.md index 2ed45be0..1f0dd9f8 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,7 @@ 42|[Trapping Rain Water](./0042-trapping-rain-water.js)|Hard| 43|[Multiply Strings](./0043-multiply-strings.js)|Medium| 46|[Permutations](./0046-permutations.js)|Medium| +47|[Permutations II](./0047-permutations-ii.js)|Medium| 48|[Rotate Image](./0048-rotate-image.js)|Medium| 49|[Group Anagrams](./0049-group-anagrams.js)|Medium| 50|[Pow(x, n)](./0050-powx-n.js)|Medium| From 058070293d4dced210180302713afe5966b4c4a3 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 16 Jan 2023 17:44:14 -0600 Subject: [PATCH 335/919] Add solution #57 --- 0057-insert-interval.js | 43 +++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 44 insertions(+) create mode 100644 0057-insert-interval.js diff --git a/0057-insert-interval.js b/0057-insert-interval.js new file mode 100644 index 00000000..390f51f8 --- /dev/null +++ b/0057-insert-interval.js @@ -0,0 +1,43 @@ +/** + * 57. Insert Interval + * https://leetcode.com/problems/insert-interval/ + * Difficulty: Medium + * + * You are given an array of non-overlapping intervals intervals where + * intervals[i] = [starti, endi] represent the start and the end of the + * ith interval and intervals is sorted in ascending order by starti. + * You are also given an interval newInterval = [start, end] that + * represents the start and end of another interval. + * + * Insert newInterval into intervals such that intervals is still sorted + * in ascending order by starti and intervals still does not have any + * overlapping intervals (merge overlapping intervals if necessary). + * + * Return intervals after the insertion. + */ + +/** + * @param {number[][]} intervals + * @param {number[]} newInterval + * @return {number[][]} + */ +var insert = function(intervals, newInterval) { + const result = []; + + for (let i = 0; i < intervals.length; i++) { + if (newInterval[1] < intervals[i][0]) { + result.push(newInterval); + return [...result, ...intervals.slice(i)]; + } else if (newInterval[0] > intervals[i][1]) { + result.push(intervals[i]); + } else { + newInterval = [ + Math.min(newInterval[0], intervals[i][0]), + Math.max(newInterval[1], intervals[i][1]), + ]; + } + } + + result.push(newInterval); + return result; +}; diff --git a/README.md b/README.md index 1f0dd9f8..9060eb7a 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,7 @@ 50|[Pow(x, n)](./0050-powx-n.js)|Medium| 53|[Maximum Subarray](./0053-maximum-subarray.js)|Easy| 54|[Spiral Matrix](./0054-spiral-matrix.js)|Medium| +57|[Insert Interval](./0057-insert-interval.js)|Medium| 58|[Length of Last Word](./0058-length-of-last-word.js)|Easy| 62|[Unique Paths](./0062-unique-paths.js)|Medium| 66|[Plus One](./0066-plus-one.js)|Easy| From ea056c65e76df486c2928a99c76448d2b2e6afd2 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 16 Jan 2023 17:49:08 -0600 Subject: [PATCH 336/919] Add solution #1 --- 0001-two-sum.js | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/0001-two-sum.js b/0001-two-sum.js index 788e9d47..ae737454 100644 --- a/0001-two-sum.js +++ b/0001-two-sum.js @@ -3,9 +3,11 @@ * https://leetcode.com/problems/two-sum/ * Difficulty: Easy * - * Given an array of integers `nums` and an integer `target`, return indices of the two numbers such that they add up to `target`. + * Given an array of integers `nums` and an integer `target`, return indices + * of the two numbers such that they add up to `target`. * - * You may assume that each input would have exactly one solution, and you may not use the same element twice. + * You may assume that each input would have exactly one solution, and you + * may not use the same element twice. * * You can return the answer in any order. */ From bf013e5e2b6fcb849705d4b99b12f75b0c1a3720 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 16 Jan 2023 17:51:10 -0600 Subject: [PATCH 337/919] Add solution #31 --- 0031-next-permutation.js | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/0031-next-permutation.js b/0031-next-permutation.js index cc05f03c..f3039d8e 100644 --- a/0031-next-permutation.js +++ b/0031-next-permutation.js @@ -3,9 +3,11 @@ * https://leetcode.com/problems/next-permutation/ * Difficulty: Medium * - * Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. + * Implement next permutation, which rearranges numbers into the + * lexicographically next greater permutation of numbers. * - * If such an arrangement is not possible, it must rearrange it as the lowest possible order (i.e., sorted in ascending order). + * If such an arrangement is not possible, it must rearrange it + * as the lowest possible order (i.e., sorted in ascending order). * * The replacement must be in place and use only constant extra memory. */ @@ -14,7 +16,7 @@ * @param {number[]} nums * @return {void} Do not return anything, modify nums in-place instead. */ - var nextPermutation = function(nums) { +var nextPermutation = function(nums) { let i = nums.length - 2; while (i >= 0 && nums[i + 1] <= nums[i]) { @@ -47,4 +49,4 @@ function swap(nums, i, j) { const temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; -} \ No newline at end of file +} From 819b6e60823ed80b1e1706f233a830b35b5d61c6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 16 Jan 2023 17:51:38 -0600 Subject: [PATCH 338/919] Add solution #1360 --- 1360-number-of-days-between-two-dates.js | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/1360-number-of-days-between-two-dates.js b/1360-number-of-days-between-two-dates.js index b3a6ed22..734b0be9 100644 --- a/1360-number-of-days-between-two-dates.js +++ b/1360-number-of-days-between-two-dates.js @@ -5,7 +5,8 @@ * * Write a program to count the number of days between two dates. * - * The two dates are given as strings, their format is `YYYY-MM-DD` as shown in the examples. + * The two dates are given as strings, their format is `YYYY-MM-DD` + * as shown in the examples. */ /** @@ -13,6 +14,6 @@ * @param {string} date2 * @return {number} */ - var daysBetweenDates = function(date1, date2) { +var daysBetweenDates = function(date1, date2) { return Math.abs(new Date(date1) - new Date(date2)) / (24 * 60 * 60 * 1000); -}; \ No newline at end of file +}; From c8dcbd02b099563e2711f21488f6848c86b8a598 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 16 Jan 2023 18:25:00 -0600 Subject: [PATCH 339/919] Add solution #1519 --- ...des-in-the-sub-tree-with-the-same-label.js | 52 +++++++++++++++++++ README.md | 1 + 2 files changed, 53 insertions(+) create mode 100644 1519-number-of-nodes-in-the-sub-tree-with-the-same-label.js diff --git a/1519-number-of-nodes-in-the-sub-tree-with-the-same-label.js b/1519-number-of-nodes-in-the-sub-tree-with-the-same-label.js new file mode 100644 index 00000000..2a370d4f --- /dev/null +++ b/1519-number-of-nodes-in-the-sub-tree-with-the-same-label.js @@ -0,0 +1,52 @@ +/** + * 1519. Number of Nodes in the Sub-Tree With the Same Label + * https://leetcode.com/problems/number-of-nodes-in-the-sub-tree-with-the-same-label/ + * Difficulty: Medium + * + * You are given a tree (i.e. a connected, undirected graph that has no cycles) + * consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges. The + * root of the tree is the node 0, and each node of the tree has a label which + * is a lower-case character given in the string labels (i.e. The node with the + * number i has the label labels[i]). + * + * The edges array is given on the form edges[i] = [ai, bi], which means there + * is an edge between nodes ai and bi in the tree. + * + * Return an array of size n where ans[i] is the number of nodes in the subtree + * of the ith node which have the same label as node i. + * + * A subtree of a tree T is the tree consisting of a node in T and all of its + * descendant nodes. + */ + +/** + * @param {number} n + * @param {number[][]} edges + * @param {string} labels + * @return {number[]} + */ +var countSubTrees = function(n, edges, labels) { + const lookup = Array.from(Array(n), () => []); + const result = new Array(n).fill(0); + + edges.forEach(([x, y]) => { + lookup[x].push(y); + lookup[y].push(x); + }); + + function bfs(index, previous, chars = new Array(26).fill(0)) { + const key = labels.charCodeAt(index) - 97; + const count = chars[key]; + chars[key]++; + lookup[index].forEach(i => { + if (i !== previous) { + bfs(i, index, chars); + } + }); + result[index] = chars[key] - count; + } + + bfs(0, -1); + + return result; +}; diff --git a/README.md b/README.md index 9060eb7a..985c4398 100644 --- a/README.md +++ b/README.md @@ -285,6 +285,7 @@ 1502|[Can Make Arithmetic Progression From Sequence](./1502-can-make-arithmetic-progression-from-sequence.js)|Easy| 1507|[Reformat Date](./1507-reformat-date.js)|Easy| 1512|[Number of Good Pairs](./1512-number-of-good-pairs.js)|Easy| +1519|[Number of Nodes in the Sub-Tree With the Same Label](./1519-number-of-nodes-in-the-sub-tree-with-the-same-label.js)|Medium| 1528|[Shuffle String](./1528-shuffle-string.js)|Easy| 1550|[Three Consecutive Odds](./1550-three-consecutive-odds.js)|Easy| 1551|[Minimum Operations to Make Array Equal](./1551-minimum-operations-to-make-array-equal.js)|Medium| From 366a48a0f49bf558a1204d592b9c46d8b6ef22c5 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 17 Jan 2023 19:47:43 -0600 Subject: [PATCH 340/919] Add solution #926 --- 0926-flip-string-to-monotone-increasing.js | 33 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 0926-flip-string-to-monotone-increasing.js diff --git a/0926-flip-string-to-monotone-increasing.js b/0926-flip-string-to-monotone-increasing.js new file mode 100644 index 00000000..b1f3c14c --- /dev/null +++ b/0926-flip-string-to-monotone-increasing.js @@ -0,0 +1,33 @@ +/** + * 926. Flip String to Monotone Increasing + * https://leetcode.com/problems/flip-string-to-monotone-increasing/ + * Difficulty: Medium + * + * A binary string is monotone increasing if it consists of some number of 0's + * (possibly none), followed by some number of 1's (also possibly none). + * + * You are given a binary string s. You can flip s[i] changing it from 0 to 1 + * or from 1 to 0. + * + * Return the minimum number of flips to make s monotone increasing. + */ + +/** + * @param {string} s + * @return {number} + */ +var minFlipsMonoIncr = function(s) { + let result = 0; + let count = 0; + + for (const str of s) { + if (str == '1') { + count++; + } else if (str =='0' && count > 0) { + result++; + count--; + } + } + + return result; +}; diff --git a/README.md b/README.md index 985c4398..ac30a8c4 100644 --- a/README.md +++ b/README.md @@ -208,6 +208,7 @@ 916|[Word Subsets](./0916-word-subsets.js)|Medium| 922|[Sort Array By Parity II](./0922-sort-array-by-parity-ii.js)|Easy| 925|[Long Pressed Name](./0925-long-pressed-name.js)|Easy| +926|[Flip String to Monotone Increasing](./0926-flip-string-to-monotone-increasing.js)|Medium| 929|[Unique Email Addresses](./0929-unique-email-addresses.js)|Easy| 966|[Vowel Spellchecker](./0966-vowel-spellchecker.js)|Medium| 970|[Powerful Integers](./0970-powerful-integers.js)|Easy| From 337b0fc65d9a67b721f9e634f7f6d3bdae5c7a39 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 17 Jan 2023 19:48:49 -0600 Subject: [PATCH 341/919] Add solution #45 --- 0045-jump-game-ii.js | 37 +++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 38 insertions(+) create mode 100644 0045-jump-game-ii.js diff --git a/0045-jump-game-ii.js b/0045-jump-game-ii.js new file mode 100644 index 00000000..69cbd1f3 --- /dev/null +++ b/0045-jump-game-ii.js @@ -0,0 +1,37 @@ +/** + * 45. Jump Game II + * https://leetcode.com/problems/jump-game-ii/ + * Difficulty: Medium + * + * You are given a 0-indexed array of integers nums of length n. + * You are initially positioned at nums[0]. + * + * Each element nums[i] represents the maximum length of a forward + * jump from index i. In other words, if you are at nums[i], you + * can jump to any nums[i + j] where: + * - 0 <= j <= nums[i] and + * - i + j < n + * + * Return the minimum number of jumps to reach nums[n - 1]. + * The test cases are generated such that you can reach nums[n - 1]. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var jump = function(nums) { + let result = 0; + let max = 0; + let previous = 0; + + for (let index = 0; index < nums.length - 1; index++) { + max = Math.max(max, index + nums[index]); + if (index === previous) { + result++; + previous = max; + } + } + + return result; +}; diff --git a/README.md b/README.md index ac30a8c4..64e6808f 100644 --- a/README.md +++ b/README.md @@ -48,6 +48,7 @@ 41|[First Missing Positive](./0041-first-missing-positive.js)|Hard| 42|[Trapping Rain Water](./0042-trapping-rain-water.js)|Hard| 43|[Multiply Strings](./0043-multiply-strings.js)|Medium| +45|[Jump Game II](./0045-jump-game-ii.js)|Medium| 46|[Permutations](./0046-permutations.js)|Medium| 47|[Permutations II](./0047-permutations-ii.js)|Medium| 48|[Rotate Image](./0048-rotate-image.js)|Medium| From 72c4d48af70bb5080280e01f6954a75502affa6b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 17 Jan 2023 19:57:04 -0600 Subject: [PATCH 342/919] Add solution #37 --- 0037-sudoku-solver.js | 56 +++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 57 insertions(+) create mode 100644 0037-sudoku-solver.js diff --git a/0037-sudoku-solver.js b/0037-sudoku-solver.js new file mode 100644 index 00000000..bfbf0f8c --- /dev/null +++ b/0037-sudoku-solver.js @@ -0,0 +1,56 @@ +/** + * 37. Sudoku Solver + * https://leetcode.com/problems/sudoku-solver/ + * Difficulty: Hard + * + * Write a program to solve a Sudoku puzzle by filling the empty cells. + * + * A sudoku solution must satisfy all of the following rules: + * - Each of the digits 1-9 must occur exactly once in each row. + * - Each of the digits 1-9 must occur exactly once in each column. + * - Each of the digits 1-9 must occur exactly once in each of the + * 9 3x3 sub-boxes of the grid. + * - The '.' character indicates empty cells. + */ + +/** + * @param {character[][]} board + * @return {void} Do not return anything, modify board in-place instead. + */ +var solveSudoku = function(board) { + for (let i = 0; i < board.length; i++) { + for (let j = 0; j < board.length; j++) { + if (board[i][j] === '.') { + for (let k = 1; k < 10; k++) { + if (isValid(board, i, j, k.toString())) { + board[i][j] = k.toString(); + const solution = solveSudoku(board); + if (solution !== false) { + return solution; + } + board[i][j] = '.'; + } + } + return false; + } + } + } + + return board; +}; + +function isValid(board, i, j, k) { + for (let index = 0; index < board.length; index++) { + if (board[i][index] === k) return false; + if (board[index][j] === k) return false; + const [x, y] = [ + 3 * Math.floor(i / 3) + Math.floor(index / 3), + 3 * Math.floor(j / 3) + index % 3, + ]; + if (board[x][y] === k) { + return false; + } + } + + return true; +} diff --git a/README.md b/README.md index 64e6808f..67d9ba11 100644 --- a/README.md +++ b/README.md @@ -42,6 +42,7 @@ 34|[Find First and Last Position of Element in Sorted Array](./0034-find-first-and-last-position-of-element-in-sorted-array.js)|Medium| 35|[Search Insert Position](./0035-search-insert-position.js)|Easy| 36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium| +37|[Sudoku Solver](./0037-sudoku-solver.js)|Hard| 38|[Count and Say](./0038-count-and-say.js)|Medium| 39|[Combination Sum](./0039-combination-sum.js)|Medium| 40|[Combination Sum II](./0040-combination-sum-ii.js)|Medium| From b90660405f74fe1e2c1c19cd4d9969bea7abe7e5 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 18 Jan 2023 18:10:02 -0600 Subject: [PATCH 343/919] Add solution #2529 --- ...f-positive-integer-and-negative-integer.js | 24 +++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 2529-maximum-count-of-positive-integer-and-negative-integer.js diff --git a/2529-maximum-count-of-positive-integer-and-negative-integer.js b/2529-maximum-count-of-positive-integer-and-negative-integer.js new file mode 100644 index 00000000..b771cf85 --- /dev/null +++ b/2529-maximum-count-of-positive-integer-and-negative-integer.js @@ -0,0 +1,24 @@ +/** + * 2529. Maximum Count of Positive Integer and Negative Integer + * https://leetcode.com/problems/maximum-count-of-positive-integer-and-negative-integer/ + * Difficulty: Easy + * + * Given an array nums sorted in non-decreasing order, return the maximum + * between the number of positive integers and the number of negative integers. + * + * In other words, if the number of positive integers in nums is pos and the + * number of negative integers is neg, then return the maximum of pos and neg. + * + * Note that 0 is neither positive nor negative. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var maximumCount = function(nums) { + const result = nums.reduce(([neg = 0, pos = 0], n) => { + return [neg + (n < 0 ? 1 : 0), pos + (n > 0 ? 1 : 0)]; + }, []); + return Math.max(...result); +}; diff --git a/README.md b/README.md index 67d9ba11..938f354a 100644 --- a/README.md +++ b/README.md @@ -331,6 +331,7 @@ 2469|[Convert the Temperature](./2469-convert-the-temperature.js)|Easy| 2482|[Difference Between Ones and Zeros in Row and Column](./2482-difference-between-ones-and-zeros-in-row-and-column.js)|Medium| 2490|[Circular Sentence](./2490-circular-sentence.js)|Easy| +2529|[Maximum Count of Positive Integer and Negative Integer](./2529-maximum-count-of-positive-integer-and-negative-integer.js)|Easy| ## License From 7f93f48f73ca2dcf8852d57cf0fc4992f9f0be21 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 18 Jan 2023 18:11:22 -0600 Subject: [PATCH 344/919] Add solution #2535 --- ...n-element-sum-and-digit-sum-of-an-array.js | 23 +++++++++++++++++++ README.md | 1 + 2 files changed, 24 insertions(+) create mode 100644 2535-difference-between-element-sum-and-digit-sum-of-an-array.js diff --git a/2535-difference-between-element-sum-and-digit-sum-of-an-array.js b/2535-difference-between-element-sum-and-digit-sum-of-an-array.js new file mode 100644 index 00000000..8f6790f3 --- /dev/null +++ b/2535-difference-between-element-sum-and-digit-sum-of-an-array.js @@ -0,0 +1,23 @@ +/** + * 2535. Difference Between Element Sum and Digit Sum of an Array + * https://leetcode.com/problems/difference-between-element-sum-and-digit-sum-of-an-array/ + * Difficulty: Easy + * + * You are given a positive integer array nums: + * - The element sum is the sum of all the elements in nums. + * - The digit sum is the sum of all the digits (not necessarily distinct) + * that appear in nums. + * + * Return the absolute difference between the element sum and digit sum of nums. + * Note that the absolute difference between two integers x and y is defined + * as |x - y|. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var differenceOfSum = function(nums) { + const sum = input => input.reduce((sum, n) => sum + +n, 0); + return Math.abs(sum(nums) - sum(nums.join('').split(''))); +}; diff --git a/README.md b/README.md index 938f354a..8025358a 100644 --- a/README.md +++ b/README.md @@ -332,6 +332,7 @@ 2482|[Difference Between Ones and Zeros in Row and Column](./2482-difference-between-ones-and-zeros-in-row-and-column.js)|Medium| 2490|[Circular Sentence](./2490-circular-sentence.js)|Easy| 2529|[Maximum Count of Positive Integer and Negative Integer](./2529-maximum-count-of-positive-integer-and-negative-integer.js)|Easy| +2535|[Difference Between Element Sum and Digit Sum of an Array](./2535-difference-between-element-sum-and-digit-sum-of-an-array.js)|Easy| ## License From c8138867364fe092d127b831ee248a053f2a91a2 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 18 Jan 2023 18:12:23 -0600 Subject: [PATCH 345/919] Add solution #59 --- 0059-spiral-matrix-ii.js | 44 ++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 45 insertions(+) create mode 100644 0059-spiral-matrix-ii.js diff --git a/0059-spiral-matrix-ii.js b/0059-spiral-matrix-ii.js new file mode 100644 index 00000000..302411e6 --- /dev/null +++ b/0059-spiral-matrix-ii.js @@ -0,0 +1,44 @@ +/** + * 59. Spiral Matrix II + * https://leetcode.com/problems/spiral-matrix-ii/ + * Difficulty: Medium + * + * Given a positive integer n, generate an n x n matrix filled with + * elements from 1 to n2 in spiral order. + */ + +/** + * @param {number} n + * @return {number[][]} + */ +var generateMatrix = function(n) { + const result = Array.from(new Array(n), () => new Array(n).fill(0)); + let top = 0; + let right = n - 1; + let bottom = n - 1; + let left = 0; + + for (let count = 0; count < (n * n);) { + for (let i = left; i <= right; i++) { + result[top][i] = ++count; + } + top++; + + for (let i = top; i <= bottom; i++) { + result[i][right] = ++count; + } + right--; + + for (let i = right; top <= bottom && i >= left; i--) { + result[bottom][i] = ++count; + } + bottom--; + + for (let i = bottom; left <= right && i >= top; i--) { + result[i][left] = ++count; + } + left++; + } + + return result; +}; diff --git a/README.md b/README.md index 8025358a..cc613afc 100644 --- a/README.md +++ b/README.md @@ -59,6 +59,7 @@ 54|[Spiral Matrix](./0054-spiral-matrix.js)|Medium| 57|[Insert Interval](./0057-insert-interval.js)|Medium| 58|[Length of Last Word](./0058-length-of-last-word.js)|Easy| +59|[Spiral Matrix II](./0059-spiral-matrix-ii.js)|Medium| 62|[Unique Paths](./0062-unique-paths.js)|Medium| 66|[Plus One](./0066-plus-one.js)|Easy| 67|[Add Binary](./0067-add-binary.js)|Easy| From 0ce894c8adf78e78d7f232ebabab3031f219af76 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 19 Jan 2023 22:40:11 -0600 Subject: [PATCH 346/919] Add solution #491 --- 0491-non-decreasing-subsequences.js | 30 +++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 0491-non-decreasing-subsequences.js diff --git a/0491-non-decreasing-subsequences.js b/0491-non-decreasing-subsequences.js new file mode 100644 index 00000000..ac2b0eb8 --- /dev/null +++ b/0491-non-decreasing-subsequences.js @@ -0,0 +1,30 @@ +/** + * 491. Non-decreasing Subsequences + * https://leetcode.com/problems/non-decreasing-subsequences/ + * Difficulty: Medium + * + * Given an integer array nums, return all the different possible non-decreasing + * subsequences of the given array with at least two elements. You may return + * the answer in any order. + */ + +/** + * @param {number[]} nums + * @return {number[][]} + */ +var findSubsequences = function(nums) { + const result = new Set(); + backtrack(result, nums, 0, []); + return Array.from(result).map(s => s.split(',')); +}; + +function backtrack(result, nums, offset, order) { + if (order.length > 1) { + result.add(order.join()); + } + for (let index = offset; index < nums.length; index++) { + if (!(order[order.length - 1] > nums[index])) { + backtrack(result, nums, index + 1, [...order, nums[index]]); + } + } +} diff --git a/README.md b/README.md index cc613afc..6e27e9d3 100644 --- a/README.md +++ b/README.md @@ -160,6 +160,7 @@ 461|[Hamming Distance](./0461-hamming-distance.js)|Easy| 463|[Island Perimeter](./0463-island-perimeter.js)|Medium| 476|[Number Complement](./0476-number-complement.js)|Easy| +491|[Non-decreasing Subsequences](./0491-non-decreasing-subsequences.js)|Medium| 500|[Keyboard Row](./0500-keyboard-row.js)|Easy| 506|[Relative Ranks](./0506-relative-ranks.js)|Easy| 509|[Fibonacci Number](./0509-fibonacci-number.js)|Easy| From 6558275aa661fa87f3ce1dedb26a97c255414b13 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 19 Jan 2023 22:44:05 -0600 Subject: [PATCH 347/919] Add solution #492 --- 0492-construct-the-rectangle.js | 30 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 0492-construct-the-rectangle.js diff --git a/0492-construct-the-rectangle.js b/0492-construct-the-rectangle.js new file mode 100644 index 00000000..673c93d5 --- /dev/null +++ b/0492-construct-the-rectangle.js @@ -0,0 +1,30 @@ +/** + * 492. Construct the Rectangle + * https://leetcode.com/problems/construct-the-rectangle/ + * Difficulty: Easy + * + * A web developer needs to know how to design a web page's size. So, given + * a specific rectangular web page’s area, your job by now is to design a + * rectangular web page, whose length L and width W satisfy the following + * requirements: + * + * The area of the rectangular web page you designed must equal to the given + * target area. The width W should not be larger than the length L, which + * means L >= W. The difference between length L and width W should be as + * small as possible. + * + * Return an array [L, W] where L and W are the length and width of the web + * page you designed in sequence. + */ + +/** + * @param {number} area + * @return {number[]} + */ +var constructRectangle = function(area) { + let width = Math.floor(Math.sqrt(area)); + while (area % width) { + width--; + } + return [area / width, width]; +}; diff --git a/README.md b/README.md index 6e27e9d3..a26aa537 100644 --- a/README.md +++ b/README.md @@ -161,6 +161,7 @@ 463|[Island Perimeter](./0463-island-perimeter.js)|Medium| 476|[Number Complement](./0476-number-complement.js)|Easy| 491|[Non-decreasing Subsequences](./0491-non-decreasing-subsequences.js)|Medium| +492|[Construct the Rectangle](./0492-construct-the-rectangle.js)|Easy| 500|[Keyboard Row](./0500-keyboard-row.js)|Easy| 506|[Relative Ranks](./0506-relative-ranks.js)|Easy| 509|[Fibonacci Number](./0509-fibonacci-number.js)|Easy| From 8c6db71eb8c6561ced73c371f0dcd5a89a97fffa Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 19 Jan 2023 22:49:15 -0600 Subject: [PATCH 348/919] Add solution #563 --- 0563-binary-tree-tilt.js | 38 ++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 39 insertions(+) create mode 100644 0563-binary-tree-tilt.js diff --git a/0563-binary-tree-tilt.js b/0563-binary-tree-tilt.js new file mode 100644 index 00000000..173354ac --- /dev/null +++ b/0563-binary-tree-tilt.js @@ -0,0 +1,38 @@ +/** + * 563. Binary Tree Tilt + * https://leetcode.com/problems/binary-tree-tilt/ + * Difficulty: Easy + * + * Given the root of a binary tree, return the sum of every tree node's tilt. + * + * The tilt of a tree node is the absolute difference between the sum of all + * left subtree node values and all right subtree node values. If a node does + * not have a left child, then the sum of the left subtree node values is + * treated as 0. The rule is similar if the node does not have a right child. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number} + */ +var findTilt = function(root) { + const result = { val: 0 }; + dfs(root, result); + return result.val; +}; + +function dfs(root, tilt) { + if (!root) return 0; + const left = dfs(root.left, tilt); + const right = dfs(root.right, tilt); + tilt.val += Math.abs(left - right); + return root.val + left + right; +} diff --git a/README.md b/README.md index a26aa537..b7b8fef7 100644 --- a/README.md +++ b/README.md @@ -170,6 +170,7 @@ 542|[01 Matrix](./0542-01-matrix.js)|Medium| 551|[Student Attendance Record I](./0551-student-attendance-record-i.js)|Easy| 557|[Reverse Words in a String III](./0557-reverse-words-in-a-string-iii.js)|Easy| +563|[Binary Tree Tilt](./0563-binary-tree-tilt.js)|Easy| 565|[Array Nesting](./0565-array-nesting.js)|Medium| 566|[Reshape the Matrix](./0566-reshape-the-matrix.js)|Easy| 567|[Permutation in String](./0567-permutation-in-string.js)|Medium| From e0b9c93ac70f4c27ecfcfeac8cef8915713c0df0 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 19 Jan 2023 22:50:12 -0600 Subject: [PATCH 349/919] Add solution #884 --- 0884-uncommon-words-from-two-sentences.js | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/0884-uncommon-words-from-two-sentences.js b/0884-uncommon-words-from-two-sentences.js index 6ee36541..3c228191 100644 --- a/0884-uncommon-words-from-two-sentences.js +++ b/0884-uncommon-words-from-two-sentences.js @@ -1,16 +1,16 @@ /** * 884. Uncommon Words from Two Sentences - * https://leetcode.com/problems/uncommon-words-from-two-sentences/submissions/ + * https://leetcode.com/problems/uncommon-words-from-two-sentences/ * Difficulty: Easy * - * A sentence is a string of single-space separated words where each word consists - * only of lowercase letters. + * 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. + * 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. + * Given two sentences s1 and s2, return a list of all the uncommon words. + * You may return the answer in any order. */ /** @@ -20,7 +20,6 @@ */ var uncommonFromSentences = function(s1, s2) { const map = new Map(); - (s1 + ' ' + s2).split(/\s+/).forEach(s => map.set(s, (map.get(s) || 0) + 1)); return [...map].reduce((a, [k, c]) => c === 1 ? [...a, k] : a, []); }; From 19a4fd6b70a5438b747486963b9acff2b93005c7 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 19 Jan 2023 22:51:25 -0600 Subject: [PATCH 350/919] Add solution #1323 --- 1323-maximum-69-number.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/1323-maximum-69-number.js b/1323-maximum-69-number.js index a472a90e..de1e0bb8 100644 --- a/1323-maximum-69-number.js +++ b/1323-maximum-69-number.js @@ -1,6 +1,6 @@ /** * 1323. Maximum 69 Number - * https://leetcode.com/problems/maximum-69-number/submissions/ + * https://leetcode.com/problems/maximum-69-number/ * Difficulty: Easy * * Given a positive integer num consisting only of digits 6 and 9. @@ -13,6 +13,6 @@ * @param {number} num * @return {number} */ -var maximum69Number = function(num) { +var maximum69Number = function(num) { return +String(num).replace(6, 9); }; From f11a11c91a32c98f3d103cbe958e47048e5f9962 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 20 Jan 2023 19:25:03 -0600 Subject: [PATCH 351/919] Add solution #501 --- 0501-find-mode-in-binary-search-tree.js | 36 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 37 insertions(+) create mode 100644 0501-find-mode-in-binary-search-tree.js diff --git a/0501-find-mode-in-binary-search-tree.js b/0501-find-mode-in-binary-search-tree.js new file mode 100644 index 00000000..816be2bb --- /dev/null +++ b/0501-find-mode-in-binary-search-tree.js @@ -0,0 +1,36 @@ +/** + * 501. Find Mode in Binary Search Tree + * https://leetcode.com/problems/find-mode-in-binary-search-tree/ + * Difficulty: Easy + * + * Given the root of a binary search tree (BST) with duplicates, return all + * the mode(s) (i.e., the most frequently occurred element) in it. + * + * If the tree has more than one mode, return them in any order. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number[]} + */ +var findMode = function(root) { + const map = new Map(); + dfs(root); + + function dfs(root) { + if (!root) return 0; + map.set(root.val, (map.get(root.val) || 0) + 1); + [root.left, root.right].forEach(dfs); + } + + const max = Math.max(...map.values()); + return Array.from(map.keys()).filter(key => map.get(key) === max); +}; diff --git a/README.md b/README.md index b7b8fef7..578a0787 100644 --- a/README.md +++ b/README.md @@ -163,6 +163,7 @@ 491|[Non-decreasing Subsequences](./0491-non-decreasing-subsequences.js)|Medium| 492|[Construct the Rectangle](./0492-construct-the-rectangle.js)|Easy| 500|[Keyboard Row](./0500-keyboard-row.js)|Easy| +501|[Find Mode in Binary Search Tree](./0501-find-mode-in-binary-search-tree.js)|Easy| 506|[Relative Ranks](./0506-relative-ranks.js)|Easy| 509|[Fibonacci Number](./0509-fibonacci-number.js)|Easy| 520|[Detect Capital](./0520-detect-capital.js)|Easy| From 8a6204d461419e3f161e0c0399e7d01adc252d51 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 20 Jan 2023 19:26:39 -0600 Subject: [PATCH 352/919] Add solution #502 --- 0502-ipo.js | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 53 insertions(+) create mode 100644 0502-ipo.js diff --git a/0502-ipo.js b/0502-ipo.js new file mode 100644 index 00000000..03dcf73c --- /dev/null +++ b/0502-ipo.js @@ -0,0 +1,52 @@ +/** + * 502. IPO + * https://leetcode.com/problems/ipo/ + * Difficulty: Hard + * + * Suppose LeetCode will start its IPO soon. In order to sell a good price of + * its shares to Venture Capital, LeetCode would like to work on some projects + * to increase its capital before the IPO. Since it has limited resources, it + * can only finish at most k distinct projects before the IPO. Help LeetCode + * design the best way to maximize its total capital after finishing at most + * k distinct projects. + * + * You are given n projects where the ith project has a pure profit profits[i] + * and a minimum capital of capital[i] is needed to start it. + * + * Initially, you have w capital. When you finish a project, you will obtain + * its pure profit and the profit will be added to your total capital. + * + * Pick a list of at most k distinct projects from given projects to maximize + * your final capital, and return the final maximized capital. + * + * The answer is guaranteed to fit in a 32-bit signed integer. + */ + +/** + * @param {number} k + * @param {number} w + * @param {number[]} profits + * @param {number[]} capital + * @return {number} + */ +var findMaximizedCapital = function(k, w, profits, capital) { + const queue = new MinPriorityQueue(); + const descendingQueue = new MaxPriorityQueue(); + + for (let i = 0; i < capital.length; i++) { + queue.enqueue([capital[i], profits[i]], capital[i]); + } + + for (let i = 0; i < k; i++) { + while (!queue.isEmpty() && queue.front().element[0] <= w) { + const element = queue.dequeue().element; + descendingQueue.enqueue(element, element[1]); + } + if (descendingQueue.isEmpty()) { + return w; + } + w += descendingQueue.dequeue().element[1]; + } + + return w; +}; diff --git a/README.md b/README.md index 578a0787..0ed9ea7a 100644 --- a/README.md +++ b/README.md @@ -164,6 +164,7 @@ 492|[Construct the Rectangle](./0492-construct-the-rectangle.js)|Easy| 500|[Keyboard Row](./0500-keyboard-row.js)|Easy| 501|[Find Mode in Binary Search Tree](./0501-find-mode-in-binary-search-tree.js)|Easy| +502|[IPO](./0502-ipo.js)|Hard| 506|[Relative Ranks](./0506-relative-ranks.js)|Easy| 509|[Fibonacci Number](./0509-fibonacci-number.js)|Easy| 520|[Detect Capital](./0520-detect-capital.js)|Easy| From a2cd98b16900612cfe3e32563851186291ced0f8 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 20 Jan 2023 19:28:29 -0600 Subject: [PATCH 353/919] Add solution #503 --- 0503-next-greater-element-ii.js | 33 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 0503-next-greater-element-ii.js diff --git a/0503-next-greater-element-ii.js b/0503-next-greater-element-ii.js new file mode 100644 index 00000000..1f1513d0 --- /dev/null +++ b/0503-next-greater-element-ii.js @@ -0,0 +1,33 @@ +/** + * 503. Next Greater Element II + * https://leetcode.com/problems/next-greater-element-ii/ + * Difficulty: Medium + * + * Given a circular integer array nums (i.e., the next element of + * nums[nums.length - 1] is nums[0]), return the next greater number + * for every element in nums. + * + * The next greater number of a number x is the first greater number + * to its traversing-order next in the array, which means you could + * search circularly to find its next greater number. If it doesn't + * exist, return -1 for this number. + */ + +/** + * @param {number[]} nums + * @return {number[]} + */ +var nextGreaterElements = function(nums) { + const total = nums.length; + const result = new Array(total).fill(-1); + const stack = []; + + for (let i = 0; i < 2 * total; i++) { + while (stack.length && nums[i % total] > nums[stack[stack.length - 1]]) { + result[stack.pop()] = nums[i % total]; + } + stack.push(i % total); + } + + return result; +}; diff --git a/README.md b/README.md index 0ed9ea7a..10258505 100644 --- a/README.md +++ b/README.md @@ -165,6 +165,7 @@ 500|[Keyboard Row](./0500-keyboard-row.js)|Easy| 501|[Find Mode in Binary Search Tree](./0501-find-mode-in-binary-search-tree.js)|Easy| 502|[IPO](./0502-ipo.js)|Hard| +503|[Next Greater Element II](./0503-next-greater-element-ii.js)|Medium| 506|[Relative Ranks](./0506-relative-ranks.js)|Easy| 509|[Fibonacci Number](./0509-fibonacci-number.js)|Easy| 520|[Detect Capital](./0520-detect-capital.js)|Easy| From 74105b4bd874e62bc35102399af26668a74142af Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 20 Jan 2023 21:12:46 -0600 Subject: [PATCH 354/919] Add solution #4 --- 0004-median-of-two-sorted-arrays.js | 26 +------------------------- 1 file changed, 1 insertion(+), 25 deletions(-) diff --git a/0004-median-of-two-sorted-arrays.js b/0004-median-of-two-sorted-arrays.js index 88a7613a..fbb1aeb9 100644 --- a/0004-median-of-two-sorted-arrays.js +++ b/0004-median-of-two-sorted-arrays.js @@ -11,31 +11,6 @@ * You may assume nums1 and nums2 cannot be both empty. */ -/** - * @param {number[]} nums1 - * @param {number[]} nums2 - * @return {number} - */ -var findMedianSortedArrays = function(nums1, nums2) { - const total = nums1.length + nums2.length; - const limit = Math.floor(total / 2) + 1; - let i = 0, j = 0, prev, last - - while (i + j < limit) { - if (last !== undefined) { - prev = last; - } - if (nums1[i] < nums2[j] || j === nums2.length) { - last = nums1[i++]; - } else { - last = nums2[j++]; - } - } - - return total % 2 === 0 ? (prev + last) / 2 : last; -}; - -// shorter/readable alternative with higher time complexity: /** * @param {number[]} nums1 * @param {number[]} nums2 @@ -44,6 +19,7 @@ var findMedianSortedArrays = function(nums1, nums2) { var findMedianSortedArrays = function(nums1, nums2) { const sorted = [...nums1, ...nums2].sort((a, b) => a - b); const index = Math.floor((sorted.length - 1) / 2); + return sorted.length % 2 === 0 ? (sorted[index] + sorted[index + 1]) / 2 : sorted[index]; From d11e6a55b2bf34305af933b0fc729213c773d458 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 20 Jan 2023 21:15:52 -0600 Subject: [PATCH 355/919] Add solution #5 --- 0005-longest-palindromic-substring.js | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/0005-longest-palindromic-substring.js b/0005-longest-palindromic-substring.js index d15b8499..86dee903 100644 --- a/0005-longest-palindromic-substring.js +++ b/0005-longest-palindromic-substring.js @@ -14,10 +14,11 @@ var longestPalindrome = function(s) { let result = ''; for (let i = 0; i < s.length; i++) { - let palindrome1 = getExtendedPalindrome(s, i, i); - let palindrome2 = getExtendedPalindrome(s, i, i + 1); - let longerPalindrome = palindrome1.length > palindrome2.length - ? palindrome1 : palindrome2; + const palindrome1 = getExtendedPalindrome(s, i, i); + const palindrome2 = getExtendedPalindrome(s, i, i + 1); + const longerPalindrome = palindrome1.length > palindrome2.length + ? palindrome1 + : palindrome2; if (longerPalindrome.length > result.length) { result = longerPalindrome; From 3f9955029c643be25bf998d44e59ce1aa74cd926 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 21 Jan 2023 20:34:27 -0600 Subject: [PATCH 356/919] Add solution #504 --- 0504-base-7.js | 15 +++++++++++++++ README.md | 1 + 2 files changed, 16 insertions(+) create mode 100644 0504-base-7.js diff --git a/0504-base-7.js b/0504-base-7.js new file mode 100644 index 00000000..d29d7585 --- /dev/null +++ b/0504-base-7.js @@ -0,0 +1,15 @@ +/** + * 504. Base 7 + * https://leetcode.com/problems/base-7/ + * Difficulty: Easy + * + * Given an integer num, return a string of its base 7 representation. + */ + +/** + * @param {number} num + * @return {string} + */ +var convertToBase7 = function(num) { + return num.toString(7); +}; diff --git a/README.md b/README.md index 10258505..1bb7da8c 100644 --- a/README.md +++ b/README.md @@ -166,6 +166,7 @@ 501|[Find Mode in Binary Search Tree](./0501-find-mode-in-binary-search-tree.js)|Easy| 502|[IPO](./0502-ipo.js)|Hard| 503|[Next Greater Element II](./0503-next-greater-element-ii.js)|Medium| +504|[Base 7](./0504-base-7.js)|Easy| 506|[Relative Ranks](./0506-relative-ranks.js)|Easy| 509|[Fibonacci Number](./0509-fibonacci-number.js)|Easy| 520|[Detect Capital](./0520-detect-capital.js)|Easy| From d62f8342ebf1bb1753da084c6bf2a404b8aa5be5 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 21 Jan 2023 20:38:56 -0600 Subject: [PATCH 357/919] Add solution #93 --- 0093-restore-ip-addresses.js | 42 ++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 43 insertions(+) create mode 100644 0093-restore-ip-addresses.js diff --git a/0093-restore-ip-addresses.js b/0093-restore-ip-addresses.js new file mode 100644 index 00000000..b3b68854 --- /dev/null +++ b/0093-restore-ip-addresses.js @@ -0,0 +1,42 @@ +/** + * 93. Restore IP Addresses + * https://leetcode.com/problems/restore-ip-addresses/ + * Difficulty: Medium + * + * A valid IP address consists of exactly four integers separated by single + * dots. Each integer is between 0 and 255 (inclusive) and cannot have + * leading zeros. + * + * For example, "0.1.2.201" and "192.168.1.1" are valid IP addresses, but + * "0.011.255.245", "192.168.1.312" and "192.168@1.1" are invalid IP addresses. + * + * Given a string s containing only digits, return all possible valid IP + * addresses that can be formed by inserting dots into s. You are not allowed + * to reorder or remove any digits in s. You may return the valid IP addresses + * in any order. + */ + +/** + * @param {string} s + * @return {string[]} + */ +var restoreIpAddresses = function(s) { + return backtrack([], s); +}; + +function backtrack(order, string, result = []) { + const isValid = s => +s <= 255 && `${+s}` === s; + + if (order.length === 3 && isValid(string)) { + result.push([...order, string].join('.')); + } else { + for (let index = 1; index < 4; index++) { + const sliced = string.slice(0, index); + if (isValid(sliced)) { + backtrack([...order, sliced], string.slice(index), result); + } + } + } + + return result; +} diff --git a/README.md b/README.md index 1bb7da8c..1a869b94 100644 --- a/README.md +++ b/README.md @@ -73,6 +73,7 @@ 83|[Remove Duplicates from Sorted List](./0083-remove-duplicates-from-sorted-list.js)|Easy| 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| 90|[Subsets II](./0090-subsets-ii.js)|Medium| +93|[Restore IP Addresses](./0093-restore-ip-addresses.js)|Medium| 94|[Binary Tree Inorder Traversal](./0094-binary-tree-inorder-traversal.js)|Easy| 98|[Validate Binary Search Tree](./0098-validate-binary-search-tree.js)|Medium| 100|[Same Tree](./0100-same-tree.js)|Easy| From a52f1c92a70d411d6e145d78df7e869ed15b29e6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 21 Jan 2023 20:43:58 -0600 Subject: [PATCH 358/919] Add solution #44 --- 0044-wildcard-matching.js | 50 +++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 51 insertions(+) create mode 100644 0044-wildcard-matching.js diff --git a/0044-wildcard-matching.js b/0044-wildcard-matching.js new file mode 100644 index 00000000..5f2f2f29 --- /dev/null +++ b/0044-wildcard-matching.js @@ -0,0 +1,50 @@ +/** + * 44. Wildcard Matching + * https://leetcode.com/problems/wildcard-matching/ + * Difficulty: Hard + * + * Given an input string (s) and a pattern (p), implement wildcard pattern + * matching with support for '?' and '*' where: + * + * - '?' Matches any single character. + * - '*' Matches any sequence of characters (including the empty sequence). + * + * The matching should cover the entire input string (not partial). + */ + +/** + * @param {string} s + * @param {string} p + * @return {boolean} + */ +var isMatch = function(s, p) { + let i = 0; + let j = 0; + let start = -1; + let offset = -1; + + while (i < s.length) { + if (j < p.length && s[i] === p[j] || p[j] === '?') { + i++; + j++; + } else if (j < p.length && p[j] === '*') { + start = j; + offset = i; + j++; + } else if (start === -1) { + return false; + } else { + j = start + 1; + i = offset + 1; + offset = i; + } + } + + for (let index = j; index < p.length; index++) { + if (p[index] !== '*') { + return false; + } + } + + return true; +}; diff --git a/README.md b/README.md index 1a869b94..a73fe86e 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,7 @@ 41|[First Missing Positive](./0041-first-missing-positive.js)|Hard| 42|[Trapping Rain Water](./0042-trapping-rain-water.js)|Hard| 43|[Multiply Strings](./0043-multiply-strings.js)|Medium| +44|[Wildcard Matching](./0044-wildcard-matching.js)|Hard| 45|[Jump Game II](./0045-jump-game-ii.js)|Medium| 46|[Permutations](./0046-permutations.js)|Medium| 47|[Permutations II](./0047-permutations-ii.js)|Medium| From d10ab86d9abf29d91670cdb5dd8a5f53ba7c32fa Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 22 Jan 2023 16:52:13 -0600 Subject: [PATCH 359/919] Add solution #131 --- 0131-palindrome-partitioning.js | 46 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 47 insertions(+) create mode 100644 0131-palindrome-partitioning.js diff --git a/0131-palindrome-partitioning.js b/0131-palindrome-partitioning.js new file mode 100644 index 00000000..fabe3875 --- /dev/null +++ b/0131-palindrome-partitioning.js @@ -0,0 +1,46 @@ +/** + * 131. Palindrome Partitioning + * https://leetcode.com/problems/palindrome-partitioning/ + * Difficulty: Medium + * + * Given a string s, partition s such that every substring of the partition + * is a palindrome. Return all possible palindrome partitioning of s. + */ + +/** + * @param {string} s + * @return {string[][]} + */ +var partition = function(s) { + return backtrack([], s); +}; + +function backtrack(order, string, result = []) { + if (!string.length) { + result.push(order); + } + + for (let index = 1; index <= string.length; index++) { + const sliced = string.slice(0, index); + if (isPalindrome(sliced)) { + backtrack([...order, sliced], string.slice(index), result); + } + } + + return result; +} + +function isPalindrome(input) { + let right = input.length - 1; + let left = 0; + + while (left < right) { + if (input[left] !== input[right]) { + return false; + } + left++; + right--; + } + + return true; +} diff --git a/README.md b/README.md index a73fe86e..ea0a9e8c 100644 --- a/README.md +++ b/README.md @@ -90,6 +90,7 @@ 121|[Best Time to Buy and Sell Stock](./0121-best-time-to-buy-and-sell-stock.js)|Easy| 125|[Valid Palindrome](./0125-valid-palindrome.js)|Easy| 128|[Longest Consecutive Sequence](./0128-longest-consecutive-sequence.js)|Medium| +131|[Palindrome Partitioning](./0131-palindrome-partitioning.js)|Medium| 133|[Clone Graph](./0133-clone-graph.js)|Medium| 134|[Gas Station](./0134-gas-station.js)|Medium| 135|[Candy](./0135-candy.js)|Hard| From b5cfbd27accb8cf6b8b3add06ad6964b584120fe Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 22 Jan 2023 16:53:15 -0600 Subject: [PATCH 360/919] Add solution #51 --- 0051-n-queens.js | 42 ++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 43 insertions(+) create mode 100644 0051-n-queens.js diff --git a/0051-n-queens.js b/0051-n-queens.js new file mode 100644 index 00000000..38aa53c4 --- /dev/null +++ b/0051-n-queens.js @@ -0,0 +1,42 @@ +/** + * 51. N-Queens + * https://leetcode.com/problems/n-queens/ + * Difficulty: Hard + * + * The n-queens puzzle is the problem of placing n queens on an n x n + * chessboard such that no two queens attack each other. + * + * Given an integer n, return all distinct solutions to the n-queens + * puzzle. You may return the answer in any order. + * + * Each solution contains a distinct board configuration of the n-queens' + * placement, where 'Q' and '.' both indicate a queen and an empty space, + * respectively. + */ + +/** + * @param {number} n + * @return {string[][]} + */ +var solveNQueens = function(n) { + const result = []; + backtrack(result, n); + return result; +}; + +function backtrack(result, n, board = [], size = 0) { + if (n === size) { + result.push(board.map(s => `${'.'.repeat(s)}Q${'.'.repeat(n - s - 1)}`)); + } else { + for (let rows = 0; rows < n; rows++) { + const isValid = !board.some((i, j) => { + return i === rows || i === rows + size - j || i === rows - size + j; + }); + if (isValid) { + board.push(rows); + backtrack(result, n, board, size + 1); + board.pop(); + } + } + } +} diff --git a/README.md b/README.md index ea0a9e8c..d28f1e53 100644 --- a/README.md +++ b/README.md @@ -56,6 +56,7 @@ 48|[Rotate Image](./0048-rotate-image.js)|Medium| 49|[Group Anagrams](./0049-group-anagrams.js)|Medium| 50|[Pow(x, n)](./0050-powx-n.js)|Medium| +51|[N-Queens](./0051-n-queens.js)|Hard| 53|[Maximum Subarray](./0053-maximum-subarray.js)|Easy| 54|[Spiral Matrix](./0054-spiral-matrix.js)|Medium| 57|[Insert Interval](./0057-insert-interval.js)|Medium| From 1925117a74afe8c6d69a9f9208f7a51c387858b8 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 22 Jan 2023 16:54:44 -0600 Subject: [PATCH 361/919] Add solution #52 --- 0052-n-queens-ii.js | 38 ++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 39 insertions(+) create mode 100644 0052-n-queens-ii.js diff --git a/0052-n-queens-ii.js b/0052-n-queens-ii.js new file mode 100644 index 00000000..ea1ac8b5 --- /dev/null +++ b/0052-n-queens-ii.js @@ -0,0 +1,38 @@ +/** + * 52. N-Queens II + * https://leetcode.com/problems/n-queens-ii/ + * Difficulty: Hard + * + * The n-queens puzzle is the problem of placing n queens on an n x n + * chessboard such that no two queens attack each other. + * + * Given an integer n, return the number of distinct solutions to the + * n-queens puzzle. + */ + +/** + * @param {number} n + * @return {number} + */ +var totalNQueens = function(n) { + const result = []; + backtrack(result, n); + return result.length; +}; + +function backtrack(result, n, board = [], size = 0) { + if (n === size) { + result.push(board.map(s => `${'.'.repeat(s)}Q${'.'.repeat(n - s - 1)}`)); + } else { + for (let rows = 0; rows < n; rows++) { + const isValid = !board.some((i, j) => { + return i === rows || i === rows + size - j || i === rows - size + j; + }); + if (isValid) { + board.push(rows); + backtrack(result, n, board, size + 1); + board.pop(); + } + } + } +} diff --git a/README.md b/README.md index d28f1e53..4fda511e 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,7 @@ 49|[Group Anagrams](./0049-group-anagrams.js)|Medium| 50|[Pow(x, n)](./0050-powx-n.js)|Medium| 51|[N-Queens](./0051-n-queens.js)|Hard| +52|[N-Queens II](./0052-n-queens-ii.js)|Hard| 53|[Maximum Subarray](./0053-maximum-subarray.js)|Easy| 54|[Spiral Matrix](./0054-spiral-matrix.js)|Medium| 57|[Insert Interval](./0057-insert-interval.js)|Medium| From 98e3d24e6540ce01cbc4ff903ac224016b77f9b9 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 22 Jan 2023 16:58:19 -0600 Subject: [PATCH 362/919] Add solution #20 --- 0020-valid-parentheses.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/0020-valid-parentheses.js b/0020-valid-parentheses.js index bc7a1752..8073e964 100644 --- a/0020-valid-parentheses.js +++ b/0020-valid-parentheses.js @@ -3,8 +3,8 @@ * https://leetcode.com/problems/valid-parentheses/ * Difficulty: Easy * - * Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', - * determine if the input string is valid. + * Given a string s containing just the characters '(', ')', '{', '}', + * '[' and ']', determine if the input string is valid. * * An input string is valid if: * - Open brackets must be closed by the same type of brackets. @@ -17,10 +17,10 @@ */ var isValid = function(s) { const map = { - '(': ')', - '[': ']', - '{': '}' - } + '(': ')', + '[': ']', + '{': '}', + }; const stack = []; for (let i = 0; i < s.length; i++) { From f214a4ef9908775886182a7d54fdb20744e7a90f Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 22 Jan 2023 17:00:31 -0600 Subject: [PATCH 363/919] Add solution #12 --- 0012-integer-to-roman.js | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/0012-integer-to-roman.js b/0012-integer-to-roman.js index b4e941f6..a7872336 100644 --- a/0012-integer-to-roman.js +++ b/0012-integer-to-roman.js @@ -3,7 +3,8 @@ * https://leetcode.com/problems/integer-to-roman/ * Difficulty: Medium * - * Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D` and `M`. + * Roman numerals are represented by seven different symbols: `I`, `V`, `X`, + * `L`, `C`, `D` and `M`. * * Symbol Value * I 1 @@ -14,13 +15,15 @@ * D 500 * M 1000 * - * For example, `2` is written as `II` in Roman numeral, just two one's added together. `12` is written - * as `XII`, which is simply `X + II`. The number `27` is written as `XXVII`, which is `XX + V + II`. + * For example, `2` is written as `II` in Roman numeral, just two one's + * added together. `12` is written as `XII`, which is simply `X + II`. + * The number `27` is written as `XXVII`, which is `XX + V + II`. * - * Roman numerals are usually written largest to smallest from left to right. However, the numeral for - * four is not `IIII`. Instead, the number four is written as `IV`. Because the one is before the five - * we subtract it making four. The same principle applies to the number nine, which is written as `IX`. - * There are six instances where subtraction is used: + * Roman numerals are usually written largest to smallest from left to right. + * However, the numeral for four is not `IIII`. Instead, the number four is + * written as `IV`. Because the one is before the five we subtract it making + * four. The same principle applies to the number nine, which is written as + * `IX`. There are six instances where subtraction is used: * * - `I` can be placed before `V (5)` and `X (10)` to make 4 and 9. * - `X` can be placed before `L (50)` and `C (100)` to make 40 and 90. @@ -34,7 +37,10 @@ * @return {string} */ var intToRoman = function(num) { - const map = { M: 1000, CM: 900, D: 500, CD: 400, C: 100, XC: 90, L: 50, XL: 40, X: 10, IX: 9, V: 5, IV: 4, I: 1 }; + const map = { + M: 1000, CM: 900, D: 500, CD: 400, C: 100, XC: 90, + L: 50, XL: 40, X: 10, IX: 9, V: 5, IV: 4, I: 1 + }; return Object.entries(map).reduce((result, [letter, n]) => { result += letter.repeat(Math.floor(num / n)); From 98903f4ecf698ee661283eea293cc66dd6e78a42 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 22 Jan 2023 17:01:44 -0600 Subject: [PATCH 364/919] Add solution #13 --- 0013-roman-to-integer.js | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/0013-roman-to-integer.js b/0013-roman-to-integer.js index 14593317..acbb22f8 100644 --- a/0013-roman-to-integer.js +++ b/0013-roman-to-integer.js @@ -3,7 +3,8 @@ * https://leetcode.com/problems/roman-to-integer/ * Difficulty: Easy * - * Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D` and `M`. + * Roman numerals are represented by seven different symbols: `I`, `V`, `X`, + * `L`, `C`, `D` and `M`. * * Symbol Value * I 1 @@ -14,13 +15,15 @@ * D 500 * M 1000 * - * For example, `2` is written as `II` in Roman numeral, just two one's added together. `12` is written - * as `XII`, which is simply `X + II`. The number `27` is written as `XXVII`, which is `XX + V + II`. + * For example, `2` is written as `II` in Roman numeral, just two one's + * added together. `12` is written as `XII`, which is simply `X + II`. + * The number `27` is written as `XXVII`, which is `XX + V + II`. * - * Roman numerals are usually written largest to smallest from left to right. However, the numeral for - * four is not `IIII`. Instead, the number four is written as `IV`. Because the one is before the five - * we subtract it making four. The same principle applies to the number nine, which is written as `IX`. - * There are six instances where subtraction is used: + * Roman numerals are usually written largest to smallest from left to right. + * However, the numeral for four is not `IIII`. Instead, the number four is + * written as `IV`. Because the one is before the five we subtract it making + * four. The same principle applies to the number nine, which is written as + * `IX`. There are six instances where subtraction is used: * * - `I` can be placed before `V (5)` and `X (10)` to make 4 and 9. * - `X` can be placed before `L (50)` and `C (100)` to make 40 and 90. From d4d98c7fa5b37ceeebc27a31839d28299d076f0a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 23 Jan 2023 22:21:17 -0600 Subject: [PATCH 365/919] Add solution #95 --- 0095-unique-binary-search-trees-ii.js | 37 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 38 insertions(+) create mode 100644 0095-unique-binary-search-trees-ii.js diff --git a/0095-unique-binary-search-trees-ii.js b/0095-unique-binary-search-trees-ii.js new file mode 100644 index 00000000..1e4c7928 --- /dev/null +++ b/0095-unique-binary-search-trees-ii.js @@ -0,0 +1,37 @@ +/** + * 95. Unique Binary Search Trees II + * https://leetcode.com/problems/unique-binary-search-trees-ii/ + * Difficulty: Medium + * + * Given an integer n, return all the structurally unique BST's (binary search + * trees), which has exactly n nodes of unique values from 1 to n. Return the + * answer in any order. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {number} n + * @return {TreeNode[]} + */ +var generateTrees = function(n) { + return backtrack(n); +}; + +function backtrack(n, j = 1, k = n, result = []) { + for (let index = j; index <= k; index++) { + for (const left of backtrack(n, j, index - 1)) { + for (const right of backtrack(n, index + 1, k)) { + result.push({ val: index, left, right }); + } + } + } + + return n ? result.length ? result : [null] : []; +} diff --git a/README.md b/README.md index 4fda511e..92d7f414 100644 --- a/README.md +++ b/README.md @@ -78,6 +78,7 @@ 90|[Subsets II](./0090-subsets-ii.js)|Medium| 93|[Restore IP Addresses](./0093-restore-ip-addresses.js)|Medium| 94|[Binary Tree Inorder Traversal](./0094-binary-tree-inorder-traversal.js)|Easy| +95|[Unique Binary Search Trees II](./0095-unique-binary-search-trees-ii.js)|Medium| 98|[Validate Binary Search Tree](./0098-validate-binary-search-tree.js)|Medium| 100|[Same Tree](./0100-same-tree.js)|Easy| 101|[Symmetric Tree](./0101-symmetric-tree.js)|Easy| From 0025dc667c0e8bee2604e063818fc0d978ff7ef6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 23 Jan 2023 22:27:20 -0600 Subject: [PATCH 366/919] Add solution #96 --- 0096-unique-binary-search-trees.js | 20 ++++++++++++++++++++ README.md | 1 + 2 files changed, 21 insertions(+) create mode 100644 0096-unique-binary-search-trees.js diff --git a/0096-unique-binary-search-trees.js b/0096-unique-binary-search-trees.js new file mode 100644 index 00000000..ff3ae0ca --- /dev/null +++ b/0096-unique-binary-search-trees.js @@ -0,0 +1,20 @@ +/** + * 96. Unique Binary Search Trees + * https://leetcode.com/problems/unique-binary-search-trees/ + * Difficulty: Medium + * + * Given an integer n, return the number of structurally unique BST's (binary + * search trees) which has exactly n nodes of unique values from 1 to n. + */ + +/** + * @param {number} n + * @return {number} + */ +var numTrees = function(n) { + return traverse(2 * n) / (traverse(n + 1) * traverse(n)); +}; + +function traverse(n) { + return n <= 0 ? 1 : n * traverse(n - 1); +} diff --git a/README.md b/README.md index 92d7f414..dc4414b8 100644 --- a/README.md +++ b/README.md @@ -79,6 +79,7 @@ 93|[Restore IP Addresses](./0093-restore-ip-addresses.js)|Medium| 94|[Binary Tree Inorder Traversal](./0094-binary-tree-inorder-traversal.js)|Easy| 95|[Unique Binary Search Trees II](./0095-unique-binary-search-trees-ii.js)|Medium| +96|[Unique Binary Search Trees](./0096-unique-binary-search-trees.js)|Medium| 98|[Validate Binary Search Tree](./0098-validate-binary-search-tree.js)|Medium| 100|[Same Tree](./0100-same-tree.js)|Easy| 101|[Symmetric Tree](./0101-symmetric-tree.js)|Easy| From babbec94aabe452db9799c597bad44f6d9e3eeca Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 23 Jan 2023 22:29:32 -0600 Subject: [PATCH 367/919] Add solution #371 --- 0371-sum-of-two-integers.js | 24 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 0371-sum-of-two-integers.js diff --git a/0371-sum-of-two-integers.js b/0371-sum-of-two-integers.js new file mode 100644 index 00000000..0930fd60 --- /dev/null +++ b/0371-sum-of-two-integers.js @@ -0,0 +1,24 @@ +/** + * 371. Sum of Two Integers + * https://leetcode.com/problems/sum-of-two-integers/ + * Difficulty: Medium + * + * Given two integers a and b, return the sum of the two integers + * without using the operators + and -. + */ + +/** + * @param {number} a + * @param {number} b + * @return {number} + */ +var getSum = function(a, b) { + const sum = a ^ b; + const carry = (a & b) << 1; + + if (!carry) { + return sum; + } + + return getSum(sum, carry); +}; diff --git a/README.md b/README.md index dc4414b8..54455888 100644 --- a/README.md +++ b/README.md @@ -154,6 +154,7 @@ 349|[Intersection of Two Arrays](./0349-intersection-of-two-arrays.js)|Easy| 350|[Intersection of Two Arrays II](./0350-intersection-of-two-arrays-ii.js)|Easy| 367|[Valid Perfect Square](./0367-valid-perfect-square.js)|Easy| +371|[Sum of Two Integers](./0371-sum-of-two-integers.js)|Medium| 374|[Guess Number Higher or Lower](./0374-guess-number-higher-or-lower.js)|Medium| 383|[Ransom Note](./0383-ransom-note.js)|Easy| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| From 14484f7796a3d518a19b42c1a03883da85c9ce0a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 24 Jan 2023 22:52:24 -0600 Subject: [PATCH 368/919] Add solution #372 --- 0372-super-pow.js | 31 +++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 0372-super-pow.js diff --git a/0372-super-pow.js b/0372-super-pow.js new file mode 100644 index 00000000..a2ce4af2 --- /dev/null +++ b/0372-super-pow.js @@ -0,0 +1,31 @@ +/** + * 372. Super Pow + * https://leetcode.com/problems/super-pow/ + * Difficulty: Medium + * + * Your task is to calculate ab mod 1337 where a is a positive integer and b + * is an extremely large positive integer given in the form of an array. + */ + +/** + * @param {number} a + * @param {number[]} b + * @return {number} + */ +var superPow = function(a, b) { + return helper(BigInt(a), BigInt(b.join('')), 1337n); +}; + +function helper(a, b, mod) { + let r = 1n; + + while (b > 0n) { + if (b % 2n == 1) { + r = r * a % mod; + } + b >>= 1n; + a = a * a % mod; + } + + return Number(r); +}; diff --git a/README.md b/README.md index 54455888..d7942fe0 100644 --- a/README.md +++ b/README.md @@ -155,6 +155,7 @@ 350|[Intersection of Two Arrays II](./0350-intersection-of-two-arrays-ii.js)|Easy| 367|[Valid Perfect Square](./0367-valid-perfect-square.js)|Easy| 371|[Sum of Two Integers](./0371-sum-of-two-integers.js)|Medium| +372|[Super Pow](./0372-super-pow.js)|Medium| 374|[Guess Number Higher or Lower](./0374-guess-number-higher-or-lower.js)|Medium| 383|[Ransom Note](./0383-ransom-note.js)|Easy| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| From ec8550b8e2f3740d208c999971e0dd3a6e548fe6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 24 Jan 2023 22:59:01 -0600 Subject: [PATCH 369/919] Add solution #86 --- 0086-partition-list.js | 31 +++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 0086-partition-list.js diff --git a/0086-partition-list.js b/0086-partition-list.js new file mode 100644 index 00000000..b461d5b7 --- /dev/null +++ b/0086-partition-list.js @@ -0,0 +1,31 @@ +/** + * 86. Partition List + * https://leetcode.com/problems/partition-list/ + * Difficulty: Medium + * + * Given the head of a linked list and a value x, partition it such that + * all nodes less than x come before nodes greater than or equal to x. + * + * You should preserve the original relative order of the nodes in each + * of the two partitions. + */ + +/** + * @param {ListNode} head + * @param {number} x + * @return {ListNode} + */ +var partition = function(head, x) { + const result = []; + const stack = []; + + while (head) { + const target = head.val >= x ? result : stack; + target.push(head.val); + head = head.next; + } + + return [...stack, ...result].reverse().reduce((a, b) => { + return new ListNode(b, a); + }, null); +}; diff --git a/README.md b/README.md index d7942fe0..77457b62 100644 --- a/README.md +++ b/README.md @@ -74,6 +74,7 @@ 78|[Subsets](./0078-subsets.js)|Medium| 80|[Remove Duplicates from Sorted Array II](./0080-remove-duplicates-from-sorted-array-ii.js)|Medium| 83|[Remove Duplicates from Sorted List](./0083-remove-duplicates-from-sorted-list.js)|Easy| +86|[Partition List](./0086-partition-list.js)|Medium| 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| 90|[Subsets II](./0090-subsets-ii.js)|Medium| 93|[Restore IP Addresses](./0093-restore-ip-addresses.js)|Medium| From 1f82cdf3a05f919d21bcb1b8ed5d513e9c90e5c0 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 24 Jan 2023 23:55:17 -0600 Subject: [PATCH 370/919] Add solution #64 --- 0064-minimum-path-sum.js | 28 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 29 insertions(+) create mode 100644 0064-minimum-path-sum.js diff --git a/0064-minimum-path-sum.js b/0064-minimum-path-sum.js new file mode 100644 index 00000000..9c5303a4 --- /dev/null +++ b/0064-minimum-path-sum.js @@ -0,0 +1,28 @@ +/** + * 64. Minimum Path Sum + * https://leetcode.com/problems/minimum-path-sum/ + * Difficulty: Medium + * + * Given a m x n grid filled with non-negative numbers, find a path from + * top left to bottom right, which minimizes the sum of all numbers along + * its path. + * + * Note: You can only move either down or right at any point in time. + */ + +/** + * @param {number[][]} grid + * @return {number} + */ +var minPathSum = function(grid) { + for (let i = 0; i < grid.length; i++) { + for (let j = 0; j < grid[0].length; j++) { + if (i === 0 && j === 0) grid[i][j] = grid[i][j]; + else if (i === 0 && j !== 0) grid[i][j] = grid[i][j] + grid[i][j - 1]; + else if (i !== 0 && j === 0) grid[i][j] = grid[i][j] + grid[i - 1][j]; + else grid[i][j] = grid[i][j] + Math.min(grid[i - 1][j], grid[i][j - 1]); + } + } + + return grid[grid.length - 1][grid[0].length - 1]; +}; diff --git a/README.md b/README.md index 77457b62..c470c394 100644 --- a/README.md +++ b/README.md @@ -64,6 +64,7 @@ 58|[Length of Last Word](./0058-length-of-last-word.js)|Easy| 59|[Spiral Matrix II](./0059-spiral-matrix-ii.js)|Medium| 62|[Unique Paths](./0062-unique-paths.js)|Medium| +64|[Minimum Path Sum](./0064-minimum-path-sum.js)|Medium| 66|[Plus One](./0066-plus-one.js)|Easy| 67|[Add Binary](./0067-add-binary.js)|Easy| 69|[Sqrt(x)](./0069-sqrtx.js)|Medium| From 36e83f9da526e7e85271abf3131a395c19bb7eba Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 25 Jan 2023 21:32:24 -0600 Subject: [PATCH 371/919] Add solution #55 --- 0055-jump-game.js | 28 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 29 insertions(+) create mode 100644 0055-jump-game.js diff --git a/0055-jump-game.js b/0055-jump-game.js new file mode 100644 index 00000000..7e605bec --- /dev/null +++ b/0055-jump-game.js @@ -0,0 +1,28 @@ +/** + * 55. Jump Game + * https://leetcode.com/problems/jump-game/ + * Difficulty: Medium + * + * You are given an integer array nums. You are initially positioned at the + * array's first index, and each element in the array represents your maximum + * jump length at that position. + * + * Return true if you can reach the last index, or false otherwise. + */ + +/** + * @param {number[]} nums + * @return {boolean} + */ +var canJump = function(nums) { + let max = nums[0]; + + for (let i = 1; i < nums.length; i++) { + if (max < i) { + return false; + } + max = Math.max(nums[i] + i, max); + } + + return true; +}; diff --git a/README.md b/README.md index c470c394..e8290f43 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,7 @@ 52|[N-Queens II](./0052-n-queens-ii.js)|Hard| 53|[Maximum Subarray](./0053-maximum-subarray.js)|Easy| 54|[Spiral Matrix](./0054-spiral-matrix.js)|Medium| +55|[Jump Game](./0055-jump-game.js)|Medium| 57|[Insert Interval](./0057-insert-interval.js)|Medium| 58|[Length of Last Word](./0058-length-of-last-word.js)|Easy| 59|[Spiral Matrix II](./0059-spiral-matrix-ii.js)|Medium| From e4732ff7116a7a4b940ac80f218d549bf6372202 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 25 Jan 2023 21:41:35 -0600 Subject: [PATCH 372/919] Add solution #56 --- 0056-merge-intervals.js | 29 +++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 30 insertions(+) create mode 100644 0056-merge-intervals.js diff --git a/0056-merge-intervals.js b/0056-merge-intervals.js new file mode 100644 index 00000000..74b2e02f --- /dev/null +++ b/0056-merge-intervals.js @@ -0,0 +1,29 @@ +/** + * 56. Merge Intervals + * https://leetcode.com/problems/merge-intervals/ + * Difficulty: Medium + * + * Given an array of intervals where intervals[i] = [starti, endi], merge all + * overlapping intervals, and return an array of the non-overlapping intervals + * that cover all the intervals in the input. + */ + +/** + * @param {number[][]} intervals + * @return {number[][]} + */ +var merge = function(intervals) { + intervals.sort(([a], [b]) => a - b); + + const result = [intervals.shift()]; + intervals.forEach(([first, second]) => { + const [, last] = result[result.length - 1]; + if (first <= last) { + result[result.length - 1][1] = Math.max(second, last); + } else { + result.push([first, second]); + } + }); + + return result; +}; diff --git a/README.md b/README.md index e8290f43..7e7830b9 100644 --- a/README.md +++ b/README.md @@ -61,6 +61,7 @@ 53|[Maximum Subarray](./0053-maximum-subarray.js)|Easy| 54|[Spiral Matrix](./0054-spiral-matrix.js)|Medium| 55|[Jump Game](./0055-jump-game.js)|Medium| +56|[Merge Intervals](./0056-merge-intervals.js)|Medium| 57|[Insert Interval](./0057-insert-interval.js)|Medium| 58|[Length of Last Word](./0058-length-of-last-word.js)|Easy| 59|[Spiral Matrix II](./0059-spiral-matrix-ii.js)|Medium| From e0145e548875fde7be1029d41952f4105b61a50c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 25 Jan 2023 21:45:10 -0600 Subject: [PATCH 373/919] Add solution #405 --- 0405-convert-a-number-to-hexadecimal.js | 32 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 0405-convert-a-number-to-hexadecimal.js diff --git a/0405-convert-a-number-to-hexadecimal.js b/0405-convert-a-number-to-hexadecimal.js new file mode 100644 index 00000000..bfa94f51 --- /dev/null +++ b/0405-convert-a-number-to-hexadecimal.js @@ -0,0 +1,32 @@ +/** + * 405. Convert a Number to Hexadecimal + * https://leetcode.com/problems/convert-a-number-to-hexadecimal/ + * Difficulty: Easy + * + * Given an integer num, return a string representing its hexadecimal + * representation. For negative integers, two’s complement method is used. + * + * All the letters in the answer string should be lowercase characters, + * and there should not be any leading zeros in the answer except for + * the zero itself. + * + * Note: You are not allowed to use any built-in library method to directly + * solve this problem. + */ + +/** + * @param {number} num + * @return {string} + */ +var toHex = function(num) { + if (num === 0) { + return num.toString(); + } + const words = '0123456789abcdef'; + let result = ''; + while (num !== 0) { + result = words[num & 0xf] + result; + num >>>= 4; + } + return result; +}; diff --git a/README.md b/README.md index 7e7830b9..546f17be 100644 --- a/README.md +++ b/README.md @@ -163,6 +163,7 @@ 374|[Guess Number Higher or Lower](./0374-guess-number-higher-or-lower.js)|Medium| 383|[Ransom Note](./0383-ransom-note.js)|Easy| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| +405|[Convert a Number to Hexadecimal](./0405-convert-a-number-to-hexadecimal.js)|Easy| 414|[Third Maximum Number](./0414-third-maximum-number.js)|Easy| 419|[Battleships in a Board](./0419-battleships-in-a-board.js)|Medium| 442|[Find All Duplicates in an Array](./0442-find-all-duplicates-in-an-array.js)|Medium| From f44be804d85fea5ac2d64d002f79fb6ac3f9137e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 1 Feb 2023 22:31:58 -0600 Subject: [PATCH 374/919] Add solution #412 --- 0412-fizz-buzz.js | 22 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 0412-fizz-buzz.js diff --git a/0412-fizz-buzz.js b/0412-fizz-buzz.js new file mode 100644 index 00000000..ed737dd8 --- /dev/null +++ b/0412-fizz-buzz.js @@ -0,0 +1,22 @@ +/** + * 412. Fizz Buzz + * https://leetcode.com/problems/fizz-buzz/ + * Difficulty: Easy + * + * Given an integer n, return a string array answer (1-indexed) where: + * - answer[i] == "FizzBuzz" if i is divisible by 3 and 5. + * - answer[i] == "Fizz" if i is divisible by 3. + * - answer[i] == "Buzz" if i is divisible by 5. + * - answer[i] == i (as a string) if none of the above conditions are true. + */ + +/** + * @param {number} n + * @return {string[]} + */ +var fizzBuzz = function(n) { + return Array.from(new Array(n), (_, i) => i + 1).map(i => + i % 3 === 0 && i % 5 === 0 + ? 'FizzBuzz' : i % 3 === 0 ? 'Fizz' : i % 5 === 0 ? 'Buzz' : String(i) + ); +}; diff --git a/README.md b/README.md index 546f17be..e4416d6d 100644 --- a/README.md +++ b/README.md @@ -164,6 +164,7 @@ 383|[Ransom Note](./0383-ransom-note.js)|Easy| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| 405|[Convert a Number to Hexadecimal](./0405-convert-a-number-to-hexadecimal.js)|Easy| +412|[Fizz Buzz](./0412-fizz-buzz.js)|Easy| 414|[Third Maximum Number](./0414-third-maximum-number.js)|Easy| 419|[Battleships in a Board](./0419-battleships-in-a-board.js)|Medium| 442|[Find All Duplicates in an Array](./0442-find-all-duplicates-in-an-array.js)|Medium| From 946698eb7aa2b5df6f62c6183a0486f56a4f1f07 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 1 Feb 2023 22:47:03 -0600 Subject: [PATCH 375/919] Add solution #99 --- 0099-recover-binary-search-tree.js | 43 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 44 insertions(+) create mode 100644 0099-recover-binary-search-tree.js diff --git a/0099-recover-binary-search-tree.js b/0099-recover-binary-search-tree.js new file mode 100644 index 00000000..d226cb44 --- /dev/null +++ b/0099-recover-binary-search-tree.js @@ -0,0 +1,43 @@ +/** + * 99. Recover Binary Search Tree + * https://leetcode.com/problems/recover-binary-search-tree/ + * Difficulty: Medium + * + * You are given the root of a binary search tree (BST), where the values + * of exactly two nodes of the tree were swapped by mistake. Recover the + * tree without changing its structure. + */ + +/** + * 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 {void} Do not return anything, modify root in-place instead. + */ +var recoverTree = function(root) { + let [previous, small, large] = [null, null, null]; + + dfs(root); + [large.val, small.val] = [small.val, large.val]; + + function dfs(root) { + if (!root) return; + dfs(root.left); + if (previous != null && previous.val > root.val) { + small = root; + if (!large) { + large = previous; + } else { + return false; + } + } + previous = root; + dfs(root.right); + } +}; diff --git a/README.md b/README.md index e4416d6d..0ed777c3 100644 --- a/README.md +++ b/README.md @@ -85,6 +85,7 @@ 95|[Unique Binary Search Trees II](./0095-unique-binary-search-trees-ii.js)|Medium| 96|[Unique Binary Search Trees](./0096-unique-binary-search-trees.js)|Medium| 98|[Validate Binary Search Tree](./0098-validate-binary-search-tree.js)|Medium| +99|[Recover Binary Search Tree](./0099-recover-binary-search-tree.js)|Medium| 100|[Same Tree](./0100-same-tree.js)|Easy| 101|[Symmetric Tree](./0101-symmetric-tree.js)|Easy| 102|[Binary Tree Level Order Traversal](./0102-binary-tree-level-order-traversal.js)|Medium| From b9aa4d7d6e32e0ca1b6bce0f9d028d02bfb5acb9 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 1 Feb 2023 22:56:10 -0600 Subject: [PATCH 376/919] Add solution #168 --- 0168-excel-sheet-column-title.js | 19 +++++++++++++++++++ README.md | 1 + 2 files changed, 20 insertions(+) create mode 100644 0168-excel-sheet-column-title.js diff --git a/0168-excel-sheet-column-title.js b/0168-excel-sheet-column-title.js new file mode 100644 index 00000000..575c0729 --- /dev/null +++ b/0168-excel-sheet-column-title.js @@ -0,0 +1,19 @@ +/** + * 168. Excel Sheet Column Title + * https://leetcode.com/problems/excel-sheet-column-title/ + * Difficulty: Easy + * + * Given an integer columnNumber, return its corresponding column + * title as it appears in an Excel sheet. + */ + +/** + * @param {number} columnNumber + * @return {string} + */ +var convertToTitle = function(columnNumber) { + const n = columnNumber - 1; + return n >= 0 && n < 26 + ? String.fromCharCode(65 + n) + : convertToTitle(parseInt(n / 26)) + convertToTitle((n % 26) + 1); +}; diff --git a/README.md b/README.md index 0ed777c3..090a42fe 100644 --- a/README.md +++ b/README.md @@ -118,6 +118,7 @@ 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| 160|[Intersection of Two Linked Lists](./0160-intersection-of-two-linked-lists.js)|Medium| 167|[Two Sum II - Input Array Is Sorted](./0167-two-sum-ii-input-array-is-sorted.js)|Easy| +168|[Excel Sheet Column Title](./0168-excel-sheet-column-title.js)|Easy| 169|[Majority Element](./0169-majority-element.js)|Easy| 179|[Largest Number](./0179-largest-number.js)|Medium| 189|[Rotate Array](./0189-rotate-array.js)|Medium| From ef213ed4d8bfa53cf55746c4486cf0c8b15ef485 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 2 Feb 2023 18:49:02 -0600 Subject: [PATCH 377/919] Add solution #81 --- 0081-search-in-rotated-sorted-array-ii.js | 28 +++++++++++++++++++++++ README.md | 1 + 2 files changed, 29 insertions(+) create mode 100644 0081-search-in-rotated-sorted-array-ii.js diff --git a/0081-search-in-rotated-sorted-array-ii.js b/0081-search-in-rotated-sorted-array-ii.js new file mode 100644 index 00000000..2bafa642 --- /dev/null +++ b/0081-search-in-rotated-sorted-array-ii.js @@ -0,0 +1,28 @@ +/** + * 81. Search in Rotated Sorted Array II + * https://leetcode.com/problems/search-in-rotated-sorted-array-ii/ + * Difficulty: Medium + * + * There is an integer array nums sorted in non-decreasing order (not + * necessarily with distinct values). + * + * Before being passed to your function, nums is rotated at an unknown + * pivot index k (0 <= k < nums.length) such that the resulting array + * is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] + * (0-indexed). For example, [0,1,2,4,4,4,5,6,6,7] might be rotated at pivot + * index 5 and become [4,5,6,6,7,0,1,2,4,4]. + * + * Given the array nums after the rotation and an integer target, return + * true if target is in nums, or false if it is not in nums. + * + * You must decrease the overall operation steps as much as possible. + */ + +/** + * @param {number[]} nums + * @param {number} target + * @return {boolean} + */ +var search = function(nums, target) { + return nums.includes(target); +}; diff --git a/README.md b/README.md index 090a42fe..1df9ea1b 100644 --- a/README.md +++ b/README.md @@ -76,6 +76,7 @@ 77|[Combinations](./0077-combinations.js)|Medium| 78|[Subsets](./0078-subsets.js)|Medium| 80|[Remove Duplicates from Sorted Array II](./0080-remove-duplicates-from-sorted-array-ii.js)|Medium| +81|[Search in Rotated Sorted Array II](./0081-search-in-rotated-sorted-array-ii.js)|Medium| 83|[Remove Duplicates from Sorted List](./0083-remove-duplicates-from-sorted-list.js)|Easy| 86|[Partition List](./0086-partition-list.js)|Medium| 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| From 55f0d8062c6e020a3f7de1d07996b2889bef9897 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 2 Feb 2023 19:10:18 -0600 Subject: [PATCH 378/919] Add solution #82 --- 0082-remove-duplicates-from-sorted-list-ii.js | 37 +++++++++++++++++++ README.md | 1 + 2 files changed, 38 insertions(+) create mode 100644 0082-remove-duplicates-from-sorted-list-ii.js diff --git a/0082-remove-duplicates-from-sorted-list-ii.js b/0082-remove-duplicates-from-sorted-list-ii.js new file mode 100644 index 00000000..8bccf70f --- /dev/null +++ b/0082-remove-duplicates-from-sorted-list-ii.js @@ -0,0 +1,37 @@ +/** + * 82. Remove Duplicates from Sorted List II + * https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/ + * Difficulty: Medium + * + * Given the head of a sorted linked list, delete all nodes that have duplicate + * numbers, leaving only distinct numbers from the original list. Return the + * linked list sorted as well. + */ + +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ +var deleteDuplicates = function(head) { + const result = new ListNode(); + let previous = null; + let tail = result; + + while (head) { + if (head.val !== head.next?.val && head.val !== previous) { + tail.next = new ListNode(head.val); + tail = tail.next; + } + previous = head.val; + head = head.next; + } + + return result.next; +}; diff --git a/README.md b/README.md index 1df9ea1b..4ddf6a5c 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,7 @@ 78|[Subsets](./0078-subsets.js)|Medium| 80|[Remove Duplicates from Sorted Array II](./0080-remove-duplicates-from-sorted-array-ii.js)|Medium| 81|[Search in Rotated Sorted Array II](./0081-search-in-rotated-sorted-array-ii.js)|Medium| +82|[Remove Duplicates from Sorted List II](./0082-remove-duplicates-from-sorted-list-ii.js)|Medium| 83|[Remove Duplicates from Sorted List](./0083-remove-duplicates-from-sorted-list.js)|Easy| 86|[Partition List](./0086-partition-list.js)|Medium| 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| From 2c9c4f747db970e6ae0c3329890b7d29052fb89e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 2 Feb 2023 19:12:20 -0600 Subject: [PATCH 379/919] Add solution #83 --- 0083-remove-duplicates-from-sorted-list.js | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/0083-remove-duplicates-from-sorted-list.js b/0083-remove-duplicates-from-sorted-list.js index 1bd5a0ad..b1e7de59 100644 --- a/0083-remove-duplicates-from-sorted-list.js +++ b/0083-remove-duplicates-from-sorted-list.js @@ -20,17 +20,14 @@ */ var deleteDuplicates = function(head) { const result = new ListNode(); - const set = new Set(); let tail = result; while (head) { - if (!set.has(head.val)) { + if (head.val !== head.next?.val) { tail.next = new ListNode(head.val); tail = tail.next; } - - set.add(head.val); - + previous = head.val; head = head.next; } From c4c473137934ffa6c63ae8dab3e8bf2e3161d538 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 2 Feb 2023 19:19:26 -0600 Subject: [PATCH 380/919] Add solution #89 --- 0089-gray-code.js | 27 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 28 insertions(+) create mode 100644 0089-gray-code.js diff --git a/0089-gray-code.js b/0089-gray-code.js new file mode 100644 index 00000000..766f0620 --- /dev/null +++ b/0089-gray-code.js @@ -0,0 +1,27 @@ +/** + * 89. Gray Code + * https://leetcode.com/problems/gray-code/ + * Difficulty: Medium + * + * An n-bit gray code sequence is a sequence of 2n integers where: + * - Every integer is in the inclusive range [0, 2n - 1], + * - The first integer is 0, + * - An integer appears no more than once in the sequence, + * - The binary representation of every pair of adjacent integers differs + * by exactly one bit, and + * - The binary representation of the first and last integers differs by + * exactly one bit. + * Given an integer n, return any valid n-bit gray code sequence. + */ + +/** + * @param {number} n + * @return {number[]} + */ +var grayCode = function(n) { + const result = [0]; + for (let i = 0; i < n; i++) { + result.push(...result.map((v) => v | 1 << i).reverse()); + } + return result; +}; diff --git a/README.md b/README.md index 4ddf6a5c..6760b1d0 100644 --- a/README.md +++ b/README.md @@ -81,6 +81,7 @@ 83|[Remove Duplicates from Sorted List](./0083-remove-duplicates-from-sorted-list.js)|Easy| 86|[Partition List](./0086-partition-list.js)|Medium| 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| +89|[Gray Code](./0089-gray-code.js)|Medium| 90|[Subsets II](./0090-subsets-ii.js)|Medium| 93|[Restore IP Addresses](./0093-restore-ip-addresses.js)|Medium| 94|[Binary Tree Inorder Traversal](./0094-binary-tree-inorder-traversal.js)|Easy| From b571521c1650f8b976474386997465dc1e82f069 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 1 Jan 2025 17:41:40 -0600 Subject: [PATCH 381/919] Add solution #3402 --- ...ons-to-make-columns-strictly-increasing.js | 32 +++++++++++++++++++ README.md | 3 +- 2 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 3402-minimum-operations-to-make-columns-strictly-increasing.js diff --git a/3402-minimum-operations-to-make-columns-strictly-increasing.js b/3402-minimum-operations-to-make-columns-strictly-increasing.js new file mode 100644 index 00000000..18b4b600 --- /dev/null +++ b/3402-minimum-operations-to-make-columns-strictly-increasing.js @@ -0,0 +1,32 @@ +/** + * 3402. Minimum Operations to Make Columns Strictly Increasing + * https://leetcode.com/problems/minimum-operations-to-make-columns-strictly-increasing + * Difficulty: Easy + * + * You are given a m x n matrix grid consisting of non-negative integers. + * + * In one operation, you can increment the value of any grid[i][j] by 1. + * + * Return the minimum number of operations needed to make all columns of grid strictly increasing. + */ + +/** + * @param {number[][]} grid + * @return {number} + */ +var minimumOperations = function(grid) { + let count = 0; + + for (let i = 1; i < grid.length; i++) { + for (let j = 0; j < grid[i].length; j++) { + const [previous, current] = [grid[i - 1][j], grid[i][j]]; + if (current <= previous) { + const operations = previous - current + 1; + grid[i][j] = operations + current; + count += operations; + } + } + } + + return count; +}; diff --git a/README.md b/README.md index 6760b1d0..4a36f53f 100644 --- a/README.md +++ b/README.md @@ -361,9 +361,10 @@ 2490|[Circular Sentence](./2490-circular-sentence.js)|Easy| 2529|[Maximum Count of Positive Integer and Negative Integer](./2529-maximum-count-of-positive-integer-and-negative-integer.js)|Easy| 2535|[Difference Between Element Sum and Digit Sum of an Array](./2535-difference-between-element-sum-and-digit-sum-of-an-array.js)|Easy| +3402|[Minimum Operations to Make Columns Strictly Increasing](./3402-minimum-operations-to-make-columns-strictly-increasing.js)|Easy| ## License [MIT License](https://opensource.org/licenses/MIT) -Copyright (c) 2019-2023 [Josh Crozier](https://joshcrozier.com) +Copyright (c) 2019-2025 [Josh Crozier](https://joshcrozier.com) From 2eb3f2425da230a0d1ca1057f932b4ac1eff0a08 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 1 Jan 2025 18:32:42 -0600 Subject: [PATCH 382/919] Add solution #3396 --- ...ions-to-make-elements-in-array-distinct.js | 29 +++++++++++++++++++ README.md | 1 + 2 files changed, 30 insertions(+) create mode 100644 3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js diff --git a/3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js b/3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js new file mode 100644 index 00000000..ea954b6d --- /dev/null +++ b/3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js @@ -0,0 +1,29 @@ +/** + * 3396. Minimum Number of Operations to Make Elements in Array Distinct + * https://leetcode.com/problems/minimum-number-of-operations-to-make-elements-in-array-distinct/ + * Difficulty: Easy + * + * You are given an integer array nums. You need to ensure that the elements in the array are + * distinct. To achieve this, you can perform the following operation any number of times: + * - Remove 3 elements from the beginning of the array. If the array has fewer than 3 elements, + * remove all remaining elements. + * Note that an empty array is considered to have distinct elements. Return the minimum number + * of operations needed to make the elements in the array distinct. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var minimumOperations = function(nums) { + const unique = new Set(); + + for (let i = nums.length - 1; i > -1; i--) { + if (unique.has(nums[i])) { + return Math.ceil((i + 1) / 3); + } + unique.add(nums[i]); + } + + return 0; +}; diff --git a/README.md b/README.md index 4a36f53f..db5a9095 100644 --- a/README.md +++ b/README.md @@ -361,6 +361,7 @@ 2490|[Circular Sentence](./2490-circular-sentence.js)|Easy| 2529|[Maximum Count of Positive Integer and Negative Integer](./2529-maximum-count-of-positive-integer-and-negative-integer.js)|Easy| 2535|[Difference Between Element Sum and Digit Sum of an Array](./2535-difference-between-element-sum-and-digit-sum-of-an-array.js)|Easy| +3396|[Minimum Number of Operations to Make Elements in Array Distinct](./3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy| 3402|[Minimum Operations to Make Columns Strictly Increasing](./3402-minimum-operations-to-make-columns-strictly-increasing.js)|Easy| ## License From 0189ee790f35f4216685c82305767e8811f120b7 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 1 Jan 2025 22:52:08 -0600 Subject: [PATCH 383/919] Add solution #3397 --- ...r-of-distinct-elements-after-operations.js | 31 +++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 3397-maximum-number-of-distinct-elements-after-operations.js diff --git a/3397-maximum-number-of-distinct-elements-after-operations.js b/3397-maximum-number-of-distinct-elements-after-operations.js new file mode 100644 index 00000000..96665e90 --- /dev/null +++ b/3397-maximum-number-of-distinct-elements-after-operations.js @@ -0,0 +1,31 @@ +/** + * 3397. Maximum Number of Distinct Elements After Operations + * https://leetcode.com/problems/maximum-number-of-distinct-elements-after-operations/ + * Difficulty: Medium + * + * You are given an integer array nums and an integer k. + * + * You are allowed to perform the following operation on each element of the array at most once: + * - Add an integer in the range [-k, k] to the element. + * + * Return the maximum possible number of distinct elements in nums after performing the operations. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var maxDistinctElements = function(nums, k) { + nums.sort((a, b) => a - b); + let last = nums[0] - k; + let count = 1; + + for (let i = 1; i < nums.length; i++) { + if (last + 1 > nums[i] + k) continue; + last = Math.max(last + 1, nums[i] - k); + count++; + } + + return count; +}; diff --git a/README.md b/README.md index db5a9095..2c70f6ef 100644 --- a/README.md +++ b/README.md @@ -362,6 +362,7 @@ 2529|[Maximum Count of Positive Integer and Negative Integer](./2529-maximum-count-of-positive-integer-and-negative-integer.js)|Easy| 2535|[Difference Between Element Sum and Digit Sum of an Array](./2535-difference-between-element-sum-and-digit-sum-of-an-array.js)|Easy| 3396|[Minimum Number of Operations to Make Elements in Array Distinct](./3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy| +3397|[Maximum Number of Distinct Elements After Operations](./3397-maximum-number-of-distinct-elements-after-operations.js)|Medium| 3402|[Minimum Operations to Make Columns Strictly Increasing](./3402-minimum-operations-to-make-columns-strictly-increasing.js)|Easy| ## License From 64ad37e5666b5d503da780075dad73301bdfb930 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 2 Jan 2025 15:09:48 -0600 Subject: [PATCH 384/919] Add solution #3392 --- ...arrays-of-length-three-with-a-condition.js | 22 +++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 3392-count-subarrays-of-length-three-with-a-condition.js diff --git a/3392-count-subarrays-of-length-three-with-a-condition.js b/3392-count-subarrays-of-length-three-with-a-condition.js new file mode 100644 index 00000000..a18fa0b8 --- /dev/null +++ b/3392-count-subarrays-of-length-three-with-a-condition.js @@ -0,0 +1,22 @@ +/** + * 3392. Count Subarrays of Length Three With a Condition + * https://leetcode.com/problems/count-subarrays-of-length-three-with-a-condition/ + * Difficulty: Easy + * + * Given an integer array nums, return the number of subarrays of length 3 such that + * the sum of the first and third numbers equals exactly half of the second number. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var countSubarrays = function(nums) { + let count = 0; + for (let i = 0; i < nums.length - 2; i++) { + if (nums[i] + nums[i + 2] === nums[i + 1] / 2) { + count++; + } + } + return count; +}; diff --git a/README.md b/README.md index 2c70f6ef..cdf8bd47 100644 --- a/README.md +++ b/README.md @@ -361,6 +361,7 @@ 2490|[Circular Sentence](./2490-circular-sentence.js)|Easy| 2529|[Maximum Count of Positive Integer and Negative Integer](./2529-maximum-count-of-positive-integer-and-negative-integer.js)|Easy| 2535|[Difference Between Element Sum and Digit Sum of an Array](./2535-difference-between-element-sum-and-digit-sum-of-an-array.js)|Easy| +3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| 3396|[Minimum Number of Operations to Make Elements in Array Distinct](./3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy| 3397|[Maximum Number of Distinct Elements After Operations](./3397-maximum-number-of-distinct-elements-after-operations.js)|Medium| 3402|[Minimum Operations to Make Columns Strictly Increasing](./3402-minimum-operations-to-make-columns-strictly-increasing.js)|Easy| From 5017c935592ba03fa0ec68e299a4586c59034385 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 2 Jan 2025 15:13:58 -0600 Subject: [PATCH 385/919] Add solution #2618 --- 2618-check-if-object-instance-of-class.js | 24 +++++++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 2618-check-if-object-instance-of-class.js diff --git a/2618-check-if-object-instance-of-class.js b/2618-check-if-object-instance-of-class.js new file mode 100644 index 00000000..f54fe6c0 --- /dev/null +++ b/2618-check-if-object-instance-of-class.js @@ -0,0 +1,24 @@ +/** + * 2618. Check if Object Instance of Class + * https://leetcode.com/problems/check-if-object-instance-of-class/ + * Difficulty: Medium + * + * Write a function that checks if a given value is an instance of a given class or superclass. + * For this problem, an object is considered an instance of a given class if that object has + * access to that class's methods. + * + * There are no constraints on the data types that can be passed to the function. For example, + * the value or the class could be undefined. + */ + +/** + * @param {*} obj + * @param {*} classFunction + * @return {boolean} + */ +var checkIfInstanceOf = function(obj, classFunction) { + if (obj === null || obj === undefined || typeof classFunction !== 'function') { + return false; + } + return Object(obj) instanceof classFunction; +}; diff --git a/README.md b/README.md index cdf8bd47..298b7d1c 100644 --- a/README.md +++ b/README.md @@ -361,6 +361,7 @@ 2490|[Circular Sentence](./2490-circular-sentence.js)|Easy| 2529|[Maximum Count of Positive Integer and Negative Integer](./2529-maximum-count-of-positive-integer-and-negative-integer.js)|Easy| 2535|[Difference Between Element Sum and Digit Sum of an Array](./2535-difference-between-element-sum-and-digit-sum-of-an-array.js)|Easy| +2618|[Check if Object Instance of Class](./2618-check-if-object-instance-of-class.js)|Medium| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| 3396|[Minimum Number of Operations to Make Elements in Array Distinct](./3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy| 3397|[Maximum Number of Distinct Elements After Operations](./3397-maximum-number-of-distinct-elements-after-operations.js)|Medium| From 34140f11b97873e569f4c3572e6c756c50654682 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 2 Jan 2025 15:16:29 -0600 Subject: [PATCH 386/919] Add solution #2619 --- 2619-array-prototype-last.js | 18 ++++++++++++++++++ README.md | 1 + 2 files changed, 19 insertions(+) create mode 100644 2619-array-prototype-last.js diff --git a/2619-array-prototype-last.js b/2619-array-prototype-last.js new file mode 100644 index 00000000..7e99a754 --- /dev/null +++ b/2619-array-prototype-last.js @@ -0,0 +1,18 @@ +/** + * 2619. Array Prototype Last + * https://leetcode.com/problems/array-prototype-last/ + * Difficulty: Easy + * + * Write code that enhances all arrays such that you can call the array.last() method on + * any array and it will return the last element. If there are no elements in the array, + * it should return -1. + * + * You may assume the array is the output of JSON.parse. + */ + +/** + * @return {null|boolean|number|string|Array|Object} + */ +Array.prototype.last = function() { + return !this.length ? -1 : this[this.length - 1]; +}; diff --git a/README.md b/README.md index 298b7d1c..bfec9892 100644 --- a/README.md +++ b/README.md @@ -362,6 +362,7 @@ 2529|[Maximum Count of Positive Integer and Negative Integer](./2529-maximum-count-of-positive-integer-and-negative-integer.js)|Easy| 2535|[Difference Between Element Sum and Digit Sum of an Array](./2535-difference-between-element-sum-and-digit-sum-of-an-array.js)|Easy| 2618|[Check if Object Instance of Class](./2618-check-if-object-instance-of-class.js)|Medium| +2619|[Array Prototype Last](./2619-array-prototype-last.js)|Easy| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| 3396|[Minimum Number of Operations to Make Elements in Array Distinct](./3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy| 3397|[Maximum Number of Distinct Elements After Operations](./3397-maximum-number-of-distinct-elements-after-operations.js)|Medium| From 4f33e0c3f5819e786b4233c70489f40c48c985ab Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 2 Jan 2025 15:37:57 -0600 Subject: [PATCH 387/919] Add solution #2629 --- 2629-function-composition.js | 23 +++++++++++++++++++++++ README.md | 1 + 2 files changed, 24 insertions(+) create mode 100644 2629-function-composition.js diff --git a/2629-function-composition.js b/2629-function-composition.js new file mode 100644 index 00000000..30546886 --- /dev/null +++ b/2629-function-composition.js @@ -0,0 +1,23 @@ +/** + * 2629. Function Composition + * https://leetcode.com/problems/function-composition/ + * Difficulty: Easy + * + * Given an array of functions [f1, f2, f3, ..., fn], return a new function fn that is the function + * composition of the array of functions. + * + * The function composition of [f(x), g(x), h(x)] is fn(x) = f(g(h(x))). + * + * The function composition of an empty list of functions is the identity function f(x) = x. + * + * You may assume each function in the array accepts one integer as input and returns one integer + * as output. + */ + +/** + * @param {Function[]} functions + * @return {Function} + */ +var compose = function(functions) { + return x => functions.reduceRight((result, fn) => fn(result), x); +}; diff --git a/README.md b/README.md index bfec9892..35df3dae 100644 --- a/README.md +++ b/README.md @@ -363,6 +363,7 @@ 2535|[Difference Between Element Sum and Digit Sum of an Array](./2535-difference-between-element-sum-and-digit-sum-of-an-array.js)|Easy| 2618|[Check if Object Instance of Class](./2618-check-if-object-instance-of-class.js)|Medium| 2619|[Array Prototype Last](./2619-array-prototype-last.js)|Easy| +2629|[Function Composition](./2629-function-composition.js)|Easy| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| 3396|[Minimum Number of Operations to Make Elements in Array Distinct](./3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy| 3397|[Maximum Number of Distinct Elements After Operations](./3397-maximum-number-of-distinct-elements-after-operations.js)|Medium| From 7dadfe9f56b5bb59db3a4fbeb7f356f612685dbd Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 2 Jan 2025 15:46:29 -0600 Subject: [PATCH 388/919] Add solution #2620 --- 2620-counter.js | 18 ++++++++++++++++++ README.md | 1 + 2 files changed, 19 insertions(+) create mode 100644 2620-counter.js diff --git a/2620-counter.js b/2620-counter.js new file mode 100644 index 00000000..933a4630 --- /dev/null +++ b/2620-counter.js @@ -0,0 +1,18 @@ +/** + * 2620. Counter + * https://leetcode.com/problems/counter/ + * Difficulty: Easy + * + * Given an integer n, return a counter function. This counter function initially + * returns n and then returns 1 more than the previous value every subsequent + * time it is called (n, n + 1, n + 2, etc). + */ + +/** + * @param {number} n + * @return {Function} counter + */ +var createCounter = function(n) { + let count = n; + return () => count++; +}; diff --git a/README.md b/README.md index 35df3dae..008eec04 100644 --- a/README.md +++ b/README.md @@ -363,6 +363,7 @@ 2535|[Difference Between Element Sum and Digit Sum of an Array](./2535-difference-between-element-sum-and-digit-sum-of-an-array.js)|Easy| 2618|[Check if Object Instance of Class](./2618-check-if-object-instance-of-class.js)|Medium| 2619|[Array Prototype Last](./2619-array-prototype-last.js)|Easy| +2620|[Counter](./2620-counter.js)|Easy| 2629|[Function Composition](./2629-function-composition.js)|Easy| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| 3396|[Minimum Number of Operations to Make Elements in Array Distinct](./3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy| From b1ce8ca6ad4fa6b623877620db29e725b58cbb51 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 2 Jan 2025 15:49:48 -0600 Subject: [PATCH 389/919] Add solution #2621 --- 2621-sleep.js | 16 ++++++++++++++++ README.md | 1 + 2 files changed, 17 insertions(+) create mode 100644 2621-sleep.js diff --git a/2621-sleep.js b/2621-sleep.js new file mode 100644 index 00000000..46d3fcd4 --- /dev/null +++ b/2621-sleep.js @@ -0,0 +1,16 @@ +/** + * 2621. Sleep + * https://leetcode.com/problems/sleep/ + * Difficulty: Easy + * + * Given a positive integer `ms`, write an asynchronous function that + * sleeps for `ms` milliseconds. It can resolve any value. + */ + +/** + * @param {number} ms + * @return {Promise} + */ +async function sleep(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} diff --git a/README.md b/README.md index 008eec04..0105b202 100644 --- a/README.md +++ b/README.md @@ -364,6 +364,7 @@ 2618|[Check if Object Instance of Class](./2618-check-if-object-instance-of-class.js)|Medium| 2619|[Array Prototype Last](./2619-array-prototype-last.js)|Easy| 2620|[Counter](./2620-counter.js)|Easy| +2621|[Sleep](./2621-sleep.js)|Easy| 2629|[Function Composition](./2629-function-composition.js)|Easy| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| 3396|[Minimum Number of Operations to Make Elements in Array Distinct](./3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy| From 29acd611abfb273608443ef5b50d3f55b5ccc648 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 2 Jan 2025 16:20:30 -0600 Subject: [PATCH 390/919] Add solution #2622 --- 2622-cache-with-time-limit.js | 54 +++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 55 insertions(+) create mode 100644 2622-cache-with-time-limit.js diff --git a/2622-cache-with-time-limit.js b/2622-cache-with-time-limit.js new file mode 100644 index 00000000..3097145e --- /dev/null +++ b/2622-cache-with-time-limit.js @@ -0,0 +1,54 @@ +/** + * 2622. Cache With Time Limit + * https://leetcode.com/problems/cache-with-time-limit/ + * Difficulty: Medium + * + * Write a class that allows getting and setting key-value pairs, however a time until + * expiration is associated with each key. + * + * The class has three public methods: + * - set(key, value, duration): accepts an integer key, an integer value, and a duration + * in milliseconds. Once the duration has elapsed, the key should be inaccessible. + * The method should return true if the same un-expired key already exists and false + * otherwise. Both the value and duration should be overwritten if the key already exists. + * + * - get(key): if an un-expired key exists, it should return the associated value. + * Otherwise it should return -1. + * + * - count(): returns the count of un-expired keys. + */ + +var TimeLimitedCache = function() { + this.cache = new Map(); +}; + +/** + * @param {number} key + * @param {number} value + * @param {number} duration time until expiration in ms + * @return {boolean} if un-expired key already existed + */ +TimeLimitedCache.prototype.set = function(key, value, duration) { + const hit = this.cache.has(key) && this.cache.get(key)[1] > Date.now(); + this.cache.set(key, [value, Date.now() + duration]); + return hit; +}; + +/** + * @param {number} key + * @return {number} value associated with key + */ +TimeLimitedCache.prototype.get = function(key) { + if (!this.cache.has(key)) return -1; + const [value, expiredAt] = this.cache.get(key); + return expiredAt > Date.now() ? value : -1; +}; + +/** + * @return {number} count of non-expired keys + */ +TimeLimitedCache.prototype.count = function() { + return [...this.cache.keys()].reduce((count, key) => { + return this.cache.get(key)[1] > Date.now() ? ++count : count; + }, 0); +}; diff --git a/README.md b/README.md index 0105b202..d5292649 100644 --- a/README.md +++ b/README.md @@ -365,6 +365,7 @@ 2619|[Array Prototype Last](./2619-array-prototype-last.js)|Easy| 2620|[Counter](./2620-counter.js)|Easy| 2621|[Sleep](./2621-sleep.js)|Easy| +2622|[Cache With Time Limit](./2622-cache-with-time-limit.js)|Medium| 2629|[Function Composition](./2629-function-composition.js)|Easy| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| 3396|[Minimum Number of Operations to Make Elements in Array Distinct](./3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy| From 9ff5d72e38bb3509aaeb75c77cdbf517ad6d9ab8 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 3 Jan 2025 17:56:05 -0600 Subject: [PATCH 391/919] Add solution #60 --- 0060-permutation-sequence.js | 43 ++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 44 insertions(+) create mode 100644 0060-permutation-sequence.js diff --git a/0060-permutation-sequence.js b/0060-permutation-sequence.js new file mode 100644 index 00000000..0f6f1a55 --- /dev/null +++ b/0060-permutation-sequence.js @@ -0,0 +1,43 @@ +/** + * 60. Permutation Sequence + * https://leetcode.com/problems/permutation-sequence/ + * Difficulty: Hard + * + * The set [1, 2, 3, ..., n] contains a total of n! unique permutations. + * + * By listing and labeling all of the permutations in order, we get the + * following sequence for n = 3: + * - "123" + * - "132" + * - "213" + * - "231" + * - "312" + * - "321" + * + * Given n and k, return the kth permutation sequence. + */ + +/** + * @param {number} n + * @param {number} k + * @return {string} + */ +var getPermutation = function(n, k) { + const factorial = [1]; + for (let i = 1; i < n; i++) { + factorial[i] = factorial[i-1] * i; + } + + const values = new Array(n).fill(0).map((_, i) => i + 1); + let result = ''; + k--; + + for (let i = n - 1; i >= 0; i--) { + const index = Math.floor(k / factorial[i]); + k = k % factorial[i]; + result += values[index]; + values.splice(index, 1); + } + + return result; +}; diff --git a/README.md b/README.md index d5292649..561b4ec9 100644 --- a/README.md +++ b/README.md @@ -65,6 +65,7 @@ 57|[Insert Interval](./0057-insert-interval.js)|Medium| 58|[Length of Last Word](./0058-length-of-last-word.js)|Easy| 59|[Spiral Matrix II](./0059-spiral-matrix-ii.js)|Medium| +60|[Permutation Sequence](./0060-permutation-sequence.js)|Hard| 62|[Unique Paths](./0062-unique-paths.js)|Medium| 64|[Minimum Path Sum](./0064-minimum-path-sum.js)|Medium| 66|[Plus One](./0066-plus-one.js)|Easy| From e54a0cbb7d7e7ecf75cef9055233aeb17fad3ba4 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 3 Jan 2025 17:59:06 -0600 Subject: [PATCH 392/919] Add solution #148 --- 0148-sort-list.js | 49 +++++++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 50 insertions(+) create mode 100644 0148-sort-list.js diff --git a/0148-sort-list.js b/0148-sort-list.js new file mode 100644 index 00000000..d70b320d --- /dev/null +++ b/0148-sort-list.js @@ -0,0 +1,49 @@ +/** + * 148. Sort List + * https://leetcode.com/problems/sort-list/ + * Difficulty: Medium + * + * Given the head of a linked list, return the list after sorting it in ascending order. + */ + +/** + * 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 sortList = function(head) { + if (!head || !head.next) return head; + let fast = head; + let slow = head; + while (fast.next && fast.next.next) { + fast = fast.next.next; + slow = slow.next; + } + const middle = slow.next; + slow.next = null; + return mergeList(sortList(head), sortList(middle)); +}; + +function mergeList(a, b) { + const ordered = new ListNode(-1); + let list = ordered; + + while (a && b) { + list.next = a.val < b.val ? a : b; + list = list.next; + if (a.val < b.val) { + a = a.next; + } else { + b = b.next; + } + } + + list.next = a ?? b; + return ordered.next; +} diff --git a/README.md b/README.md index 561b4ec9..0fd5dc91 100644 --- a/README.md +++ b/README.md @@ -117,6 +117,7 @@ 143|[Reorder List](./0143-reorder-list.js)|Medium| 144|[Binary Tree Preorder Traversal](./0144-binary-tree-preorder-traversal.js)|Easy| 145|[Binary Tree Postorder Traversal](./0145-binary-tree-postorder-traversal.js)|Easy| +148|[Sort List](./0148-sort-list.js)|Medium| 149|[Max Points on a Line](./0149-max-points-on-a-line.js)|Hard| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| From 8141707a2bcc4cdc3423785041886222bbe447e3 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 3 Jan 2025 18:01:06 -0600 Subject: [PATCH 393/919] Add solution #2623 --- 2623-memoize.js | 41 +++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 42 insertions(+) create mode 100644 2623-memoize.js diff --git a/2623-memoize.js b/2623-memoize.js new file mode 100644 index 00000000..d63b830d --- /dev/null +++ b/2623-memoize.js @@ -0,0 +1,41 @@ +/** + * 2623. Memoize + * https://leetcode.com/problems/memoize/ + * Difficulty: Medium + * + * Given a function fn, return a memoized version of that function. + * + * A memoized function is a function that will never be called twice + * with the same inputs. Instead it will return a cached value. + * + * You can assume there are 3 possible input functions: sum, fib, + * and factorial. + * + * - `sum` accepts two integers a and b and returns a + b. Assume that + * if a value has already been cached for the arguments (b, a) where + * a != b, it cannot be used for the arguments (a, b). For example, + * if the arguments are (3, 2) and (2, 3), two separate calls should + * be made. + * - `fib` accepts a single integer n and returns 1 if n <= 1 or + * fib(n - 1) + fib(n - 2) otherwise. + * - `factorial` accepts a single integer n and returns 1 if n <= 1 or + * factorial(n - 1) * n otherwise. + */ + +/** + * @param {Function} fn + * @return {Function} + */ +function memoize(fn) { + const cache = new Map(); + + return (...args) => { + const key = String(args); + if (cache.has(key)) { + return cache.get(key); + } + const value = fn(...args); + cache.set(key, value); + return value; + }; +} diff --git a/README.md b/README.md index 0fd5dc91..550cbb9a 100644 --- a/README.md +++ b/README.md @@ -368,6 +368,7 @@ 2620|[Counter](./2620-counter.js)|Easy| 2621|[Sleep](./2621-sleep.js)|Easy| 2622|[Cache With Time Limit](./2622-cache-with-time-limit.js)|Medium| +2623|[Memoize](./2623-memoize.js)|Medium| 2629|[Function Composition](./2629-function-composition.js)|Easy| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| 3396|[Minimum Number of Operations to Make Elements in Array Distinct](./3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy| From 3e7be463960e8ba83f1e543f41a3da182de9aa3a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 3 Jan 2025 18:02:02 -0600 Subject: [PATCH 394/919] Add solution #2630 --- 2630-memoize-ii.js | 30 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 2630-memoize-ii.js diff --git a/2630-memoize-ii.js b/2630-memoize-ii.js new file mode 100644 index 00000000..eeab53c6 --- /dev/null +++ b/2630-memoize-ii.js @@ -0,0 +1,30 @@ +/** + * 2630. Memoize II + * https://leetcode.com/problems/memoize-ii/ + * Difficulty: Hard + * + * Given a function fn, return a memoized version of that function. + * + * A memoized function is a function that will never be called twice + * with the same inputs. Instead it will return a cached value. + * + * fn can be any function and there are no constraints on what type + * of values it accepts. Inputs are considered identical if they + * are === to each other. + */ + +/** + * @param {Function} fn + * @return {Function} + */ +function memoize(fn) { + const cache = {}; + const idLookup = new Map(); + function generateId(item) { + return idLookup.get(item) ?? idLookup.set(item, idLookup.size + 1).get(item); + } + return (...args) => { + const key = args.map(generateId).join('-'); + return !cache.hasOwnProperty(key) ? (cache[key] = fn(...args)) : cache[key]; + }; +} diff --git a/README.md b/README.md index 550cbb9a..b572c4c0 100644 --- a/README.md +++ b/README.md @@ -370,6 +370,7 @@ 2622|[Cache With Time Limit](./2622-cache-with-time-limit.js)|Medium| 2623|[Memoize](./2623-memoize.js)|Medium| 2629|[Function Composition](./2629-function-composition.js)|Easy| +2630|[Memoize II](./2630-memoize-ii.js)|Hard| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| 3396|[Minimum Number of Operations to Make Elements in Array Distinct](./3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy| 3397|[Maximum Number of Distinct Elements After Operations](./3397-maximum-number-of-distinct-elements-after-operations.js)|Medium| From 26ca6fd11df5db5b6ccdd0e38ac44365bbf7515e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 3 Jan 2025 18:03:47 -0600 Subject: [PATCH 395/919] Add solution #2627 --- 2627-debounce.js | 32 ++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 2627-debounce.js diff --git a/2627-debounce.js b/2627-debounce.js new file mode 100644 index 00000000..2d017ae5 --- /dev/null +++ b/2627-debounce.js @@ -0,0 +1,32 @@ +/** + * 2627. Debounce + * https://leetcode.com/problems/debounce/ + * Difficulty: Medium + * + * Given a function fn and a time in milliseconds t, return a debounced version of that function. + * + * A debounced function is a function whose execution is delayed by t milliseconds and whose + * execution is cancelled if it is called again within that window of time. The debounced + * function should also receive the passed parameters. + * + * For example, let's say t = 50ms, and the function was called at 30ms, 60ms, and 100ms. + * + * The first 2 function calls would be cancelled, and the 3rd function call would be executed + * at 150ms. + * + * If instead t = 35ms, The 1st call would be cancelled, the 2nd would be executed at 95ms, + * and the 3rd would be executed at 135ms. + */ + +/** + * @param {Function} fn + * @param {number} t milliseconds + * @return {Function} + */ +var debounce = function(fn, t) { + let timer; + return (...args) => { + clearTimeout(timer); + timer = setTimeout(() => fn(...args), t); + }; +}; diff --git a/README.md b/README.md index b572c4c0..bf2fc51d 100644 --- a/README.md +++ b/README.md @@ -369,6 +369,7 @@ 2621|[Sleep](./2621-sleep.js)|Easy| 2622|[Cache With Time Limit](./2622-cache-with-time-limit.js)|Medium| 2623|[Memoize](./2623-memoize.js)|Medium| +2627|[Debounce](./2627-debounce.js)|Medium| 2629|[Function Composition](./2629-function-composition.js)|Easy| 2630|[Memoize II](./2630-memoize-ii.js)|Hard| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| From 0feb722700aa106f9549f3d1b31e8fc576d9d645 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 3 Jan 2025 18:24:33 -0600 Subject: [PATCH 396/919] Add solution #205 --- 0205-isomorphic-strings.js | 27 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 28 insertions(+) create mode 100644 0205-isomorphic-strings.js diff --git a/0205-isomorphic-strings.js b/0205-isomorphic-strings.js new file mode 100644 index 00000000..5067078c --- /dev/null +++ b/0205-isomorphic-strings.js @@ -0,0 +1,27 @@ +/** + * 205. Isomorphic Strings + * https://leetcode.com/problems/isomorphic-strings/ + * Difficulty: Easy + * + * Given two strings s and t, determine if they are isomorphic. + * + * Two strings s and t are isomorphic if the characters in s can be replaced to get t. + * + * All occurrences of a character must be replaced with another character while preserving + * the order of characters. No two characters may map to the same character, but a character + * may map to itself. + */ + +/** + * @param {string} s + * @param {string} t + * @return {boolean} + */ +var isIsomorphic = function(s, t) { + for (let i = 0; i < s.length; i++) { + if (s.indexOf(s[i], i + 1) !== t.indexOf(t[i], i + 1)) { + return false; + } + } + return true; +}; diff --git a/README.md b/README.md index bf2fc51d..1585a507 100644 --- a/README.md +++ b/README.md @@ -133,6 +133,7 @@ 202|[Happy Number](./0202-happy-number.js)|Easy| 203|[Remove Linked List Elements](./0203-remove-linked-list-elements.js)|Easy| 204|[Count Primes](./0204-count-primes.js)|Medium| +205|[Isomorphic Strings](./0205-isomorphic-strings.js)|Easy| 206|[Reverse Linked List](./0206-reverse-linked-list.js)|Easy| 207|[Course Schedule](./0207-course-schedule.js)|Medium| 213|[House Robber II](./0213-house-robber-ii.js)|Medium| From 964f35f5aab294a7a3b985b3a98b7dc94fd83b79 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 3 Jan 2025 19:03:48 -0600 Subject: [PATCH 397/919] Add solution #914 --- 0914-x-of-a-kind-in-a-deck-of-cards.js | 24 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 0914-x-of-a-kind-in-a-deck-of-cards.js diff --git a/0914-x-of-a-kind-in-a-deck-of-cards.js b/0914-x-of-a-kind-in-a-deck-of-cards.js new file mode 100644 index 00000000..adc311f2 --- /dev/null +++ b/0914-x-of-a-kind-in-a-deck-of-cards.js @@ -0,0 +1,24 @@ +/** + * 914. X of a Kind in a Deck of Cards + * https://leetcode.com/problems/x-of-a-kind-in-a-deck-of-cards/ + * Difficulty: Medium + * + * You are given an integer array deck where deck[i] represents the number written on the ith card. + * + * Partition the cards into one or more groups such that: + * - Each group has exactly x cards where x > 1, and + * - All the cards in one group have the same integer written on them. + * + * Return true if such partition is possible, or false otherwise. + */ + +/** + * @param {number[]} deck + * @return {boolean} + */ +var hasGroupsSizeX = function(deck) { + const gcd = (a, b) => !b ? a : gcd(b, a % b); + const map = new Map(); + deck.forEach(n => map.set(n, (map.get(n) || 0) + 1)); + return [...map.values()].reduce(gcd) > 1; +}; diff --git a/README.md b/README.md index 1585a507..1b86aad4 100644 --- a/README.md +++ b/README.md @@ -238,6 +238,7 @@ 884|[Uncommon Words from Two Sentences](./0884-uncommon-words-from-two-sentences.js)|Easy| 890|[Find and Replace Pattern](./0890-find-and-replace-pattern.js)|Medium| 905|[Sort Array By Parity](./0905-sort-array-by-parity.js)|Easy| +914|[X of a Kind in a Deck of Cards](./0914-x-of-a-kind-in-a-deck-of-cards.js)|Medium| 916|[Word Subsets](./0916-word-subsets.js)|Medium| 922|[Sort Array By Parity II](./0922-sort-array-by-parity-ii.js)|Easy| 925|[Long Pressed Name](./0925-long-pressed-name.js)|Easy| From 7f2239ddcd8b7a4710f297e65aa9e78c6a5218ca Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 4 Jan 2025 00:03:13 -0600 Subject: [PATCH 398/919] Add solution #443 --- 0443-string-compression.js | 42 ++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 43 insertions(+) create mode 100644 0443-string-compression.js diff --git a/0443-string-compression.js b/0443-string-compression.js new file mode 100644 index 00000000..63dffb2a --- /dev/null +++ b/0443-string-compression.js @@ -0,0 +1,42 @@ +/** + * 443. String Compression + * https://leetcode.com/problems/string-compression/ + * Difficulty: Medium + * + * Given an array of characters chars, compress it using the following algorithm: + * + * Begin with an empty string s. For each group of consecutive repeating characters in chars: + * - If the group's length is 1, append the character to s. + * - Otherwise, append the character followed by the group's length. + * + * The compressed string s should not be returned separately, but instead, be stored in the + * input character array chars. Note that group lengths that are 10 or longer will be split + * into multiple characters in chars. + * + * After you are done modifying the input array, return the new length of the array. + * + * You must write an algorithm that uses only constant extra space. + */ + +/** + * @param {character[]} chars + * @return {number} + */ +var compress = function(chars) { + let pointer = 0; + for (let i = 0; i < chars.length; i++) { + const char = chars[i]; + let count = 0; + while (i < chars.length && chars[i] === char) { + count++; + i++; + } + chars[pointer++] = char; + if (count !== 1) { + String(count).split('').forEach(n => chars[pointer++] = n); + } + i--; + } + chars.length = pointer; + return pointer; +}; diff --git a/README.md b/README.md index 1b86aad4..4edc9a0f 100644 --- a/README.md +++ b/README.md @@ -176,6 +176,7 @@ 414|[Third Maximum Number](./0414-third-maximum-number.js)|Easy| 419|[Battleships in a Board](./0419-battleships-in-a-board.js)|Medium| 442|[Find All Duplicates in an Array](./0442-find-all-duplicates-in-an-array.js)|Medium| +443|[String Compression](./0443-string-compression.js)|Medium| 448|[Find All Numbers Disappeared in an Array](./0448-find-all-numbers-disappeared-in-an-array.js)|Easy| 451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| 452|[Minimum Number of Arrows to Burst Balloons](./0452-minimum-number-of-arrows-to-burst-balloons.js)|Medium| From 43552e2272cfc4db60528665211d27db4605dbb3 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 4 Jan 2025 00:04:12 -0600 Subject: [PATCH 399/919] Add solution #334 --- 0334-increasing-triplet-subsequence.js | 31 ++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 0334-increasing-triplet-subsequence.js diff --git a/0334-increasing-triplet-subsequence.js b/0334-increasing-triplet-subsequence.js new file mode 100644 index 00000000..734afe32 --- /dev/null +++ b/0334-increasing-triplet-subsequence.js @@ -0,0 +1,31 @@ +/** + * 334. Increasing Triplet Subsequence + * https://leetcode.com/problems/increasing-triplet-subsequence/ + * Difficulty: Medium + * + * Given an integer array nums, return true if there exists a triple of indices + * (i, j, k) such that i < j < k and nums[i] < nums[j] < nums[k]. If no such + * indices exists, return false. + */ + +/** + * @param {number[]} nums + * @return {boolean} + */ +var increasingTriplet = function(nums) { + let first = Infinity; + let second = Infinity; + + for (const current of nums) { + if (current > second && current > first) { + return true; + } + if (current > first) { + second = current; + } else { + first = current; + } + } + + return false; +}; diff --git a/README.md b/README.md index 4edc9a0f..b251e738 100644 --- a/README.md +++ b/README.md @@ -159,6 +159,7 @@ 290|[Word Pattern](./0290-word-pattern.js)|Easy| 316|[Remove Duplicate Letters](./0316-remove-duplicate-letters.js)|Medium| 326|[Power of Three](./0326-power-of-three.js)|Easy| +334|[Increasing Triplet Subsequence](./0334-increasing-triplet-subsequence.js)|Medium| 342|[Power of Four](./0342-power-of-four.js)|Easy| 344|[Reverse String](./0344-reverse-string.js)|Easy| 345|[Reverse Vowels of a String](./0345-reverse-vowels-of-a-string.js)|Easy| From 55c3e4b81c139a42284a1682285dd750afe7a1c8 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 4 Jan 2025 00:05:23 -0600 Subject: [PATCH 400/919] Add solution #238 --- 0238-product-of-array-except-self.js | 30 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 0238-product-of-array-except-self.js diff --git a/0238-product-of-array-except-self.js b/0238-product-of-array-except-self.js new file mode 100644 index 00000000..f297cd25 --- /dev/null +++ b/0238-product-of-array-except-self.js @@ -0,0 +1,30 @@ +/** + * 238. Product of Array Except Self + * https://leetcode.com/problems/product-of-array-except-self/ + * Difficulty: Medium + * + * Given an integer array nums, return an array answer such that answer[i] is equal to the product + * of all the elements of nums except nums[i]. + * + * The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. + * + * You must write an algorithm that runs in O(n) time and without using the division operation. + */ + +/** + * @param {number[]} nums + * @return {number[]} + */ +var productExceptSelf = function(nums) { + const emptyResult = new Array(nums.length).fill(0); + const zeroCount = nums.filter(n => n === 0).length; + if (zeroCount > 1) { + return emptyResult; + } + const product = nums.reduce((product, n) => product * (n === 0 ? 1 : n), 1); + if (zeroCount === 1) { + emptyResult[nums.indexOf(0)] = product; + return emptyResult; + } + return nums.map(n => product / n); +}; diff --git a/README.md b/README.md index b251e738..486a6ea5 100644 --- a/README.md +++ b/README.md @@ -149,6 +149,7 @@ 234|[Palindrome Linked List](./0234-palindrome-linked-list.js)|Easy| 235|[Lowest Common Ancestor of a Binary Search Tree](./0235-lowest-common-ancestor-of-a-binary-search-tree.js)|Easy| 237|[Delete Node in a Linked List](./0237-delete-node-in-a-linked-list.js)|Easy| +238|[Product of Array Except Self](./0238-product-of-array-except-self.js)|Medium| 242|[Valid Anagram](./0242-valid-anagram.js)|Easy| 263|[Ugly Number](./0263-ugly-number.js)|Easy| 264|[Ugly Number II](./0264-ugly-number-ii.js)|Medium| From a5ede838c24ff36b99e6718306159f41f70ec112 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 4 Jan 2025 00:06:12 -0600 Subject: [PATCH 401/919] Add solution #605 --- 0605-can-place-flowers.js | 28 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 29 insertions(+) create mode 100644 0605-can-place-flowers.js diff --git a/0605-can-place-flowers.js b/0605-can-place-flowers.js new file mode 100644 index 00000000..d8c4d8a0 --- /dev/null +++ b/0605-can-place-flowers.js @@ -0,0 +1,28 @@ +/** + * 605. Can Place Flowers + * https://leetcode.com/problems/can-place-flowers/ + * Difficulty: Easy + * + * You have a long flowerbed in which some of the plots are planted, and some are not. + * However, flowers cannot be planted in adjacent plots. + * + * Given an integer array flowerbed containing 0's and 1's, where 0 means empty and 1 + * means not empty, and an integer n, return true if n new flowers can be planted in + * the flowerbed without violating the no-adjacent-flowers rule and false otherwise. + */ + +/** + * @param {number[]} flowerbed + * @param {number} n + * @return {boolean} + */ +var canPlaceFlowers = function(flowerbed, n) { + let count = 0; + for (let i = 0; i < flowerbed.length; i++) { + if (flowerbed[i] === 0 && flowerbed[i - 1] !== 1 && flowerbed[i + 1] !== 1) { + count++; + flowerbed[i] = 1; + } + } + return count >= n; +}; diff --git a/README.md b/README.md index 486a6ea5..05020207 100644 --- a/README.md +++ b/README.md @@ -205,6 +205,7 @@ 566|[Reshape the Matrix](./0566-reshape-the-matrix.js)|Easy| 567|[Permutation in String](./0567-permutation-in-string.js)|Medium| 599|[Minimum Index Sum of Two Lists](./0599-minimum-index-sum-of-two-lists.js)|Easy| +605|[Can Place Flowers](./0605-can-place-flowers.js)|Easy| 606|[Construct String from Binary Tree](./0606-construct-string-from-binary-tree.js)|Easy| 617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy| 628|[Maximum Product of Three Numbers](./0628-maximum-product-of-three-numbers.js)|Easy| From 9994c451c68618e950aea91a7ce5c5834d00e73c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 4 Jan 2025 00:07:03 -0600 Subject: [PATCH 402/919] Add solution #1071 --- 1071-greatest-common-divisor-of-strings.js | 26 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 27 insertions(+) create mode 100644 1071-greatest-common-divisor-of-strings.js diff --git a/1071-greatest-common-divisor-of-strings.js b/1071-greatest-common-divisor-of-strings.js new file mode 100644 index 00000000..e1639737 --- /dev/null +++ b/1071-greatest-common-divisor-of-strings.js @@ -0,0 +1,26 @@ +/** + * 1071. Greatest Common Divisor of Strings + * https://leetcode.com/problems/greatest-common-divisor-of-strings/ + * Difficulty: Easy + * + * For two strings s and t, we say "t divides s" if and only if s = t + t + t + ... + t + t + * (i.e., t is concatenated with itself one or more times). + * + * Given two strings str1 and str2, return the largest string x such that x divides both str1 + * and str2. + */ + +/** + * @param {string} str1 + * @param {string} str2 + * @return {string} + */ +var gcdOfStrings = function(str1, str2) { + if (str1 + str2 !== str2 + str1) return ''; + + for (let i = str2.length; i >= 0; i--) { + if (str1.length % i === 0 && str2.length % i === 0) { + return str1.substring(0, i); + } + } +}; diff --git a/README.md b/README.md index 05020207..773fcad9 100644 --- a/README.md +++ b/README.md @@ -262,6 +262,7 @@ 1022|[Sum of Root To Leaf Binary Numbers](./1022-sum-of-root-to-leaf-binary-numbers.js)|Easy| 1037|[Valid Boomerang](./1037-valid-boomerang.js)|Easy| 1041|[Robot Bounded In Circle](./1041-robot-bounded-in-circle.js)|Medium| +1071|[Greatest Common Divisor of Strings](./1071-greatest-common-divisor-of-strings.js)|Easy| 1081|[Smallest Subsequence of Distinct Characters](./1081-smallest-subsequence-of-distinct-characters.js)|Medium| 1103|[Distribute Candies to People](./1103-distribute-candies-to-people.js)|Easy| 1108|[Defanging an IP Address](./1108-defanging-an-ip-address.js)|Easy| From 0061ca8ed440120a792e072bd46f1b6e5193b490 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 4 Jan 2025 00:08:08 -0600 Subject: [PATCH 403/919] Add solution #1768 --- 1768-merge-strings-alternately.js | 25 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 26 insertions(+) create mode 100644 1768-merge-strings-alternately.js diff --git a/1768-merge-strings-alternately.js b/1768-merge-strings-alternately.js new file mode 100644 index 00000000..80b58b16 --- /dev/null +++ b/1768-merge-strings-alternately.js @@ -0,0 +1,25 @@ +/** + * 1768. Merge Strings Alternately + * https://leetcode.com/problems/merge-strings-alternately/ + * Difficulty: Easy + * + * You are given two strings word1 and word2. Merge the strings by adding letters in alternating + * order, starting with word1. If a string is longer than the other, append the additional + * letters onto the end of the merged string. + * + * Return the merged string. + */ + +/** + * @param {string} word1 + * @param {string} word2 + * @return {string} + */ +var mergeAlternately = function(word1, word2) { + let result = ''; + for (let i = 0; i < Math.max(word1.length, word2.length); i++) { + if (i < word1.length) result += word1[i]; + if (i < word2.length) result += word2[i]; + } + return result; +}; diff --git a/README.md b/README.md index 773fcad9..26f444f1 100644 --- a/README.md +++ b/README.md @@ -337,6 +337,7 @@ 1672|[Richest Customer Wealth](./1672-richest-customer-wealth.js)|Easy| 1716|[Calculate Money in Leetcode Bank](./1716-calculate-money-in-leetcode-bank.js)|Easy| 1748|[Sum of Unique Elements](./1748-sum-of-unique-elements.js)|Easy| +1768|[Merge Strings Alternately](./1768-merge-strings-alternately.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| 1791|[Find Center of Star Graph](./1791-find-center-of-star-graph.js)|Easy| 1812|[Determine Color of a Chessboard Square](./1812-determine-color-of-a-chessboard-square.js)|Easy| From bfc3b20b876be49a3579bd1b4468ee5096e4627d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 4 Jan 2025 00:16:57 -0600 Subject: [PATCH 404/919] Add solution #392 --- 0392-is-subsequence.js | 27 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 28 insertions(+) create mode 100644 0392-is-subsequence.js diff --git a/0392-is-subsequence.js b/0392-is-subsequence.js new file mode 100644 index 00000000..a041d570 --- /dev/null +++ b/0392-is-subsequence.js @@ -0,0 +1,27 @@ +/** + * 392. Is Subsequence + * https://leetcode.com/problems/is-subsequence/ + * Difficulty: Easy + * + * Given two strings s and t, return true if s is a subsequence of t, or false otherwise. + * + * A subsequence of a string is a new string that is formed from the original string by + * deleting some (can be none) of the characters without disturbing the relative positions + * of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not). + */ + +/** + * @param {string} s + * @param {string} t + * @return {boolean} + */ +var isSubsequence = function(s, t) { + if (s.length > t.length) return false; + let count = 0; + for (let i = 0; i < t.length; i++) { + if (s[count] === t[i]) { + count++; + } + } + return count === s.length; +}; diff --git a/README.md b/README.md index 26f444f1..e0854597 100644 --- a/README.md +++ b/README.md @@ -173,6 +173,7 @@ 374|[Guess Number Higher or Lower](./0374-guess-number-higher-or-lower.js)|Medium| 383|[Ransom Note](./0383-ransom-note.js)|Easy| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| +392|[Is Subsequence](./0392-is-subsequence.js)|Easy| 405|[Convert a Number to Hexadecimal](./0405-convert-a-number-to-hexadecimal.js)|Easy| 412|[Fizz Buzz](./0412-fizz-buzz.js)|Easy| 414|[Third Maximum Number](./0414-third-maximum-number.js)|Easy| From ab0086fe651e377d11d3c5eea1c3e8d10bad0029 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 5 Jan 2025 00:50:41 -0600 Subject: [PATCH 405/919] Add solution #1657 --- 1657-determine-if-two-strings-are-close.js | 47 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 48 insertions(+) create mode 100644 1657-determine-if-two-strings-are-close.js diff --git a/1657-determine-if-two-strings-are-close.js b/1657-determine-if-two-strings-are-close.js new file mode 100644 index 00000000..cc000018 --- /dev/null +++ b/1657-determine-if-two-strings-are-close.js @@ -0,0 +1,47 @@ +/** + * 1657. Determine if Two Strings Are Close + * https://leetcode.com/problems/determine-if-two-strings-are-close/ + * Difficulty: Medium + * + * Two strings are considered close if you can attain one from the other using the following + * operations: + * + * - Operation 1: Swap any two existing characters. + * For example, abcde -> aecdb + * - Operation 2: Transform every occurrence of one existing character into another existing + * character, and do the same with the other character. + * For example, aacabb -> bbcbaa (all a's turn into b's, and all b's turn into a's) + * + * You can use the operations on either string as many times as necessary. + * + * Given two strings, word1 and word2, return true if word1 and word2 are close, and false + * otherwise. + */ + +/** + * @param {string} word1 + * @param {string} word2 + * @return {boolean} + */ +var closeStrings = function(word1, word2) { + const map1 = helper(word1); + const map2 = helper(word2); + + for (let i = 0; i < map1.length; i++) { + if ((map1[i] === 0 || map2[i] === 0) && map1[i] !== map2[i]) { + return false; + } + } + + [map1, map2].forEach(m => m.sort((a, b) => b - a)); + + return map1.join('') === map2.join(''); +}; + +function helper(input) { + const map = Array(26).fill(0); + for (let i = 0; i < input.length; i++) { + map[input.charCodeAt(i) - 'a'.charCodeAt(0)]++; + } + return map; +} diff --git a/README.md b/README.md index e0854597..6c18cd3f 100644 --- a/README.md +++ b/README.md @@ -333,6 +333,7 @@ 1566|[Detect Pattern of Length M Repeated K or More Times](./1566-detect-pattern-of-length-m-repeated-k-or-more-times.js)|Easy| 1576|[Replace All ?'s to Avoid Consecutive Repeating Characters](./1576-replace-all-s-to-avoid-consecutive-repeating-characters.js)|Medium| 1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy| +1657|[Determine if Two Strings Are Close](./1657-determine-if-two-strings-are-close.js)|Medium| 1668|[Maximum Repeating Substring](./1668-maximum-repeating-substring.js)|Easy| 1669|[Merge In Between Linked Lists](./1669-merge-in-between-linked-lists.js)|Medium| 1672|[Richest Customer Wealth](./1672-richest-customer-wealth.js)|Easy| From 8fa227ea4e0b26f2f88738e4efb4e983709efefe Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 5 Jan 2025 00:52:16 -0600 Subject: [PATCH 406/919] Add solution #75 --- 0075-sort-colors.js | 28 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 29 insertions(+) create mode 100644 0075-sort-colors.js diff --git a/0075-sort-colors.js b/0075-sort-colors.js new file mode 100644 index 00000000..9f4b5f73 --- /dev/null +++ b/0075-sort-colors.js @@ -0,0 +1,28 @@ +/** + * 75. Sort Colors + * https://leetcode.com/problems/sort-colors/ + * Difficulty: Medium + * + * Given an array nums with n objects colored red, white, or blue, sort them in-place so + * that objects of the same color are adjacent, with the colors in the order red, white, + * and blue. + * + * We will use the integers 0, 1, and 2 to represent the color red, white, and blue, + * respectively. + * + * You must solve this problem without using the library's sort function. + */ + +/** + * @param {number[]} nums + * @return {void} Do not return anything, modify nums in-place instead. + */ +var sortColors = function(nums) { + const count = nums.reduce((a, n) => ++a[n] && a, [0, 0, 0]); + for (let i = 0, j = 0; i < count.length; i++) { + for (let k = 0; k < count[i]; k++) { + nums[j++] = i; + } + } + return nums; +}; diff --git a/README.md b/README.md index 6c18cd3f..bb2b018d 100644 --- a/README.md +++ b/README.md @@ -74,6 +74,7 @@ 70|[Climbing Stairs](./0070-climbing-stairs.js)|Easy| 73|[Set Matrix Zeroes](./0073-set-matrix-zeroes.js)|Medium| 74|[Search a 2D Matrix](./0074-search-a-2d-matrix.js)|Medium| +75|[Sort Colors](./0075-sort-colors.js)|Medium| 77|[Combinations](./0077-combinations.js)|Medium| 78|[Subsets](./0078-subsets.js)|Medium| 80|[Remove Duplicates from Sorted Array II](./0080-remove-duplicates-from-sorted-array-ii.js)|Medium| From 0d9b123788fa35b414ed061c16ada20336fe15bd Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 5 Jan 2025 00:53:25 -0600 Subject: [PATCH 407/919] Add solution #2215 --- 2215-find-the-difference-of-two-arrays.js | 25 +++++++++++++++++++++++ README.md | 1 + 2 files changed, 26 insertions(+) create mode 100644 2215-find-the-difference-of-two-arrays.js diff --git a/2215-find-the-difference-of-two-arrays.js b/2215-find-the-difference-of-two-arrays.js new file mode 100644 index 00000000..6185f291 --- /dev/null +++ b/2215-find-the-difference-of-two-arrays.js @@ -0,0 +1,25 @@ +/** + * 2215. Find the Difference of Two Arrays + * https://leetcode.com/problems/find-the-difference-of-two-arrays/ + * Difficulty: Easy + * + * Given two 0-indexed integer arrays nums1 and nums2, return a list answer of size 2 where: + * - answer[0] is a list of all distinct integers in nums1 which are not present in nums2. + * - answer[1] is a list of all distinct integers in nums2 which are not present in nums1. + * + * Note that the integers in the lists may be returned in any order. + */ + +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number[][]} + */ +var findDifference = function(nums1, nums2) { + const set1 = new Set(nums1); + const set2 = new Set(nums2); + return [ + [...set1].filter(n => !set2.has(n)), + [...set2].filter(n => !set1.has(n)) + ]; +}; diff --git a/README.md b/README.md index bb2b018d..dde510f5 100644 --- a/README.md +++ b/README.md @@ -364,6 +364,7 @@ 2114|[Maximum Number of Words Found in Sentences](./2114-maximum-number-of-words-found-in-sentences.js)|Easy| 2129|[Capitalize the Title](./2129-capitalize-the-title.js)|Easy| 2154|[Keep Multiplying Found Values by Two](./2154-keep-multiplying-found-values-by-two.js)|Easy| +2215|[Find the Difference of Two Arrays](./2215-find-the-difference-of-two-arrays.js)|Easy| 2235|[Add Two Integers](./2235-add-two-integers.js)|Easy| 2244|[Minimum Rounds to Complete All Tasks](./2244-minimum-rounds-to-complete-all-tasks.js)|Medium| 2396|[Strictly Palindromic Number](./2396-strictly-palindromic-number.js)|Medium| From e2b79b90e92c19e216e5efcf5342b5c6ed3bca57 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 5 Jan 2025 00:54:55 -0600 Subject: [PATCH 408/919] Add solution #3110 --- 3110-score-of-a-string.js | 22 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 3110-score-of-a-string.js diff --git a/3110-score-of-a-string.js b/3110-score-of-a-string.js new file mode 100644 index 00000000..047fe4dc --- /dev/null +++ b/3110-score-of-a-string.js @@ -0,0 +1,22 @@ +/** + * 3110. Score of a String + * https://leetcode.com/problems/score-of-a-string/ + * Difficulty: Easy + * + * You are given a string s. The score of a string is defined as the sum of the absolute + * difference between the ASCII values of adjacent characters. + * + * Return the score of s. + */ + +/** + * @param {string} s + * @return {number} + */ +var scoreOfString = function(s) { + let sum = 0; + for (let i = 0; i < s.length - 1; i++) { + sum += Math.abs(s[i].charCodeAt() - s[i + 1].charCodeAt()); + } + return sum; +}; diff --git a/README.md b/README.md index dde510f5..d9806fe7 100644 --- a/README.md +++ b/README.md @@ -384,6 +384,7 @@ 2627|[Debounce](./2627-debounce.js)|Medium| 2629|[Function Composition](./2629-function-composition.js)|Easy| 2630|[Memoize II](./2630-memoize-ii.js)|Hard| +3110|[Score of a String](./3110-score-of-a-string.js)|Easy| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| 3396|[Minimum Number of Operations to Make Elements in Array Distinct](./3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy| 3397|[Maximum Number of Distinct Elements After Operations](./3397-maximum-number-of-distinct-elements-after-operations.js)|Medium| From 0bb0be067bcebbe872f2a7376e4e213efbdc12b7 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 5 Jan 2025 00:57:54 -0600 Subject: [PATCH 409/919] Add solution #65 --- 0065-valid-number.js | 33 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 0065-valid-number.js diff --git a/0065-valid-number.js b/0065-valid-number.js new file mode 100644 index 00000000..ddc0723a --- /dev/null +++ b/0065-valid-number.js @@ -0,0 +1,33 @@ +/** + * 65. Valid Number + * https://leetcode.com/problems/valid-number/ + * Difficulty: Hard + * + * Given a string s, return whether s is a valid number. + * + * For example, all the following are valid numbers: "2", "0089", "-0.1", "+3.14", "4.", "-.9", + * "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789", while the following are not + * valid numbers: "abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53". + * + * Formally, a valid number is defined using one of the following definitions: + * - An integer number followed by an optional exponent. + * - A decimal number followed by an optional exponent. + * + * An integer number is defined with an optional sign '-' or '+' followed by digits. + * A decimal number is defined with an optional sign '-' or '+' followed by one of the + * following definitions: + * - Digits followed by a dot '.'. + * - Digits followed by a dot '.' followed by digits. + * - A dot '.' followed by digits. + * - An exponent is defined with an exponent notation 'e' or 'E' followed by an integer number. + * + * The digits are defined as one or more digits. + */ + +/** + * @param {string} s + * @return {boolean} + */ +var isNumber = function(s) { + return s.trim().length && !isNaN(s.trim()) && !s.includes('Infinity'); +}; diff --git a/README.md b/README.md index d9806fe7..20481b6f 100644 --- a/README.md +++ b/README.md @@ -68,6 +68,7 @@ 60|[Permutation Sequence](./0060-permutation-sequence.js)|Hard| 62|[Unique Paths](./0062-unique-paths.js)|Medium| 64|[Minimum Path Sum](./0064-minimum-path-sum.js)|Medium| +65|[Valid Number](./0065-valid-number.js)|Hard| 66|[Plus One](./0066-plus-one.js)|Easy| 67|[Add Binary](./0067-add-binary.js)|Easy| 69|[Sqrt(x)](./0069-sqrtx.js)|Medium| From 42319e178d9aaff20b13cff98550a934169685c7 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 5 Jan 2025 00:59:23 -0600 Subject: [PATCH 410/919] Add solution #2703 --- 2703-return-length-of-arguments-passed.js | 15 +++++++++++++++ README.md | 1 + 2 files changed, 16 insertions(+) create mode 100644 2703-return-length-of-arguments-passed.js diff --git a/2703-return-length-of-arguments-passed.js b/2703-return-length-of-arguments-passed.js new file mode 100644 index 00000000..36efef1f --- /dev/null +++ b/2703-return-length-of-arguments-passed.js @@ -0,0 +1,15 @@ +/** + * 2703. Return Length of Arguments Passed + * https://leetcode.com/problems/return-length-of-arguments-passed/ + * Difficulty: Easy + * + * Write a function argumentsLength that returns the count of arguments passed to it. + */ + +/** + * @param {...(null|boolean|number|string|Array|Object)} args + * @return {number} + */ +var argumentsLength = function(...args) { + return args.length; +}; diff --git a/README.md b/README.md index 20481b6f..a5ee1f45 100644 --- a/README.md +++ b/README.md @@ -385,6 +385,7 @@ 2627|[Debounce](./2627-debounce.js)|Medium| 2629|[Function Composition](./2629-function-composition.js)|Easy| 2630|[Memoize II](./2630-memoize-ii.js)|Hard| +2703|[Return Length of Arguments Passed](./2703-return-length-of-arguments-passed.js)|Easy| 3110|[Score of a String](./3110-score-of-a-string.js)|Easy| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| 3396|[Minimum Number of Operations to Make Elements in Array Distinct](./3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy| From ac079f3f095092dc5da2df403eaa8c1cb73c5d1d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 5 Jan 2025 01:00:02 -0600 Subject: [PATCH 411/919] Add solution #61 --- 0061-rotate-list.js | 37 +++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 38 insertions(+) create mode 100644 0061-rotate-list.js diff --git a/0061-rotate-list.js b/0061-rotate-list.js new file mode 100644 index 00000000..69037d40 --- /dev/null +++ b/0061-rotate-list.js @@ -0,0 +1,37 @@ +/** + * 61. Rotate List + * https://leetcode.com/problems/rotate-list/ + * Difficulty: Medium + * + * Given the head of a linked list, rotate the list to the right by k places. + */ + +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @param {number} k + * @return {ListNode} + */ +var rotateRight = function(head, k) { + if (!head || !head.next || !k) return head; + let tailCopy = head; + let tail = head; + let count = 1; + while (tail.next) { + tail = tail.next; + count++; + } + tail.next = head; + for (let i = 1; i < count - k % count; i++) { + tailCopy = tailCopy.next; + } + const result = tailCopy.next; + tailCopy.next = null; + return result; +}; diff --git a/README.md b/README.md index a5ee1f45..cbb30b11 100644 --- a/README.md +++ b/README.md @@ -66,6 +66,7 @@ 58|[Length of Last Word](./0058-length-of-last-word.js)|Easy| 59|[Spiral Matrix II](./0059-spiral-matrix-ii.js)|Medium| 60|[Permutation Sequence](./0060-permutation-sequence.js)|Hard| +61|[Rotate List](./0061-rotate-list.js)|Medium| 62|[Unique Paths](./0062-unique-paths.js)|Medium| 64|[Minimum Path Sum](./0064-minimum-path-sum.js)|Medium| 65|[Valid Number](./0065-valid-number.js)|Hard| From a391a1db28005a1af9ebd3a26aef6f4fd834f5ad Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 6 Jan 2025 01:35:04 -0600 Subject: [PATCH 412/919] Add solution #2637 --- 2637-promise-time-limit.js | 28 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 29 insertions(+) create mode 100644 2637-promise-time-limit.js diff --git a/2637-promise-time-limit.js b/2637-promise-time-limit.js new file mode 100644 index 00000000..4e1c2d9e --- /dev/null +++ b/2637-promise-time-limit.js @@ -0,0 +1,28 @@ +/** + * 2637. Promise Time Limit + * https://leetcode.com/problems/promise-time-limit/ + * Difficulty: Medium + * + * Given an asynchronous function fn and a time t in milliseconds, return a new time limited + * version of the input function. fn takes arguments provided to the time limited function. + * + * The time limited function should follow these rules: + * - If the fn completes within the time limit of t milliseconds, the time limited function + * should resolve with the result. + * - If the execution of the fn exceeds the time limit, the time limited function should + * reject with the string "Time Limit Exceeded". + */ + +/** + * @param {Function} fn + * @param {number} t + * @return {Function} + */ +var timeLimit = function(fn, t) { + return async function(...args) { + return Promise.race([ + fn(...args), + new Promise((_, reject) => setTimeout(() => reject('Time Limit Exceeded'), t)), + ]); + }; +}; diff --git a/README.md b/README.md index cbb30b11..6e04ec50 100644 --- a/README.md +++ b/README.md @@ -386,6 +386,7 @@ 2627|[Debounce](./2627-debounce.js)|Medium| 2629|[Function Composition](./2629-function-composition.js)|Easy| 2630|[Memoize II](./2630-memoize-ii.js)|Hard| +2637|[Promise Time Limit](./2637-promise-time-limit.js)|Medium| 2703|[Return Length of Arguments Passed](./2703-return-length-of-arguments-passed.js)|Easy| 3110|[Score of a String](./3110-score-of-a-string.js)|Easy| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| From b519ee1ba21f8d41f95dd4ea78df00ee57a3aa71 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 6 Jan 2025 01:35:46 -0600 Subject: [PATCH 413/919] Add solution #2648 --- 2648-generate-fibonacci-sequence.js | 24 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 2648-generate-fibonacci-sequence.js diff --git a/2648-generate-fibonacci-sequence.js b/2648-generate-fibonacci-sequence.js new file mode 100644 index 00000000..8e03eea5 --- /dev/null +++ b/2648-generate-fibonacci-sequence.js @@ -0,0 +1,24 @@ +/** + * 2648. Generate Fibonacci Sequence + * https://leetcode.com/problems/generate-fibonacci-sequence/ + * Difficulty: Easy + * + * Write a generator function that returns a generator object which yields the fibonacci sequence. + * + * The fibonacci sequence is defined by the relation Xn = Xn-1 + Xn-2. + * + * The first few numbers of the series are 0, 1, 1, 2, 3, 5, 8, 13. + */ + +/** + * @return {Generator} + */ +var fibGenerator = function* () { + let current = 0; + let next = 1; + + while (next) { + yield current; + [current, next] = [next, current + next]; + } +}; diff --git a/README.md b/README.md index 6e04ec50..efd99ad2 100644 --- a/README.md +++ b/README.md @@ -387,6 +387,7 @@ 2629|[Function Composition](./2629-function-composition.js)|Easy| 2630|[Memoize II](./2630-memoize-ii.js)|Hard| 2637|[Promise Time Limit](./2637-promise-time-limit.js)|Medium| +2648|[Generate Fibonacci Sequence](./2648-generate-fibonacci-sequence.js)|Easy| 2703|[Return Length of Arguments Passed](./2703-return-length-of-arguments-passed.js)|Easy| 3110|[Score of a String](./3110-score-of-a-string.js)|Easy| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| From d5f8285675bce92ed2e40e134365f05fdab7f1aa Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 6 Jan 2025 01:36:34 -0600 Subject: [PATCH 414/919] Add solution #2649 --- 2649-nested-array-generator.js | 25 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 26 insertions(+) create mode 100644 2649-nested-array-generator.js diff --git a/2649-nested-array-generator.js b/2649-nested-array-generator.js new file mode 100644 index 00000000..ff72f6e5 --- /dev/null +++ b/2649-nested-array-generator.js @@ -0,0 +1,25 @@ +/** + * 2649. Nested Array Generator + * https://leetcode.com/problems/nested-array-generator/ + * Difficulty: Medium + * + * Given a multi-dimensional array of integers, return a generator object which yields + * integers in the same order as inorder traversal. + * + * A multi-dimensional array is a recursive data structure that contains both integers + * and other multi-dimensional arrays. + * + * inorder traversal iterates over each array from left to right, yielding any integers + * it encounters or applying inorder traversal to any arrays it encounters. + */ + +/** + * @param {Array} input + * @return {Generator} + */ +var inorderTraversal = function* (input) { + for (const item of input) { + if (!Array.isArray(item)) yield item; + else yield* inorderTraversal(item); + } +}; diff --git a/README.md b/README.md index efd99ad2..c861dd8f 100644 --- a/README.md +++ b/README.md @@ -388,6 +388,7 @@ 2630|[Memoize II](./2630-memoize-ii.js)|Hard| 2637|[Promise Time Limit](./2637-promise-time-limit.js)|Medium| 2648|[Generate Fibonacci Sequence](./2648-generate-fibonacci-sequence.js)|Easy| +2649|[Nested Array Generator](./2649-nested-array-generator.js)|Medium| 2703|[Return Length of Arguments Passed](./2703-return-length-of-arguments-passed.js)|Easy| 3110|[Score of a String](./3110-score-of-a-string.js)|Easy| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| From ce69fdd2c181d40654827acda7cfec9781978462 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 6 Jan 2025 01:38:18 -0600 Subject: [PATCH 415/919] Add solution #2650 --- 2650-design-cancellable-function.js | 47 +++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 48 insertions(+) create mode 100644 2650-design-cancellable-function.js diff --git a/2650-design-cancellable-function.js b/2650-design-cancellable-function.js new file mode 100644 index 00000000..c6f874ac --- /dev/null +++ b/2650-design-cancellable-function.js @@ -0,0 +1,47 @@ +/** + * 2650. Design Cancellable Function + * https://leetcode.com/problems/design-cancellable-function/ + * Difficulty: Hard + * + * Sometimes you have a long running task, and you may wish to cancel it before it completes. + * To help with this goal, write a function cancellable that accepts a generator object and + * returns an array of two values: a cancel function and a promise. + * + * You may assume the generator function will only yield promises. It is your function's + * responsibility to pass the values resolved by the promise back to the generator. If the + * promise rejects, your function should throw that error back to the generator. + * + * If the cancel callback is called before the generator is done, your function should throw + * an error back to the generator. That error should be the string "Cancelled" (Not an Error + * object). If the error was caught, the returned promise should resolve with the next value + * that was yielded or returned. Otherwise, the promise should reject with the thrown error. + * No more code should be executed. + * + * When the generator is done, the promise your function returned should resolve the value + * the generator returned. If, however, the generator throws an error, the returned promise + * should reject with the error. + */ + +/** + * @param {Generator} generator + * @return {[Function, Promise]} + */ +var cancellable = function(generator) { + let cancel; + const cancelPromise = new Promise((_, reject) => { + cancel = () => reject("Cancelled"); + }); + cancelPromise.catch(() => {}); + const promise = (async () => { + let next = generator.next(); + while (!next.done) { + try { + next = generator.next(await Promise.race([next.value, cancelPromise])); + } catch (e) { + next = generator.throw(e); + } + } + return next.value; + })(); + return [cancel, promise]; +}; diff --git a/README.md b/README.md index c861dd8f..49ddc3c6 100644 --- a/README.md +++ b/README.md @@ -389,6 +389,7 @@ 2637|[Promise Time Limit](./2637-promise-time-limit.js)|Medium| 2648|[Generate Fibonacci Sequence](./2648-generate-fibonacci-sequence.js)|Easy| 2649|[Nested Array Generator](./2649-nested-array-generator.js)|Medium| +2650|[Design Cancellable Function](./2650-design-cancellable-function.js)|Hard| 2703|[Return Length of Arguments Passed](./2703-return-length-of-arguments-passed.js)|Easy| 3110|[Score of a String](./3110-score-of-a-string.js)|Easy| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| From 5c5e6a64154d561881b608b17fbe2f8f4ec5a86f Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 6 Jan 2025 01:39:03 -0600 Subject: [PATCH 416/919] Add solution #2665 --- 2665-counter-ii.js | 26 ++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 27 insertions(+) create mode 100644 2665-counter-ii.js diff --git a/2665-counter-ii.js b/2665-counter-ii.js new file mode 100644 index 00000000..7be48904 --- /dev/null +++ b/2665-counter-ii.js @@ -0,0 +1,26 @@ +/** + * 2665. Counter II + * https://leetcode.com/problems/counter-ii/ + * Difficulty: Easy + * + * Write a function createCounter. It should accept an initial integer init. + * It should return an object with three functions. + * + * The three functions are: + * - increment() increases the current value by 1 and then returns it. + * - decrement() reduces the current value by 1 and then returns it. + * - reset() sets the current value to init and then returns it. + */ + +/** + * @param {integer} init + * @return { increment: Function, decrement: Function, reset: Function } + */ +var createCounter = function(init) { + let current = init; + return { + increment: () => ++current, + decrement: () => --current, + reset: () => current = init, + }; +}; diff --git a/README.md b/README.md index 49ddc3c6..da47f074 100644 --- a/README.md +++ b/README.md @@ -390,6 +390,7 @@ 2648|[Generate Fibonacci Sequence](./2648-generate-fibonacci-sequence.js)|Easy| 2649|[Nested Array Generator](./2649-nested-array-generator.js)|Medium| 2650|[Design Cancellable Function](./2650-design-cancellable-function.js)|Hard| +2665|[Counter II](./2665-counter-ii.js)|Easy| 2703|[Return Length of Arguments Passed](./2703-return-length-of-arguments-passed.js)|Easy| 3110|[Score of a String](./3110-score-of-a-string.js)|Easy| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| From 70ee2abc5e66f144a231772deb5b32340f16a7af Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 6 Jan 2025 01:39:43 -0600 Subject: [PATCH 417/919] Add solution #2667 --- 2667-create-hello-world-function.js | 15 +++++++++++++++ README.md | 1 + 2 files changed, 16 insertions(+) create mode 100644 2667-create-hello-world-function.js diff --git a/2667-create-hello-world-function.js b/2667-create-hello-world-function.js new file mode 100644 index 00000000..93b1e296 --- /dev/null +++ b/2667-create-hello-world-function.js @@ -0,0 +1,15 @@ +/** + * 2667. Create Hello World Function + * https://leetcode.com/problems/create-hello-world-function/ + * Difficulty: Easy + * + * Write a function createHelloWorld. It should return a new function that + * always returns "Hello World". + */ + +/** + * @return {Function} + */ +var createHelloWorld = function() { + return () => 'Hello World'; +}; diff --git a/README.md b/README.md index da47f074..0e5a0aee 100644 --- a/README.md +++ b/README.md @@ -391,6 +391,7 @@ 2649|[Nested Array Generator](./2649-nested-array-generator.js)|Medium| 2650|[Design Cancellable Function](./2650-design-cancellable-function.js)|Hard| 2665|[Counter II](./2665-counter-ii.js)|Easy| +2667|[Create Hello World Function](./2667-create-hello-world-function.js)|Easy| 2703|[Return Length of Arguments Passed](./2703-return-length-of-arguments-passed.js)|Easy| 3110|[Score of a String](./3110-score-of-a-string.js)|Easy| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| From e9183f94d16b95635441665c6ae98151d46889d2 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 6 Jan 2025 01:40:26 -0600 Subject: [PATCH 418/919] Add solution #2666 --- 2666-allow-one-function-call.js | 19 +++++++++++++++++++ README.md | 1 + 2 files changed, 20 insertions(+) create mode 100644 2666-allow-one-function-call.js diff --git a/2666-allow-one-function-call.js b/2666-allow-one-function-call.js new file mode 100644 index 00000000..93bb604d --- /dev/null +++ b/2666-allow-one-function-call.js @@ -0,0 +1,19 @@ +/** + * 2666. Allow One Function Call + * https://leetcode.com/problems/allow-one-function-call/ + * Difficulty: Easy + * + * Given a function fn, return a new function that is identical to the original function except + * that it ensures fn is called at most once. + * + * - The first time the returned function is called, it should return the same result as fn. + * - Every subsequent time it is called, it should return undefined. + */ + +/** + * @param {Function} fn + * @return {Function} + */ +var once = function(fn) { + return (...args) => fn && [fn(...args), fn = undefined][0]; +}; diff --git a/README.md b/README.md index 0e5a0aee..236742b0 100644 --- a/README.md +++ b/README.md @@ -391,6 +391,7 @@ 2649|[Nested Array Generator](./2649-nested-array-generator.js)|Medium| 2650|[Design Cancellable Function](./2650-design-cancellable-function.js)|Hard| 2665|[Counter II](./2665-counter-ii.js)|Easy| +2666|[Allow One Function Call](./2666-allow-one-function-call.js)|Easy| 2667|[Create Hello World Function](./2667-create-hello-world-function.js)|Easy| 2703|[Return Length of Arguments Passed](./2703-return-length-of-arguments-passed.js)|Easy| 3110|[Score of a String](./3110-score-of-a-string.js)|Easy| From aba4df3feb085ee9cea9f86a12fa39f887accafe Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 7 Jan 2025 02:02:50 -0600 Subject: [PATCH 419/919] Add solution #2634 --- 2634-filter-elements-from-array.js | 34 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 2634-filter-elements-from-array.js diff --git a/2634-filter-elements-from-array.js b/2634-filter-elements-from-array.js new file mode 100644 index 00000000..bf8bd0b0 --- /dev/null +++ b/2634-filter-elements-from-array.js @@ -0,0 +1,34 @@ +/** + * 2634. Filter Elements from Array + * https://leetcode.com/problems/filter-elements-from-array/ + * Difficulty: Easy + * + * Given an integer array arr and a filtering function fn, return a filtered array filteredArr. + * + * The fn function takes one or two arguments: + * arr[i] - number from the arr + * i - index of arr[i] + * + * filteredArr should only contain the elements from the arr for which the expression + * fn(arr[i], i) evaluates to a truthy value. A truthy value is a value where + * Boolean(value) returns true. + * + * Please solve it without the built-in Array.filter method. + */ + +/** + * @param {number[]} arr + * @param {Function} fn + * @return {number[]} + */ +var filter = function(arr, fn) { + const result = []; + + for (let i = 0; i < arr.length; i++) { + if (fn(arr[i], i)) { + result.push(arr[i]); + } + } + + return result; +}; diff --git a/README.md b/README.md index 236742b0..3709358f 100644 --- a/README.md +++ b/README.md @@ -386,6 +386,7 @@ 2627|[Debounce](./2627-debounce.js)|Medium| 2629|[Function Composition](./2629-function-composition.js)|Easy| 2630|[Memoize II](./2630-memoize-ii.js)|Hard| +2634|[Filter Elements from Array](./2634-filter-elements-from-array.js)|Easy| 2637|[Promise Time Limit](./2637-promise-time-limit.js)|Medium| 2648|[Generate Fibonacci Sequence](./2648-generate-fibonacci-sequence.js)|Easy| 2649|[Nested Array Generator](./2649-nested-array-generator.js)|Medium| From 9458524950d8937d6eac7c3dfeab4b878437a7a9 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 7 Jan 2025 02:03:36 -0600 Subject: [PATCH 420/919] Add solution #2635 --- ...ly-transform-over-each-element-in-array.js | 27 +++++++++++++++++++ README.md | 1 + 2 files changed, 28 insertions(+) create mode 100644 2635-apply-transform-over-each-element-in-array.js diff --git a/2635-apply-transform-over-each-element-in-array.js b/2635-apply-transform-over-each-element-in-array.js new file mode 100644 index 00000000..35fa788c --- /dev/null +++ b/2635-apply-transform-over-each-element-in-array.js @@ -0,0 +1,27 @@ +/** + * 2635. Apply Transform Over Each Element in Array + * https://leetcode.com/problems/apply-transform-over-each-element-in-array/ + * Difficulty: Easy + * + * Given an integer array arr and a mapping function fn, return a new array with a transformation + * applied to each element. + * + * The returned array should be created such that returnedArray[i] = fn(arr[i], i). + * + * Please solve it without the built-in Array.map method. + */ + +/** + * @param {number[]} arr + * @param {Function} fn + * @return {number[]} + */ +var map = function(arr, fn) { + const result = []; + + for (let i = 0; i < arr.length; i++) { + result.push(fn(arr[i], i)); + } + + return result; +}; diff --git a/README.md b/README.md index 3709358f..0ec4c265 100644 --- a/README.md +++ b/README.md @@ -387,6 +387,7 @@ 2629|[Function Composition](./2629-function-composition.js)|Easy| 2630|[Memoize II](./2630-memoize-ii.js)|Hard| 2634|[Filter Elements from Array](./2634-filter-elements-from-array.js)|Easy| +2635|[Apply Transform Over Each Element in Array](./2635-apply-transform-over-each-element-in-array.js)|Easy| 2637|[Promise Time Limit](./2637-promise-time-limit.js)|Medium| 2648|[Generate Fibonacci Sequence](./2648-generate-fibonacci-sequence.js)|Easy| 2649|[Nested Array Generator](./2649-nested-array-generator.js)|Medium| From 3f107d4b01af03c492fd62437bee0a8c28e75e3a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 7 Jan 2025 02:04:54 -0600 Subject: [PATCH 421/919] Add solution #2626 --- 2626-array-reduce-transformation.js | 33 +++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 2626-array-reduce-transformation.js diff --git a/2626-array-reduce-transformation.js b/2626-array-reduce-transformation.js new file mode 100644 index 00000000..a93b28fa --- /dev/null +++ b/2626-array-reduce-transformation.js @@ -0,0 +1,33 @@ +/** + * 2626. Array Reduce Transformation + * https://leetcode.com/problems/array-reduce-transformation/ + * Difficulty: Easy + * + * Given an integer array nums, a reducer function fn, and an initial value init, return the final + * result obtained by executing the fn function on each element of the array, sequentially, + * passing in the return value from the calculation on the preceding element. + * + * This result is achieved through the following operations: val = fn(init, nums[0]), + * val = fn(val, nums[1]), val = fn(val, nums[2]), ... until every element in the array has been + * processed. The ultimate value of val is then returned. + * + * If the length of the array is 0, the function should return init. + * + * Please solve it without using the built-in Array.reduce method. + */ + +/** + * @param {number[]} nums + * @param {Function} fn + * @param {number} init + * @return {number} + */ +var reduce = function(nums, fn, init) { + let result = init; + + for (let i = 0; i < nums.length; i++) { + result = fn(result, nums[i]); + } + + return result; +}; diff --git a/README.md b/README.md index 0ec4c265..9a93efab 100644 --- a/README.md +++ b/README.md @@ -383,6 +383,7 @@ 2621|[Sleep](./2621-sleep.js)|Easy| 2622|[Cache With Time Limit](./2622-cache-with-time-limit.js)|Medium| 2623|[Memoize](./2623-memoize.js)|Medium| +2626|[Array Reduce Transformation](./2626-array-reduce-transformation.js)|Easy| 2627|[Debounce](./2627-debounce.js)|Medium| 2629|[Function Composition](./2629-function-composition.js)|Easy| 2630|[Memoize II](./2630-memoize-ii.js)|Hard| From ed504316e6141008400689fe05de2a6207eb6a5a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 7 Jan 2025 02:05:53 -0600 Subject: [PATCH 422/919] Add solution #2631 --- 2631-group-by.js | 35 +++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 36 insertions(+) create mode 100644 2631-group-by.js diff --git a/2631-group-by.js b/2631-group-by.js new file mode 100644 index 00000000..3a1eadd8 --- /dev/null +++ b/2631-group-by.js @@ -0,0 +1,35 @@ +/** + * 2631. Group By + * https://leetcode.com/problems/group-by/ + * Difficulty: Medium + * + * Write code that enhances all arrays such that you can call the array.groupBy(fn) method on any + * array and it will return a grouped version of the array. + * + * A grouped array is an object where each key is the output of fn(arr[i]) and each value is an + * array containing all items in the original array which generate that key. + * + * The provided callback fn will accept an item in the array and return a string key. + * + * The order of each value list should be the order the items appear in the array. Any order of + * keys is acceptable. + * + * Please solve it without lodash's _.groupBy function. + */ + +/** + * @param {Function} fn + * @return {Object} + */ +Array.prototype.groupBy = function(fn) { + return this.reduce((grouped, item) => { + const key = fn(item); + grouped[key] = grouped[key] || []; + grouped[key].push(item); + return grouped; + }, {}); +}; + +/** + * [1,2,3].groupBy(String) // {"1":[1],"2":[2],"3":[3]} + */ diff --git a/README.md b/README.md index 9a93efab..992a5937 100644 --- a/README.md +++ b/README.md @@ -387,6 +387,7 @@ 2627|[Debounce](./2627-debounce.js)|Medium| 2629|[Function Composition](./2629-function-composition.js)|Easy| 2630|[Memoize II](./2630-memoize-ii.js)|Hard| +2631|[Group By](./2631-group-by.js)|Medium| 2634|[Filter Elements from Array](./2634-filter-elements-from-array.js)|Easy| 2635|[Apply Transform Over Each Element in Array](./2635-apply-transform-over-each-element-in-array.js)|Easy| 2637|[Promise Time Limit](./2637-promise-time-limit.js)|Medium| From a0d77c7c56e7082325b41ae536e1ad28aef9eff4 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 7 Jan 2025 02:07:02 -0600 Subject: [PATCH 423/919] Add solution #2625 --- 2625-flatten-deeply-nested-array.js | 31 +++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 2625-flatten-deeply-nested-array.js diff --git a/2625-flatten-deeply-nested-array.js b/2625-flatten-deeply-nested-array.js new file mode 100644 index 00000000..73ed5916 --- /dev/null +++ b/2625-flatten-deeply-nested-array.js @@ -0,0 +1,31 @@ +/** + * 2625. Flatten Deeply Nested Array + * https://leetcode.com/problems/flatten-deeply-nested-array/ + * Difficulty: Medium + * + * Given a multi-dimensional array arr and a depth n, return a flattened version of that array. + * + * A multi-dimensional array is a recursive data structure that contains integers or other + * multi-dimensional arrays. + * + * A flattened array is a version of that array with some or all of the sub-arrays removed and + * replaced with the actual elements in that sub-array. This flattening operation should only + * be done if the current depth of nesting is less than n. The depth of the elements in the + * first array are considered to be 0. + * + * Please solve it without the built-in Array.flat method. + */ + +/** + * @param {Array} arr + * @param {number} depth + * @return {Array} + */ +var flat = function(arr, n) { + if (n === 0) return arr; + const result = []; + for (let i = 0; i < arr.length; i++) { + result.push(...(Array.isArray(arr[i]) ? flat(arr[i], n - 1) : [arr[i]])); + } + return result; +}; diff --git a/README.md b/README.md index 992a5937..0769ebab 100644 --- a/README.md +++ b/README.md @@ -383,6 +383,7 @@ 2621|[Sleep](./2621-sleep.js)|Easy| 2622|[Cache With Time Limit](./2622-cache-with-time-limit.js)|Medium| 2623|[Memoize](./2623-memoize.js)|Medium| +2625|[Flatten Deeply Nested Array](./2625-flatten-deeply-nested-array.js)|Medium| 2626|[Array Reduce Transformation](./2626-array-reduce-transformation.js)|Easy| 2627|[Debounce](./2627-debounce.js)|Medium| 2629|[Function Composition](./2629-function-composition.js)|Easy| From 86b31af16baf094cf269f8f3a89b39bb027459f7 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 7 Jan 2025 02:08:13 -0600 Subject: [PATCH 424/919] Add solution #2677 --- 2677-chunk-array.js | 31 +++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 2677-chunk-array.js diff --git a/2677-chunk-array.js b/2677-chunk-array.js new file mode 100644 index 00000000..60c72d6c --- /dev/null +++ b/2677-chunk-array.js @@ -0,0 +1,31 @@ +/** + * 2677. Chunk Array + * https://leetcode.com/problems/chunk-array/ + * Difficulty: Easy + * + * Given an array arr and a chunk size size, return a chunked array. + * + * A chunked array contains the original elements in arr, but consists of subarrays each of + * length size. The length of the last subarray may be less than size if arr.length is not + * evenly divisible by size. + * + * You may assume the array is the output of JSON.parse. In other words, it is valid JSON. + * + * Please solve it without using lodash's _.chunk function. + */ + +/** + * @param {Array} arr + * @param {number} size + * @return {Array} + */ +var chunk = function(arr, size) { + var result = []; + + for (let index = 0; index < arr.length;) { + result.push(arr.slice(index, index + size)); + index += size; + } + + return result; +}; diff --git a/README.md b/README.md index 0769ebab..94db1ec2 100644 --- a/README.md +++ b/README.md @@ -398,6 +398,7 @@ 2665|[Counter II](./2665-counter-ii.js)|Easy| 2666|[Allow One Function Call](./2666-allow-one-function-call.js)|Easy| 2667|[Create Hello World Function](./2667-create-hello-world-function.js)|Easy| +2677|[Chunk Array](./2677-chunk-array.js)|Easy| 2703|[Return Length of Arguments Passed](./2703-return-length-of-arguments-passed.js)|Easy| 3110|[Score of a String](./3110-score-of-a-string.js)|Easy| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| From 5e604510fc0b8d5c968b3254bd86863336bad35c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 7 Jan 2025 02:09:46 -0600 Subject: [PATCH 425/919] Add solution #2695 --- 2695-array-wrapper.js | 35 +++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 36 insertions(+) create mode 100644 2695-array-wrapper.js diff --git a/2695-array-wrapper.js b/2695-array-wrapper.js new file mode 100644 index 00000000..e7838250 --- /dev/null +++ b/2695-array-wrapper.js @@ -0,0 +1,35 @@ +/** + * 2695. Array Wrapper + * https://leetcode.com/problems/array-wrapper/ + * Difficulty: Easy + * + * Create a class ArrayWrapper that accepts an array of integers in its constructor. + * + * This class should have two features: + * - When two instances of this class are added together with the + operator, the resulting + * value is the sum of all the elements in both arrays. + * - When the String() function is called on the instance, it will return a comma separated + * string surrounded by brackets. For example, [1,2,3]. + */ + +/** + * @param {number[]} nums + * @return {void} + */ +var ArrayWrapper = function(nums) { + this.nums = nums; +}; + +/** + * @return {number} + */ +ArrayWrapper.prototype.valueOf = function() { + return this.nums.reduce((sum, n) => sum + n, 0); +}; + +/** + * @return {string} + */ +ArrayWrapper.prototype.toString = function() { + return JSON.stringify(this.nums); +}; diff --git a/README.md b/README.md index 94db1ec2..78c187bc 100644 --- a/README.md +++ b/README.md @@ -399,6 +399,7 @@ 2666|[Allow One Function Call](./2666-allow-one-function-call.js)|Easy| 2667|[Create Hello World Function](./2667-create-hello-world-function.js)|Easy| 2677|[Chunk Array](./2677-chunk-array.js)|Easy| +2695|[Array Wrapper](./2695-array-wrapper.js)|Easy| 2703|[Return Length of Arguments Passed](./2703-return-length-of-arguments-passed.js)|Easy| 3110|[Score of a String](./3110-score-of-a-string.js)|Easy| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| From 7b01305ef4b12d864bc1c99e7ea0f13f311e6550 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 8 Jan 2025 01:04:12 -0600 Subject: [PATCH 426/919] Add solution #85 --- 0085-maximal-rectangle.js | 38 ++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 39 insertions(+) create mode 100644 0085-maximal-rectangle.js diff --git a/0085-maximal-rectangle.js b/0085-maximal-rectangle.js new file mode 100644 index 00000000..9831d2fb --- /dev/null +++ b/0085-maximal-rectangle.js @@ -0,0 +1,38 @@ +/** + * 85. Maximal Rectangle + * https://leetcode.com/problems/maximal-rectangle/ + * Difficulty: Hard + * + * Given a rows x cols binary matrix filled with 0's and 1's, find the largest rectangle + * containing only 1's and return its area. + */ + +/** + * @param {character[][]} matrix + * @return {number} + */ +var maximalRectangle = function(matrix) { + if (!matrix?.length) return 0; + let maxArea = 0; + + for (let i = 0; i < matrix.length; i++) { + for (let j = 0; j < matrix[0].length; j++) { + if (matrix[i][j] === '1') { + let minWidth = matrix[0].length; + + for (let k = i; k < matrix.length && matrix[k][j] === '1'; k++) { + let width = 0; + + while (width < minWidth && j + width < matrix[0].length && matrix[k][j + width] === '1') { + width++; + } + + minWidth = Math.min(minWidth, width); + maxArea = Math.max(maxArea, minWidth * (k - i + 1)); + } + } + } + } + + return maxArea; +}; diff --git a/README.md b/README.md index 78c187bc..c8dda8d1 100644 --- a/README.md +++ b/README.md @@ -83,6 +83,7 @@ 81|[Search in Rotated Sorted Array II](./0081-search-in-rotated-sorted-array-ii.js)|Medium| 82|[Remove Duplicates from Sorted List II](./0082-remove-duplicates-from-sorted-list-ii.js)|Medium| 83|[Remove Duplicates from Sorted List](./0083-remove-duplicates-from-sorted-list.js)|Easy| +85|[Maximal Rectangle](./0085-maximal-rectangle.js)|Hard| 86|[Partition List](./0086-partition-list.js)|Medium| 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| 89|[Gray Code](./0089-gray-code.js)|Medium| From aea8839e574b095240fe30ea5a886d0cfb41e2eb Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 8 Jan 2025 01:04:54 -0600 Subject: [PATCH 427/919] Add solution #84 --- 0084-largest-rectangle-in-histogram.js | 32 ++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 0084-largest-rectangle-in-histogram.js diff --git a/0084-largest-rectangle-in-histogram.js b/0084-largest-rectangle-in-histogram.js new file mode 100644 index 00000000..6b25ab6f --- /dev/null +++ b/0084-largest-rectangle-in-histogram.js @@ -0,0 +1,32 @@ +/** + * 84. Largest Rectangle in Histogram + * https://leetcode.com/problems/largest-rectangle-in-histogram/ + * Difficulty: Hard + * + * Given an array of integers heights representing the histogram's bar height where the + * width of each bar is 1, return the area of the largest rectangle in the histogram. + */ + +/** + * @param {number[]} heights + * @return {number} + */ +var largestRectangleArea = function(heights) { + const entries = [...heights, 0]; + const stack = []; + let area = 0; + + for (let i = 0; i < entries.length; i++) { + let updatedHeight = i; + + while (stack.length && stack[stack.length - 1][1] > entries[i]) { + const [x, y] = stack.pop(); + area = Math.max(area, (i - x) * y); + updatedHeight = x; + } + + stack.push([updatedHeight, entries[i]]); + } + + return area; +}; diff --git a/README.md b/README.md index c8dda8d1..3f635eb3 100644 --- a/README.md +++ b/README.md @@ -83,6 +83,7 @@ 81|[Search in Rotated Sorted Array II](./0081-search-in-rotated-sorted-array-ii.js)|Medium| 82|[Remove Duplicates from Sorted List II](./0082-remove-duplicates-from-sorted-list-ii.js)|Medium| 83|[Remove Duplicates from Sorted List](./0083-remove-duplicates-from-sorted-list.js)|Easy| +84|[Largest Rectangle in Histogram](./0084-largest-rectangle-in-histogram.js)|Hard| 85|[Maximal Rectangle](./0085-maximal-rectangle.js)|Hard| 86|[Partition List](./0086-partition-list.js)|Medium| 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| From 7c0681224c00bad575e478e677adc6691acc08a6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 8 Jan 2025 01:06:29 -0600 Subject: [PATCH 428/919] Add solution #71 --- 0071-simplify-path.js | 40 ++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 41 insertions(+) create mode 100644 0071-simplify-path.js diff --git a/0071-simplify-path.js b/0071-simplify-path.js new file mode 100644 index 00000000..a769b26c --- /dev/null +++ b/0071-simplify-path.js @@ -0,0 +1,40 @@ +/** + * 71. Simplify Path + * https://leetcode.com/problems/simplify-path/ + * Difficulty: Medium + * + * You are given an absolute path for a Unix-style file system, which always begins + * with a slash '/'. Your task is to transform this absolute path into its simplified + * canonical path. + * + * The rules of a Unix-style file system are as follows: + * - A single period '.' represents the current directory. + * - A double period '..' represents the previous/parent directory. + * - Multiple consecutive slashes such as '//' and '///' are treated as a single slash '/'. + * - Any sequence of periods that does not match the rules above should be treated as a + * valid directory or file name. For example, '...' and '....' are valid directory or + * file names. + * + * The simplified canonical path should follow these rules: + * - The path must start with a single slash '/'. + * - Directories within the path must be separated by exactly one slash '/'. + * - The path must not end with a slash '/', unless it is the root directory. + * - The path must not have any single or double periods ('.' and '..') used to denote + * current or parent directories. + * + * Return the simplified canonical path. + */ + +/** + * @param {string} path + * @return {string} + */ +var simplifyPath = function(path) { + const stack = []; + for (const segment of path.split('/')) { + if (segment === '.' || segment === '') continue; + if (segment === '..') stack.pop(); + else stack.push(segment); + } + return `/${stack.join('/')}`; +}; diff --git a/README.md b/README.md index 3f635eb3..9a380413 100644 --- a/README.md +++ b/README.md @@ -74,6 +74,7 @@ 67|[Add Binary](./0067-add-binary.js)|Easy| 69|[Sqrt(x)](./0069-sqrtx.js)|Medium| 70|[Climbing Stairs](./0070-climbing-stairs.js)|Easy| +71|[Simplify Path](./0071-simplify-path.js)|Medium| 73|[Set Matrix Zeroes](./0073-set-matrix-zeroes.js)|Medium| 74|[Search a 2D Matrix](./0074-search-a-2d-matrix.js)|Medium| 75|[Sort Colors](./0075-sort-colors.js)|Medium| From 2a0829895b5a077561b99827b078627fd7cba8c9 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 8 Jan 2025 01:07:25 -0600 Subject: [PATCH 429/919] Add solution #1047 --- ...emove-all-adjacent-duplicates-in-string.js | 27 +++++++++++++++++++ README.md | 1 + 2 files changed, 28 insertions(+) create mode 100644 1047-remove-all-adjacent-duplicates-in-string.js diff --git a/1047-remove-all-adjacent-duplicates-in-string.js b/1047-remove-all-adjacent-duplicates-in-string.js new file mode 100644 index 00000000..12dae9b8 --- /dev/null +++ b/1047-remove-all-adjacent-duplicates-in-string.js @@ -0,0 +1,27 @@ +/** + * 1047. Remove All Adjacent Duplicates In String + * https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/ + * Difficulty: Easy + * + * You are given a string s consisting of lowercase English letters. A duplicate removal + * consists of choosing two adjacent and equal letters and removing them. + * + * We repeatedly make duplicate removals on s until we no longer can. + * + * Return the final string after all such duplicate removals have been made. It can be + * proven that the answer is unique. + */ + +/** + * @param {string} s + * @return {string} + */ +var removeDuplicates = function(s) { + const stack = []; + + for (const char of s) { + stack[stack.length - 1] === char ? stack.pop() : stack.push(char); + } + + return stack.join(''); +}; diff --git a/README.md b/README.md index 9a380413..717080b4 100644 --- a/README.md +++ b/README.md @@ -269,6 +269,7 @@ 1022|[Sum of Root To Leaf Binary Numbers](./1022-sum-of-root-to-leaf-binary-numbers.js)|Easy| 1037|[Valid Boomerang](./1037-valid-boomerang.js)|Easy| 1041|[Robot Bounded In Circle](./1041-robot-bounded-in-circle.js)|Medium| +1047|[Remove All Adjacent Duplicates In String](./1047-remove-all-adjacent-duplicates-in-string.js)|Easy| 1071|[Greatest Common Divisor of Strings](./1071-greatest-common-divisor-of-strings.js)|Easy| 1081|[Smallest Subsequence of Distinct Characters](./1081-smallest-subsequence-of-distinct-characters.js)|Medium| 1103|[Distribute Candies to People](./1103-distribute-candies-to-people.js)|Easy| From ddf3aee7429375cb5e456be692cd08b170e1213c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 8 Jan 2025 01:08:42 -0600 Subject: [PATCH 430/919] Add solution #3042 --- 3042-count-prefix-and-suffix-pairs-i.js | 35 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 36 insertions(+) create mode 100644 3042-count-prefix-and-suffix-pairs-i.js diff --git a/3042-count-prefix-and-suffix-pairs-i.js b/3042-count-prefix-and-suffix-pairs-i.js new file mode 100644 index 00000000..5c01d64a --- /dev/null +++ b/3042-count-prefix-and-suffix-pairs-i.js @@ -0,0 +1,35 @@ +/** + * 3042. Count Prefix and Suffix Pairs I + * https://leetcode.com/problems/count-prefix-and-suffix-pairs-i/ + * Difficulty: Easy + * + * You are given a 0-indexed string array words. + * + * Let's define a boolean function isPrefixAndSuffix that takes two strings, str1 and str2: + * - isPrefixAndSuffix(str1, str2) returns true if str1 is both a prefix and a suffix of + * str2, and false otherwise. + * + * For example, isPrefixAndSuffix("aba", "ababa") is true because "aba" is a prefix of + * "ababa" and also a suffix, but isPrefixAndSuffix("abc", "abcd") is false. + * + * Return an integer denoting the number of index pairs (i, j) such that i < j, and + * isPrefixAndSuffix(words[i], words[j]) is true. + */ + +/** + * @param {string[]} words + * @return {number} + */ +var countPrefixSuffixPairs = function(words) { + let count = 0; + + for (let i = 0; i < words.length; i++) { + for (let j = i + 1; j < words.length; j++) { + if (words[j].startsWith(words[i]) && words[j].endsWith(words[i])) { + count++; + } + } + } + + return count; +}; diff --git a/README.md b/README.md index 717080b4..de121785 100644 --- a/README.md +++ b/README.md @@ -405,6 +405,7 @@ 2677|[Chunk Array](./2677-chunk-array.js)|Easy| 2695|[Array Wrapper](./2695-array-wrapper.js)|Easy| 2703|[Return Length of Arguments Passed](./2703-return-length-of-arguments-passed.js)|Easy| +3042|[Count Prefix and Suffix Pairs I](./3042-count-prefix-and-suffix-pairs-i.js)|Easy| 3110|[Score of a String](./3110-score-of-a-string.js)|Easy| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| 3396|[Minimum Number of Operations to Make Elements in Array Distinct](./3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy| From abb4369d0f818352157798022e01285c70cf2926 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 8 Jan 2025 01:10:42 -0600 Subject: [PATCH 431/919] Add solution #901 --- 0901-online-stock-span.js | 46 +++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 47 insertions(+) create mode 100644 0901-online-stock-span.js diff --git a/0901-online-stock-span.js b/0901-online-stock-span.js new file mode 100644 index 00000000..311295de --- /dev/null +++ b/0901-online-stock-span.js @@ -0,0 +1,46 @@ +/** + * 901. Online Stock Span + * https://leetcode.com/problems/online-stock-span/ + * Difficulty: Medium + * + * Design an algorithm that collects daily price quotes for some stock and returns the + * span of that stock's price for the current day. + * + * The span of the stock's price in one day is the maximum number of consecutive days + * (starting from that day and going backward) for which the stock price was less than + * or equal to the price of that day. + * + * - For example, if the prices of the stock in the last four days is [7,2,1,2] and the + * price of the stock today is 2, then the span of today is 4 because starting from + * today, the price of the stock was less than or equal 2 for 4 consecutive days. + * + * - Also, if the prices of the stock in the last four days is [7,34,1,2] and the price + * of the stock today is 8, then the span of today is 3 because starting from today, + * the price of the stock was less than or equal 8 for 3 consecutive days. + * + * Implement the StockSpanner class: + * - StockSpanner() Initializes the object of the class. + * - int next(int price) Returns the span of the stock's price given that today's + * price is price. + */ + +var StockSpanner = function() { + this.stack = []; +}; + +/** + * @param {number} price + * @return {number} + */ +StockSpanner.prototype.next = function(price) { + let count = 1; + + while (this.stack.length && price >= this.stack[this.stack.length - 1][0]) { + count += this.stack[this.stack.length - 1][1]; + this.stack.pop(); + } + + this.stack.push([price, count]); + + return count; +}; diff --git a/README.md b/README.md index de121785..e5f7a5f2 100644 --- a/README.md +++ b/README.md @@ -248,6 +248,7 @@ 876|[Middle of the Linked List](./0876-middle-of-the-linked-list.js)|Easy| 884|[Uncommon Words from Two Sentences](./0884-uncommon-words-from-two-sentences.js)|Easy| 890|[Find and Replace Pattern](./0890-find-and-replace-pattern.js)|Medium| +901|[Online Stock Span](./0901-online-stock-span.js)|Medium| 905|[Sort Array By Parity](./0905-sort-array-by-parity.js)|Easy| 914|[X of a Kind in a Deck of Cards](./0914-x-of-a-kind-in-a-deck-of-cards.js)|Medium| 916|[Word Subsets](./0916-word-subsets.js)|Medium| From 82e765b5b4471c7a0169b81a4c556751c35dd9cd Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 8 Jan 2025 01:11:35 -0600 Subject: [PATCH 432/919] Add solution #435 --- 0435-non-overlapping-intervals.js | 31 +++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 0435-non-overlapping-intervals.js diff --git a/0435-non-overlapping-intervals.js b/0435-non-overlapping-intervals.js new file mode 100644 index 00000000..0fdc5c0a --- /dev/null +++ b/0435-non-overlapping-intervals.js @@ -0,0 +1,31 @@ +/** + * 435. Non-overlapping Intervals + * https://leetcode.com/problems/non-overlapping-intervals/ + * Difficulty: Medium + * + * Given an array of intervals intervals where intervals[i] = [starti, endi], return the + * minimum number of intervals you need to remove to make the rest of the intervals + * non-overlapping. + * + * Note that intervals which only touch at a point are non-overlapping. For example, + * [1, 2] and [2, 3] are non-overlapping. + */ + +/** + * @param {number[][]} intervals + * @return {number} + */ +var eraseOverlapIntervals = function(intervals) { + let count = 0; + + intervals.sort((a, b) => a[1] - b[1]); + let prevEnd = intervals[0][1]; + + for (let i = 1; i < intervals.length; i++) { + const [start, end] = intervals[i]; + if (prevEnd > start) count++; + else prevEnd = end; + } + + return count; +}; diff --git a/README.md b/README.md index e5f7a5f2..9e41dcec 100644 --- a/README.md +++ b/README.md @@ -184,6 +184,7 @@ 412|[Fizz Buzz](./0412-fizz-buzz.js)|Easy| 414|[Third Maximum Number](./0414-third-maximum-number.js)|Easy| 419|[Battleships in a Board](./0419-battleships-in-a-board.js)|Medium| +435|[Non-overlapping Intervals](./0435-non-overlapping-intervals.js)|Medium| 442|[Find All Duplicates in an Array](./0442-find-all-duplicates-in-an-array.js)|Medium| 443|[String Compression](./0443-string-compression.js)|Medium| 448|[Find All Numbers Disappeared in an Array](./0448-find-all-numbers-disappeared-in-an-array.js)|Easy| From a28e5dc0f89f7bfb0b17b8975b8af0541e4b4bcb Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 9 Jan 2025 01:15:53 -0600 Subject: [PATCH 433/919] Add solution #2721 --- ...cute-asynchronous-functions-in-parallel.js | 41 +++++++++++++++++++ README.md | 1 + 2 files changed, 42 insertions(+) create mode 100644 2721-execute-asynchronous-functions-in-parallel.js diff --git a/2721-execute-asynchronous-functions-in-parallel.js b/2721-execute-asynchronous-functions-in-parallel.js new file mode 100644 index 00000000..b4b9890f --- /dev/null +++ b/2721-execute-asynchronous-functions-in-parallel.js @@ -0,0 +1,41 @@ +/** + * 2721. Execute Asynchronous Functions in Parallel + * https://leetcode.com/problems/execute-asynchronous-functions-in-parallel/ + * Difficulty: Medium + * + * Given an array of asynchronous functions functions, return a new promise promise. + * Each function in the array accepts no arguments and returns a promise. All the + * promises should be executed in parallel. + * + * promise resolves: + * - When all the promises returned from functions were resolved successfully in + * parallel. The resolved value of promise should be an array of all the resolved + * values of promises in the same order as they were in the functions. The promise + * should resolve when all the asynchronous functions in the array have completed + * execution in parallel. + * + * promise rejects: + * When any of the promises returned from functions were rejected. promise should + * also reject with the reason of the first rejection. + * + * Please solve it without using the built-in Promise.all function. + */ + +/** + * @param {Array} functions + * @return {Promise} + */ +var promiseAll = function(functions) { + return new Promise((resolve, reject) => { + const promises = new Array(functions.length); + let count = 0; + functions.forEach((fn, i) => { + fn().then(result => { + promises[i] = result; + if (++count === promises.length) { + resolve(promises); + } + }).catch(reject); + }); + }); +}; diff --git a/README.md b/README.md index 9e41dcec..bb61bbfc 100644 --- a/README.md +++ b/README.md @@ -407,6 +407,7 @@ 2677|[Chunk Array](./2677-chunk-array.js)|Easy| 2695|[Array Wrapper](./2695-array-wrapper.js)|Easy| 2703|[Return Length of Arguments Passed](./2703-return-length-of-arguments-passed.js)|Easy| +2721|[Execute Asynchronous Functions in Parallel](./2721-execute-asynchronous-functions-in-parallel.js)|Medium| 3042|[Count Prefix and Suffix Pairs I](./3042-count-prefix-and-suffix-pairs-i.js)|Easy| 3110|[Score of a String](./3110-score-of-a-string.js)|Easy| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| From 756d71536299c585fe21c8f6af879a6292894aa4 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 9 Jan 2025 01:16:55 -0600 Subject: [PATCH 434/919] Add solution #2724 --- 2724-sort-by.js | 21 +++++++++++++++++++++ README.md | 1 + 2 files changed, 22 insertions(+) create mode 100644 2724-sort-by.js diff --git a/2724-sort-by.js b/2724-sort-by.js new file mode 100644 index 00000000..58dc39e3 --- /dev/null +++ b/2724-sort-by.js @@ -0,0 +1,21 @@ +/** + * 2724. Sort By + * https://leetcode.com/problems/sort-by/ + * Difficulty: Easy + * + * Given an array arr and a function fn, return a sorted array sortedArr. + * You can assume fn only returns numbers and those numbers determine the + * sort order of sortedArr. sortedArr must be sorted in ascending order + * by fn output. + * + * You may assume that fn will never duplicate numbers for a given array. + */ + +/** + * @param {Array} arr + * @param {Function} fn + * @return {Array} + */ +var sortBy = function(arr, fn) { + return arr.sort((a, b) => fn(a) - fn(b)); +}; diff --git a/README.md b/README.md index bb61bbfc..b48b69c6 100644 --- a/README.md +++ b/README.md @@ -408,6 +408,7 @@ 2695|[Array Wrapper](./2695-array-wrapper.js)|Easy| 2703|[Return Length of Arguments Passed](./2703-return-length-of-arguments-passed.js)|Easy| 2721|[Execute Asynchronous Functions in Parallel](./2721-execute-asynchronous-functions-in-parallel.js)|Medium| +2724|[Sort By](./2724-sort-by.js)|Easy| 3042|[Count Prefix and Suffix Pairs I](./3042-count-prefix-and-suffix-pairs-i.js)|Easy| 3110|[Score of a String](./3110-score-of-a-string.js)|Easy| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| From faff54f706b4975327fbbd9dd642fb1f3a4e7c63 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 9 Jan 2025 01:18:07 -0600 Subject: [PATCH 435/919] Add solution #2722 --- 2722-join-two-arrays-by-id.js | 32 ++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 2722-join-two-arrays-by-id.js diff --git a/2722-join-two-arrays-by-id.js b/2722-join-two-arrays-by-id.js new file mode 100644 index 00000000..5e81dde1 --- /dev/null +++ b/2722-join-two-arrays-by-id.js @@ -0,0 +1,32 @@ +/** + * 2722. Join Two Arrays by ID + * https://leetcode.com/problems/join-two-arrays-by-id/ + * Difficulty: Medium + * + * Given two arrays arr1 and arr2, return a new array joinedArray. All the objects in each + * of the two inputs arrays will contain an id field that has an integer value. + * + * joinedArray is an array formed by merging arr1 and arr2 based on their id key. The length + * of joinedArray should be the length of unique values of id. The returned array should be + * sorted in ascending order based on the id key. + * + * If a given id exists in one array but not the other, the single object with that id should + * be included in the result array without modification. + * + * If two objects share an id, their properties should be merged into a single object: + * - If a key only exists in one object, that single key-value pair should be included in + * the object. + * - If a key is included in both objects, the value in the object from arr2 should override + * the value from arr1. + */ + +/** + * @param {Array} arr1 + * @param {Array} arr2 + * @return {Array} + */ +var join = function(arr1, arr2) { + const map = new Map(); + [...arr1, ...arr2].forEach(obj => map.set(obj.id, { ...map.get(obj.id), ...obj })); + return Array.from(map.values()).sort((a, b) => a.id - b.id); +}; diff --git a/README.md b/README.md index b48b69c6..1343b221 100644 --- a/README.md +++ b/README.md @@ -408,6 +408,7 @@ 2695|[Array Wrapper](./2695-array-wrapper.js)|Easy| 2703|[Return Length of Arguments Passed](./2703-return-length-of-arguments-passed.js)|Easy| 2721|[Execute Asynchronous Functions in Parallel](./2721-execute-asynchronous-functions-in-parallel.js)|Medium| +2722|[Join Two Arrays by ID](./2722-join-two-arrays-by-id.js)|Medium| 2724|[Sort By](./2724-sort-by.js)|Easy| 3042|[Count Prefix and Suffix Pairs I](./3042-count-prefix-and-suffix-pairs-i.js)|Easy| 3110|[Score of a String](./3110-score-of-a-string.js)|Easy| From 5b6b182563840e708bb6fd0182f206c62dbdcf28 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 9 Jan 2025 01:20:50 -0600 Subject: [PATCH 436/919] Add solution #2715 --- 2715-timeout-cancellation.js | 28 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 29 insertions(+) create mode 100644 2715-timeout-cancellation.js diff --git a/2715-timeout-cancellation.js b/2715-timeout-cancellation.js new file mode 100644 index 00000000..3f16a299 --- /dev/null +++ b/2715-timeout-cancellation.js @@ -0,0 +1,28 @@ +/** + * 2715. Timeout Cancellation + * https://leetcode.com/problems/timeout-cancellation/ + * Difficulty: Easy + * + * Given a function fn, an array of arguments args, and a timeout t in milliseconds, + * return a cancel function cancelFn. + * + * After a delay of cancelTimeMs, the returned cancel function cancelFn will be invoked. + * > setTimeout(cancelFn, cancelTimeMs) + * + * Initially, the execution of the function fn should be delayed by t milliseconds. + * + * If, before the delay of t milliseconds, the function cancelFn is invoked, it should + * cancel the delayed execution of fn. Otherwise, if cancelFn is not invoked within the + * specified delay t, fn should be executed with the provided args as arguments. + */ + +/** + * @param {Function} fn + * @param {Array} args + * @param {number} t + * @return {Function} + */ +var cancellable = function(fn, args, t) { + const timeoutId = setTimeout(() => fn(...args), t); + return () => clearTimeout(timeoutId); +}; diff --git a/README.md b/README.md index 1343b221..149d6c7b 100644 --- a/README.md +++ b/README.md @@ -407,6 +407,7 @@ 2677|[Chunk Array](./2677-chunk-array.js)|Easy| 2695|[Array Wrapper](./2695-array-wrapper.js)|Easy| 2703|[Return Length of Arguments Passed](./2703-return-length-of-arguments-passed.js)|Easy| +2715|[Timeout Cancellation](./2715-timeout-cancellation.js)|Easy| 2721|[Execute Asynchronous Functions in Parallel](./2721-execute-asynchronous-functions-in-parallel.js)|Medium| 2722|[Join Two Arrays by ID](./2722-join-two-arrays-by-id.js)|Medium| 2724|[Sort By](./2724-sort-by.js)|Easy| From 685eb426bb00e465c332859bbee1d73e9290e5fb Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 9 Jan 2025 01:21:38 -0600 Subject: [PATCH 437/919] Add solution #2705 --- 2705-compact-object.js | 32 ++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 2705-compact-object.js diff --git a/2705-compact-object.js b/2705-compact-object.js new file mode 100644 index 00000000..2a997132 --- /dev/null +++ b/2705-compact-object.js @@ -0,0 +1,32 @@ +/** + * 2705. Compact Object + * https://leetcode.com/problems/compact-object/ + * Difficulty: Medium + * + * Given an object or array obj, return a compact object. + * + * A compact object is the same as the original object, except with keys containing falsy + * values removed. This operation applies to the object and any nested objects. Arrays are + * considered objects where the indices are keys. A value is considered falsy when + * Boolean(value) returns false. + * + * You may assume the obj is the output of JSON.parse. In other words, it is valid JSON. + */ + +/** + * @param {Object|Array} obj + * @return {Object|Array} + */ +var compactObject = function(obj) { + if (obj === null) return null; + if (Array.isArray(obj)) return obj.filter(Boolean).map(compactObject); + if (typeof obj !== 'object') return obj; + + return Object.keys(obj).reduce((result, key) => { + const value = compactObject(obj[key]); + if (value) { + result[key] = value; + } + return result; + }, {}); +}; diff --git a/README.md b/README.md index 149d6c7b..e44b1d32 100644 --- a/README.md +++ b/README.md @@ -407,6 +407,7 @@ 2677|[Chunk Array](./2677-chunk-array.js)|Easy| 2695|[Array Wrapper](./2695-array-wrapper.js)|Easy| 2703|[Return Length of Arguments Passed](./2703-return-length-of-arguments-passed.js)|Easy| +2705|[Compact Object](./2705-compact-object.js)|Medium| 2715|[Timeout Cancellation](./2715-timeout-cancellation.js)|Easy| 2721|[Execute Asynchronous Functions in Parallel](./2721-execute-asynchronous-functions-in-parallel.js)|Medium| 2722|[Join Two Arrays by ID](./2722-join-two-arrays-by-id.js)|Medium| From 3b1de07c912a391498b4c850722d235948060e64 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 9 Jan 2025 01:28:14 -0600 Subject: [PATCH 438/919] Add solution #2704 --- 2704-to-be-or-not-to-be.js | 28 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 29 insertions(+) create mode 100644 2704-to-be-or-not-to-be.js diff --git a/2704-to-be-or-not-to-be.js b/2704-to-be-or-not-to-be.js new file mode 100644 index 00000000..8dd27441 --- /dev/null +++ b/2704-to-be-or-not-to-be.js @@ -0,0 +1,28 @@ +/** + * 2704. To Be Or Not To Be + * https://leetcode.com/problems/to-be-or-not-to-be/ + * Difficulty: Easy + * + * Write a function expect that helps developers test their code. It should take in any + * value val and return an object with the following two functions. + * + * - toBe(val) accepts another value and returns true if the two values === each other. + * If they are not equal, it should throw an error "Not Equal". + * - notToBe(val) accepts another value and returns true if the two values !== each + * other. If they are equal, it should throw an error "Equal". + */ + +/** + * @param {string} val + * @return {Object} + */ +var expect = function(val) { + const compareHelper = (error, fn) => { + if (fn()) throw new Error(error); + return true; + }; + return { + toBe: input => compareHelper('Not Equal', () => input !== val), + notToBe: input => compareHelper('Equal', () => input === val), + }; +}; diff --git a/README.md b/README.md index e44b1d32..4d2a0d24 100644 --- a/README.md +++ b/README.md @@ -407,6 +407,7 @@ 2677|[Chunk Array](./2677-chunk-array.js)|Easy| 2695|[Array Wrapper](./2695-array-wrapper.js)|Easy| 2703|[Return Length of Arguments Passed](./2703-return-length-of-arguments-passed.js)|Easy| +2704|[To Be Or Not To Be](./2704-to-be-or-not-to-be.js)|Easy| 2705|[Compact Object](./2705-compact-object.js)|Medium| 2715|[Timeout Cancellation](./2715-timeout-cancellation.js)|Easy| 2721|[Execute Asynchronous Functions in Parallel](./2721-execute-asynchronous-functions-in-parallel.js)|Medium| From 50d123dc8fd5649f5bb85155e2d7daa545a51897 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 9 Jan 2025 01:28:50 -0600 Subject: [PATCH 439/919] Add solution #2185 --- 2185-counting-words-with-a-given-prefix.js | 20 ++++++++++++++++++++ README.md | 1 + 2 files changed, 21 insertions(+) create mode 100644 2185-counting-words-with-a-given-prefix.js diff --git a/2185-counting-words-with-a-given-prefix.js b/2185-counting-words-with-a-given-prefix.js new file mode 100644 index 00000000..acd59f98 --- /dev/null +++ b/2185-counting-words-with-a-given-prefix.js @@ -0,0 +1,20 @@ +/** + * 2185. Counting Words With a Given Prefix + * https://leetcode.com/problems/counting-words-with-a-given-prefix/ + * Difficulty: Easy + * + * You are given an array of strings words and a string pref. + * + * Return the number of strings in words that contain pref as a prefix. + * + * A prefix of a string s is any leading contiguous substring of s. + */ + +/** + * @param {string[]} words + * @param {string} pref + * @return {number} + */ +var prefixCount = function(words, pref) { + return words.filter(word => word.startsWith(pref)).length; +}; diff --git a/README.md b/README.md index 4d2a0d24..af21b548 100644 --- a/README.md +++ b/README.md @@ -372,6 +372,7 @@ 2114|[Maximum Number of Words Found in Sentences](./2114-maximum-number-of-words-found-in-sentences.js)|Easy| 2129|[Capitalize the Title](./2129-capitalize-the-title.js)|Easy| 2154|[Keep Multiplying Found Values by Two](./2154-keep-multiplying-found-values-by-two.js)|Easy| +2185|[Counting Words With a Given Prefix](./2185-counting-words-with-a-given-prefix.js)|Easy| 2215|[Find the Difference of Two Arrays](./2215-find-the-difference-of-two-arrays.js)|Easy| 2235|[Add Two Integers](./2235-add-two-integers.js)|Easy| 2244|[Minimum Rounds to Complete All Tasks](./2244-minimum-rounds-to-complete-all-tasks.js)|Medium| From 0a9256a335d833db1de57c7a9c497d3edfc1a9f9 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 10 Jan 2025 01:09:12 -0600 Subject: [PATCH 440/919] Add solution #274 --- 0274-h-index.js | 26 ++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 27 insertions(+) create mode 100644 0274-h-index.js diff --git a/0274-h-index.js b/0274-h-index.js new file mode 100644 index 00000000..b506f1c0 --- /dev/null +++ b/0274-h-index.js @@ -0,0 +1,26 @@ +/** + * 274. H-Index + * https://leetcode.com/problems/h-index/ + * Difficulty: Medium + * + * Given an array of integers citations where citations[i] is the number of citations + * a researcher received for their ith paper, return the researcher's h-index. + * + * According to the definition of h-index on Wikipedia: The h-index is defined as the + * maximum value of h such that the given researcher has published at least h papers + * that have each been cited at least h times. + */ + +/** + * @param {number[]} citations + * @return {number} + */ +var hIndex = function(citations) { + citations.sort((a, b) => a - b); + for (let i = 0; i < citations.length; i++) { + if (citations[i] >= citations.length - i) { + return citations.length - i; + } + } + return 0; +}; diff --git a/README.md b/README.md index af21b548..5329886f 100644 --- a/README.md +++ b/README.md @@ -161,6 +161,7 @@ 264|[Ugly Number II](./0264-ugly-number-ii.js)|Medium| 268|[Missing Number](./0268-missing-number.js)|Easy| 273|[Integer to English Words](./0273-integer-to-english-words.js)|Hard| +274|[H-Index](./0274-h-index.js)|Medium| 278|[First Bad Version](./0278-first-bad-version.js)|Medium| 283|[Move Zeroes](./0283-move-zeroes.js)|Easy| 290|[Word Pattern](./0290-word-pattern.js)|Easy| From 303dae1e83855d2869760bdc287aaceffe8e106d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 10 Jan 2025 01:10:50 -0600 Subject: [PATCH 441/919] Add solution #916 --- 0916-word-subsets.js | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/0916-word-subsets.js b/0916-word-subsets.js index 0456e435..1f1e5d62 100644 --- a/0916-word-subsets.js +++ b/0916-word-subsets.js @@ -3,28 +3,29 @@ * https://leetcode.com/problems/word-subsets/ * Difficulty: Medium * - * We are given two arrays A and B of words. Each word is a string of lowercase letters. + * You are given two string arrays words1 and words2. * - * Now, say that word b is a subset of word a if every letter in b occurs in a, including - * multiplicity. For example, "wrr" is a subset of "warrior", but is not a subset of "world". + * A string b is a subset of string a if every letter in b occurs in a including multiplicity. * - * Now say a word a from A is universal if for every b in B, b is a subset of a. + * For example, "wrr" is a subset of "warrior" but is not a subset of "world". * - * Return a list of all universal words in A. You can return the words in any order. + * A string a from words1 is universal if for every string b in words2, b is a subset of a. + * + * Return an array of all the universal strings in words1. You may return the answer in any order. */ /** - * @param {string[]} A - * @param {string[]} B + * @param {string[]} words1 + * @param {string[]} words2 * @return {string[]} */ -var wordSubsets = function(A, B) { +var wordSubsets = function(words1, words2) { const count = (string, char) => string.split(char).length - 1; - const subset = Array.from(B.reduce((map, b) => { + const subset = Array.from(words2.reduce((map, b) => { b.split('').forEach(char => { map.set(char, (map.get(char) || 0) > count(b, char) ? map.get(char) : count(b, char)); }); return map; }, new Map())); - return A.filter(a => subset.every(match => count(a, match[0]) >= match[1])); + return words1.filter(a => subset.every(match => count(a, match[0]) >= match[1])); }; From 773d464a6d41ac383f1a54f1a64a582a39b84696 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 10 Jan 2025 01:13:12 -0600 Subject: [PATCH 442/919] Add solution #912 --- 0912-sort-an-array.js | 34 ++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 0912-sort-an-array.js diff --git a/0912-sort-an-array.js b/0912-sort-an-array.js new file mode 100644 index 00000000..d11d5b32 --- /dev/null +++ b/0912-sort-an-array.js @@ -0,0 +1,34 @@ +/** + * 912. Sort an Array + * https://leetcode.com/problems/sort-an-array/ + * Difficulty: Medium + * + * Given an array of integers nums, sort the array in ascending order and return it. + * + * You must solve the problem without using any built-in functions in O(nlog(n)) time + * complexity and with the smallest space complexity possible. + */ + +/** + * @param {number[]} nums + * @return {number[]} + */ +var sortArray = function(nums) { + if (nums.length <= 1) { + return nums; + } + + const min = Math.min(...nums); + const max = Math.max(...nums); + const count = new Array(max - min + 1).fill(0); + + nums.forEach(n => count[n - min]++); + + for (let i = 0, j = 0; i < count.length; i++) { + while (count[i]-- > 0) { + nums[j++] = i + min; + } + } + + return nums; +}; diff --git a/README.md b/README.md index 5329886f..59955b80 100644 --- a/README.md +++ b/README.md @@ -252,6 +252,7 @@ 890|[Find and Replace Pattern](./0890-find-and-replace-pattern.js)|Medium| 901|[Online Stock Span](./0901-online-stock-span.js)|Medium| 905|[Sort Array By Parity](./0905-sort-array-by-parity.js)|Easy| +912|[Sort an Array](./0912-sort-an-array.js)|Medium| 914|[X of a Kind in a Deck of Cards](./0914-x-of-a-kind-in-a-deck-of-cards.js)|Medium| 916|[Word Subsets](./0916-word-subsets.js)|Medium| 922|[Sort Array By Parity II](./0922-sort-array-by-parity-ii.js)|Easy| From bc40ad58fd47ce65095eec515f0473f73e32e4f6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 10 Jan 2025 01:13:55 -0600 Subject: [PATCH 443/919] Add solution #1122 --- 1122-relative-sort-array.js | 22 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 1122-relative-sort-array.js diff --git a/1122-relative-sort-array.js b/1122-relative-sort-array.js new file mode 100644 index 00000000..9a1ebafb --- /dev/null +++ b/1122-relative-sort-array.js @@ -0,0 +1,22 @@ +/** + * 1122. Relative Sort Array + * https://leetcode.com/problems/relative-sort-array/ + * Difficulty: Easy + * + * Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all + * elements in arr2 are also in arr1. + * + * Sort the elements of arr1 such that the relative ordering of items in arr1 + * are the same as in arr2. Elements that do not appear in arr2 should be + * placed at the end of arr1 in ascending order. + */ + +/** + * @param {number[]} arr1 + * @param {number[]} arr2 + * @return {number[]} + */ +var relativeSortArray = function(arr1, arr2) { + const map = new Map(arr2.map((v, i) => [v, i])); + return arr1.sort((a, b) => (map.get(a) ?? arr2.length + a) - (map.get(b) ?? arr2.length + b)); +}; diff --git a/README.md b/README.md index 59955b80..41adb6ad 100644 --- a/README.md +++ b/README.md @@ -278,6 +278,7 @@ 1081|[Smallest Subsequence of Distinct Characters](./1081-smallest-subsequence-of-distinct-characters.js)|Medium| 1103|[Distribute Candies to People](./1103-distribute-candies-to-people.js)|Easy| 1108|[Defanging an IP Address](./1108-defanging-an-ip-address.js)|Easy| +1122|[Relative Sort Array](./1122-relative-sort-array.js)|Easy| 1189|[Maximum Number of Balloons](./1189-maximum-number-of-balloons.js)|Easy| 1207|[Unique Number of Occurrences](./1207-unique-number-of-occurrences.js)|Easy| 1232|[Check If It Is a Straight Line](./1232-check-if-it-is-a-straight-line.js)|Easy| From 244f2904a6a70be4a54ba99f16dd41ac5941a026 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 10 Jan 2025 01:14:39 -0600 Subject: [PATCH 444/919] Add solution #1051 --- 1051-height-checker.js | 25 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 26 insertions(+) create mode 100644 1051-height-checker.js diff --git a/1051-height-checker.js b/1051-height-checker.js new file mode 100644 index 00000000..38cd63fb --- /dev/null +++ b/1051-height-checker.js @@ -0,0 +1,25 @@ +/** + * 1051. Height Checker + * https://leetcode.com/problems/height-checker/ + * Difficulty: Easy + * + * A school is trying to take an annual photo of all the students. The students are asked + * to stand in a single file line in non-decreasing order by height. Let this ordering be + * represented by the integer array expected where expected[i] is the expected height of + * the ith student in line. + * + * You are given an integer array heights representing the current order that the students + * are standing in. Each heights[i] is the height of the ith student in line (0-indexed). + * + * Return the number of indices where heights[i] != expected[i]. + */ + +/** + * @param {number[]} heights + * @return {number} + */ +var heightChecker = function(heights) { + return [...heights] + .sort((a, b) => a - b) + .filter((expected, i) => heights[i] !== expected).length; +}; diff --git a/README.md b/README.md index 41adb6ad..e52e511b 100644 --- a/README.md +++ b/README.md @@ -274,6 +274,7 @@ 1037|[Valid Boomerang](./1037-valid-boomerang.js)|Easy| 1041|[Robot Bounded In Circle](./1041-robot-bounded-in-circle.js)|Medium| 1047|[Remove All Adjacent Duplicates In String](./1047-remove-all-adjacent-duplicates-in-string.js)|Easy| +1051|[Height Checker](./1051-height-checker.js)|Easy| 1071|[Greatest Common Divisor of Strings](./1071-greatest-common-divisor-of-strings.js)|Easy| 1081|[Smallest Subsequence of Distinct Characters](./1081-smallest-subsequence-of-distinct-characters.js)|Medium| 1103|[Distribute Candies to People](./1103-distribute-candies-to-people.js)|Easy| From f6bc2562ec247f128b7999415da588d4fc9983e9 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 10 Jan 2025 01:15:43 -0600 Subject: [PATCH 445/919] Add solution #2037 --- ...inimum-number-of-moves-to-seat-everyone.js | 29 +++++++++++++++++++ README.md | 1 + 2 files changed, 30 insertions(+) create mode 100644 2037-minimum-number-of-moves-to-seat-everyone.js diff --git a/2037-minimum-number-of-moves-to-seat-everyone.js b/2037-minimum-number-of-moves-to-seat-everyone.js new file mode 100644 index 00000000..04c54286 --- /dev/null +++ b/2037-minimum-number-of-moves-to-seat-everyone.js @@ -0,0 +1,29 @@ +/** + * 2037. Minimum Number of Moves to Seat Everyone + * https://leetcode.com/problems/minimum-number-of-moves-to-seat-everyone/ + * Difficulty: Easy + * + * There are n availabe seats and n students standing in a room. You are given an array + * seats of length n, where seats[i] is the position of the ith seat. You are also given + * the array students of length n, where students[j] is the position of the jth student. + * + * You may perform the following move any number of times: + * - Increase or decrease the position of the ith student by 1 (i.e., moving the ith + * student from position x to x + 1 or x - 1) + * + * Return the minimum number of moves required to move each student to a seat such that + * no two students are in the same seat. + * + * Note that there may be multiple seats or students in the same position at the beginning. + */ + +/** + * @param {number[]} seats + * @param {number[]} students + * @return {number} + */ +var minMovesToSeat = function(seats, students) { + seats.sort((a, b) => a - b); + students.sort((a, b) => a - b); + return seats.reduce((a, b, i) => a += Math.abs(seats[i] - students[i]), 0); +}; diff --git a/README.md b/README.md index e52e511b..1bfed356 100644 --- a/README.md +++ b/README.md @@ -368,6 +368,7 @@ 2011|[Final Value of Variable After Performing Operations](./2011-final-value-of-variable-after-performing-operations.js)|Easy| 2016|[Maximum Difference Between Increasing Elements](./2016-maximum-difference-between-increasing-elements.js)|Easy| 2027|[Minimum Moves to Convert String](./2027-minimum-moves-to-convert-string.js)|Easy| +2037|[Minimum Number of Moves to Seat Everyone](./2037-minimum-number-of-moves-to-seat-everyone.js)|Easy| 2047|[Number of Valid Words in a Sentence](./2047-number-of-valid-words-in-a-sentence.js)|Easy| 2053|[Kth Distinct String in an Array](./2053-kth-distinct-string-in-an-array.js)|Medium| 2085|[Count Common Words With One Occurrence](./2085-count-common-words-with-one-occurrence.js)|Easy| From f611bc5575e2f43bb57d7b6996e5b5568ab0dbad Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 10 Jan 2025 01:17:05 -0600 Subject: [PATCH 446/919] Add solution #1833 --- 1833-maximum-ice-cream-bars.js | 33 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 1833-maximum-ice-cream-bars.js diff --git a/1833-maximum-ice-cream-bars.js b/1833-maximum-ice-cream-bars.js new file mode 100644 index 00000000..e8952086 --- /dev/null +++ b/1833-maximum-ice-cream-bars.js @@ -0,0 +1,33 @@ +/** + * 1833. Maximum Ice Cream Bars + * https://leetcode.com/problems/maximum-ice-cream-bars/ + * Difficulty: Medium + * + * It is a sweltering summer day, and a boy wants to buy some ice cream bars. + * + * At the store, there are n ice cream bars. You are given an array costs of + * length n, where costs[i] is the price of the ith ice cream bar in coins. + * The boy initially has coins coins to spend, and he wants to buy as many + * ice cream bars as possible. + * + * Note: The boy can buy the ice cream bars in any order. + * + * Return the maximum number of ice cream bars the boy can buy with coins. + */ + +/** + * @param {number[]} costs + * @param {number} coins + * @return {number} + */ +var maxIceCream = function(costs, coins) { + let count = 0; + costs.sort((a, b) => a - b); + for (let i = 0; i < costs.length; i++) { + if (costs[i] <= coins) { + count++; + coins -= costs[i]; + } + } + return count; +}; diff --git a/README.md b/README.md index 1bfed356..c01b7eda 100644 --- a/README.md +++ b/README.md @@ -358,6 +358,7 @@ 1812|[Determine Color of a Chessboard Square](./1812-determine-color-of-a-chessboard-square.js)|Easy| 1817|[Finding the Users Active Minutes](./1817-finding-the-users-active-minutes.js)|Medium| 1832|[Check if the Sentence Is Pangram](./1832-check-if-the-sentence-is-pangram.js)|Easy| +1833|[Maximum Ice Cream Bars](./1833-maximum-ice-cream-bars.js)|Medium| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| 1920|[Build Array from Permutation](./1920-build-array-from-permutation.js)|Easy| From b5b7f0f14137a7ea5dfa4dd78e571e97377bd164 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 11 Jan 2025 16:15:36 -0600 Subject: [PATCH 447/919] Add solution #1400 --- 1400-construct-k-palindrome-strings.js | 21 +++++++++++++++++++++ README.md | 1 + 2 files changed, 22 insertions(+) create mode 100644 1400-construct-k-palindrome-strings.js diff --git a/1400-construct-k-palindrome-strings.js b/1400-construct-k-palindrome-strings.js new file mode 100644 index 00000000..d53e6316 --- /dev/null +++ b/1400-construct-k-palindrome-strings.js @@ -0,0 +1,21 @@ +/** + * 1400. Construct K Palindrome Strings + * https://leetcode.com/problems/construct-k-palindrome-strings/ + * Difficulty: Medium + * + * Given a string s and an integer k, return true if you can use all the characters in s to + * construct k palindrome strings or false otherwise. + */ + +/** + * @param {string} s + * @param {number} k + * @return {boolean} + */ +var canConstruct = function(s, k) { + const occurrences = new Array(26).fill(0); + s.split('').forEach(c => occurrences[c.charCodeAt(0) - 'a'.charCodeAt(0)]++); + + const oddCount = occurrences.filter(n => n % 2 !== 0).length; + return k <= s.length && oddCount <= k; +}; diff --git a/README.md b/README.md index c01b7eda..fd9cdc12 100644 --- a/README.md +++ b/README.md @@ -311,6 +311,7 @@ 1374|[Generate a String With Characters That Have Odd Counts](./1374-generate-a-string-with-characters-that-have-odd-counts.js)|Easy| 1380|[Lucky Numbers in a Matrix](./1380-lucky-numbers-in-a-matrix.js)|Easy| 1389|[Create Target Array in the Given Order](./1389-create-target-array-in-the-given-order.js)|Easy| +1400|[Construct K Palindrome Strings](./1400-construct-k-palindrome-strings.js)|Medium| 1402|[Reducing Dishes](./1402-reducing-dishes.js)|Hard| 1408|[String Matching in an Array](./1408-string-matching-in-an-array.js)|Easy| 1410|[HTML Entity Parser](./1410-html-entity-parser.js)|Medium| From 4b13914b4903a8ce88873eded3b1eab980932a91 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 11 Jan 2025 16:16:12 -0600 Subject: [PATCH 448/919] Add solution #1679 --- 1679-max-number-of-k-sum-pairs.js | 35 +++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 36 insertions(+) create mode 100644 1679-max-number-of-k-sum-pairs.js diff --git a/1679-max-number-of-k-sum-pairs.js b/1679-max-number-of-k-sum-pairs.js new file mode 100644 index 00000000..cdeb517d --- /dev/null +++ b/1679-max-number-of-k-sum-pairs.js @@ -0,0 +1,35 @@ +/** + * 1679. Max Number of K-Sum Pairs + * https://leetcode.com/problems/max-number-of-k-sum-pairs/ + * Difficulty: Medium + * + * You are given an integer array nums and an integer k. + * + * In one operation, you can pick two numbers from the array whose sum equals k and + * remove them from the array. + * + * Return the maximum number of operations you can perform on the array. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var maxOperations = function(nums, k) { + const map = new Map(); + let result = 0; + + nums.forEach(n => { + const diff = k - n; + + if (map.get(diff)) { + result++; + map.set(diff, map.get(diff) - 1); + } else { + map.set(n, (map.get(n) ?? 0) + 1); + } + }); + + return result; +}; diff --git a/README.md b/README.md index fd9cdc12..4e594b47 100644 --- a/README.md +++ b/README.md @@ -351,6 +351,7 @@ 1668|[Maximum Repeating Substring](./1668-maximum-repeating-substring.js)|Easy| 1669|[Merge In Between Linked Lists](./1669-merge-in-between-linked-lists.js)|Medium| 1672|[Richest Customer Wealth](./1672-richest-customer-wealth.js)|Easy| +1679|[Max Number of K-Sum Pairs](./1679-max-number-of-k-sum-pairs.js)|Medium| 1716|[Calculate Money in Leetcode Bank](./1716-calculate-money-in-leetcode-bank.js)|Easy| 1748|[Sum of Unique Elements](./1748-sum-of-unique-elements.js)|Easy| 1768|[Merge Strings Alternately](./1768-merge-strings-alternately.js)|Easy| From 12cafd05ada9a91ec2dcb9a23255d0e2fd592094 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 11 Jan 2025 16:16:51 -0600 Subject: [PATCH 449/919] Add solution #643 --- 0643-maximum-average-subarray-i.js | 31 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 0643-maximum-average-subarray-i.js diff --git a/0643-maximum-average-subarray-i.js b/0643-maximum-average-subarray-i.js new file mode 100644 index 00000000..413edd4f --- /dev/null +++ b/0643-maximum-average-subarray-i.js @@ -0,0 +1,31 @@ +/** + * 643. Maximum Average Subarray I + * https://leetcode.com/problems/maximum-average-subarray-i/ + * Difficulty: Easy + * + * You are given an integer array nums consisting of n elements, and an integer k. + * + * Find a contiguous subarray whose length is equal to k that has the maximum average + * value and return this value. Any answer with a calculation error less than 10-5 + * will be accepted. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var findMaxAverage = function(nums, k) { + let sum = 0; + for (let i = 0; i < k; i++) { + sum += nums[i]; + } + + let max = sum; + for (let i = k; i < nums.length; i++) { + sum = sum - nums[i - k] + nums[i]; + max = Math.max(max, sum); + } + + return max / k; +}; diff --git a/README.md b/README.md index 4e594b47..8581a639 100644 --- a/README.md +++ b/README.md @@ -218,6 +218,7 @@ 606|[Construct String from Binary Tree](./0606-construct-string-from-binary-tree.js)|Easy| 617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy| 628|[Maximum Product of Three Numbers](./0628-maximum-product-of-three-numbers.js)|Easy| +643|[Maximum Average Subarray I](./0643-maximum-average-subarray-i.js)|Easy| 645|[Set Mismatch](./0645-set-mismatch.js)|Medium| 648|[Replace Words](./0648-replace-words.js)|Medium| 653|[Two Sum IV - Input is a BST](./0653-two-sum-iv-input-is-a-bst.js)|Easy| From cbcfa18259d5e9a8e641b5c2cc53549318665403 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 11 Jan 2025 16:17:18 -0600 Subject: [PATCH 450/919] Add solution #485 --- 0485-max-consecutive-ones.js | 20 ++++++++++++++++++++ README.md | 1 + 2 files changed, 21 insertions(+) create mode 100644 0485-max-consecutive-ones.js diff --git a/0485-max-consecutive-ones.js b/0485-max-consecutive-ones.js new file mode 100644 index 00000000..8bc16ffa --- /dev/null +++ b/0485-max-consecutive-ones.js @@ -0,0 +1,20 @@ +/** + * 485. Max Consecutive Ones + * https://leetcode.com/problems/max-consecutive-ones/ + * Difficulty: Easy + * + * Given a binary array nums, return the maximum number of consecutive 1's in the array. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var findMaxConsecutiveOnes = function(nums) { + let max = 0; + for (let i = 0, count = 0; i < nums.length; i++) { + count = nums[i] ? count + 1 : 0; + max = Math.max(max, count); + } + return max; +}; diff --git a/README.md b/README.md index 8581a639..5865b193 100644 --- a/README.md +++ b/README.md @@ -195,6 +195,7 @@ 461|[Hamming Distance](./0461-hamming-distance.js)|Easy| 463|[Island Perimeter](./0463-island-perimeter.js)|Medium| 476|[Number Complement](./0476-number-complement.js)|Easy| +485|[Max Consecutive Ones](./0485-max-consecutive-ones.js)|Easy| 491|[Non-decreasing Subsequences](./0491-non-decreasing-subsequences.js)|Medium| 492|[Construct the Rectangle](./0492-construct-the-rectangle.js)|Easy| 500|[Keyboard Row](./0500-keyboard-row.js)|Easy| From ae64efe7e0bd41889994cca859ff2bd9633f0a42 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 11 Jan 2025 16:17:56 -0600 Subject: [PATCH 451/919] Add solution #1004 --- 1004-max-consecutive-ones-iii.js | 29 +++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 30 insertions(+) create mode 100644 1004-max-consecutive-ones-iii.js diff --git a/1004-max-consecutive-ones-iii.js b/1004-max-consecutive-ones-iii.js new file mode 100644 index 00000000..ec74165e --- /dev/null +++ b/1004-max-consecutive-ones-iii.js @@ -0,0 +1,29 @@ +/** + * 1004. Max Consecutive Ones III + * https://leetcode.com/problems/max-consecutive-ones-iii/ + * Difficulty: Medium + * + * Given a binary array nums and an integer k, return the maximum number of consecutive 1's + * in the array if you can flip at most k 0's. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var longestOnes = function(nums, k) { + let left = 0; + let right = 0; + + while (right < nums.length) { + if (!nums[right]) k--; + if (k < 0) { + if (!nums[left]) k++; + left++; + } + right++; + } + + return right - left; +}; diff --git a/README.md b/README.md index 5865b193..7321642a 100644 --- a/README.md +++ b/README.md @@ -270,6 +270,7 @@ 994|[Rotting Oranges](./0994-rotting-oranges.js)|Medium| 997|[Find the Town Judge](./0997-find-the-town-judge.js)|Easy| 1002|[Find Common Characters](./1002-find-common-characters.js)|Easy| +1004|[Max Consecutive Ones III](./1004-max-consecutive-ones-iii.js)|Medium| 1009|[Complement of Base 10 Integer](./1009-complement-of-base-10-integer.js)|Easy| 1010|[Pairs of Songs With Total Durations Divisible by 60](./1010-pairs-of-songs-with-total-durations-divisible-by-60.js)|Medium| 1022|[Sum of Root To Leaf Binary Numbers](./1022-sum-of-root-to-leaf-binary-numbers.js)|Easy| From da0356e87b6a64c66778ac881296a9763b43397d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 11 Jan 2025 16:18:40 -0600 Subject: [PATCH 452/919] Add solution #724 --- 0724-find-pivot-index.js | 34 ++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 0724-find-pivot-index.js diff --git a/0724-find-pivot-index.js b/0724-find-pivot-index.js new file mode 100644 index 00000000..2d8c28a2 --- /dev/null +++ b/0724-find-pivot-index.js @@ -0,0 +1,34 @@ +/** + * 724. Find Pivot Index + * https://leetcode.com/problems/find-pivot-index/ + * Difficulty: Easy + * + * Given an array of integers nums, calculate the pivot index of this array. + * + * The pivot index is the index where the sum of all the numbers strictly to the left + * of the index is equal to the sum of all the numbers strictly to the index's right. + * + * If the index is on the left edge of the array, then the left sum is 0 because there + * are no elements to the left. This also applies to the right edge of the array. + * + * Return the leftmost pivot index. If no such index exists, return -1. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var pivotIndex = function(nums) { + let left = 0; + let right = nums.reduce((sum, n) => sum + n, 0); + + for (let i = 0; i < nums.length; i++) { + left += nums[i]; + right -= nums[i]; + if (left - nums[i] === right) { + return i; + } + } + + return -1; +}; diff --git a/README.md b/README.md index 7321642a..9ea33f78 100644 --- a/README.md +++ b/README.md @@ -233,6 +233,7 @@ 706|[Design HashMap](./0706-design-hashmap.js)|Easy| 713|[Subarray Product Less Than K](./0713-subarray-product-less-than-k.js)|Medium| 722|[Remove Comments](./0722-remove-comments.js)|Medium| +724|[Find Pivot Index](./0724-find-pivot-index.js)|Easy| 733|[Flood Fill](./0733-flood-fill.js)|Easy| 739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium| 746|[Min Cost Climbing Stairs](./0746-min-cost-climbing-stairs.js)|Easy| From cdc40b089b8edf914468011c3c9ba0259141f6dc Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 11 Jan 2025 16:20:06 -0600 Subject: [PATCH 453/919] Add solution #1732 --- 1732-find-the-highest-altitude.js | 19 +++++++++++++++++++ README.md | 1 + 2 files changed, 20 insertions(+) create mode 100644 1732-find-the-highest-altitude.js diff --git a/1732-find-the-highest-altitude.js b/1732-find-the-highest-altitude.js new file mode 100644 index 00000000..4f461551 --- /dev/null +++ b/1732-find-the-highest-altitude.js @@ -0,0 +1,19 @@ +/** + * 1732. Find the Highest Altitude + * https://leetcode.com/problems/find-the-highest-altitude/ + * Difficulty: Easy + * + * There is a biker going on a road trip. The road trip consists of n + 1 points at different + * altitudes. The biker starts his trip on point 0 with altitude equal 0. + * + * You are given an integer array gain of length n where gain[i] is the net gain in altitude + * between points i and i + 1 for all (0 <= i < n). Return the highest altitude of a point. + */ + +/** + * @param {number[]} gain + * @return {number} + */ +var largestAltitude = function(gain) { + return Math.max(...gain.reduce((all, n, i) => all.push(all[i] - n * -1) && all, [0])); +}; diff --git a/README.md b/README.md index 9ea33f78..0149f0f9 100644 --- a/README.md +++ b/README.md @@ -357,6 +357,7 @@ 1672|[Richest Customer Wealth](./1672-richest-customer-wealth.js)|Easy| 1679|[Max Number of K-Sum Pairs](./1679-max-number-of-k-sum-pairs.js)|Medium| 1716|[Calculate Money in Leetcode Bank](./1716-calculate-money-in-leetcode-bank.js)|Easy| +1732|[Find the Highest Altitude](./1732-find-the-highest-altitude.js)|Easy| 1748|[Sum of Unique Elements](./1748-sum-of-unique-elements.js)|Easy| 1768|[Merge Strings Alternately](./1768-merge-strings-alternately.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| From ef164402f4e49a06c0de6bb12c16a7c7abcd2d99 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 12 Jan 2025 10:10:59 -0600 Subject: [PATCH 454/919] Add solution #2116 --- ...ck-if-a-parentheses-string-can-be-valid.js | 54 +++++++++++++++++++ README.md | 1 + 2 files changed, 55 insertions(+) create mode 100644 2116-check-if-a-parentheses-string-can-be-valid.js diff --git a/2116-check-if-a-parentheses-string-can-be-valid.js b/2116-check-if-a-parentheses-string-can-be-valid.js new file mode 100644 index 00000000..1b54dd3a --- /dev/null +++ b/2116-check-if-a-parentheses-string-can-be-valid.js @@ -0,0 +1,54 @@ +/** + * 2116. Check if a Parentheses String Can Be Valid + * https://leetcode.com/problems/check-if-a-parentheses-string-can-be-valid/ + * Difficulty: Medium + * + * A parentheses string is a non-empty string consisting only of '(' and ')'. It is valid + * if any of the following conditions is true: + * - It is (). + * - It can be written as AB (A concatenated with B), where A and B are valid parentheses + * strings. + * - It can be written as (A), where A is a valid parentheses string. + * + * You are given a parentheses string s and a string locked, both of length n. locked is a + * binary string consisting only of '0's and '1's. For each index i of locked, + * - If locked[i] is '1', you cannot change s[i]. + * - But if locked[i] is '0', you can change s[i] to either '(' or ')'. + * + * Return true if you can make s a valid parentheses string. Otherwise, return false. + */ + +/** + * @param {string} s + * @param {string} locked + * @return {boolean} + */ +var canBeValid = function(s, locked) { + if (s.length % 2) return false; + + let symmetrical = 0; + for (let i = 0; i < s.length; i++) { + if (locked[i] === '0' || s[i] === '(') { + symmetrical++; + } else { + symmetrical--; + } + if (symmetrical < 0) { + return false; + } + } + + symmetrical = 0; + for (let i = s.length - 1; i >= 0; i--) { + if (locked[i] === '0' || s[i] === ')') { + symmetrical++; + } else { + symmetrical--; + } + if (symmetrical < 0) { + return false; + } + } + + return true; +}; diff --git a/README.md b/README.md index 0149f0f9..89957306 100644 --- a/README.md +++ b/README.md @@ -383,6 +383,7 @@ 2095|[Delete the Middle Node of a Linked List](./2095-delete-the-middle-node-of-a-linked-list.js)|Medium| 2099|[Find Subsequence of Length K With the Largest Sum](./2099-find-subsequence-of-length-k-with-the-largest-sum.js)|Medium| 2114|[Maximum Number of Words Found in Sentences](./2114-maximum-number-of-words-found-in-sentences.js)|Easy| +2116|[Check if a Parentheses String Can Be Valid](./2116-check-if-a-parentheses-string-can-be-valid.js)|Medium| 2129|[Capitalize the Title](./2129-capitalize-the-title.js)|Easy| 2154|[Keep Multiplying Found Values by Two](./2154-keep-multiplying-found-values-by-two.js)|Easy| 2185|[Counting Words With a Given Prefix](./2185-counting-words-with-a-given-prefix.js)|Easy| From 4e67038bcdeb7f8482f7fd4af1439d9a52a8e99c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 12 Jan 2025 10:11:59 -0600 Subject: [PATCH 455/919] Add solution #2390 --- 2390-removing-stars-from-a-string.js | 33 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 2390-removing-stars-from-a-string.js diff --git a/2390-removing-stars-from-a-string.js b/2390-removing-stars-from-a-string.js new file mode 100644 index 00000000..1130802e --- /dev/null +++ b/2390-removing-stars-from-a-string.js @@ -0,0 +1,33 @@ +/** + * 2390. Removing Stars From a String + * https://leetcode.com/problems/removing-stars-from-a-string/ + * Difficulty: Medium + * + * You are given a string s, which contains stars *. + * + * In one operation, you can: + * - Choose a star in s. + * - Remove the closest non-star character to its left, as well as remove the star itself. + * + * Return the string after all stars have been removed. + * + * Note: + * - The input will be generated such that the operation is always possible. + * - It can be shown that the resulting string will always be unique. + */ + +/** + * @param {string} s + * @return {string} + */ +var removeStars = function(s) { + const result = []; + for (let i = 0; i < s.length; i++) { + if (s[i] !== '*') { + result.push(s[i]); + } else { + result.pop(); + } + } + return result.join(''); +}; diff --git a/README.md b/README.md index 89957306..e6bd4ee3 100644 --- a/README.md +++ b/README.md @@ -390,6 +390,7 @@ 2215|[Find the Difference of Two Arrays](./2215-find-the-difference-of-two-arrays.js)|Easy| 2235|[Add Two Integers](./2235-add-two-integers.js)|Easy| 2244|[Minimum Rounds to Complete All Tasks](./2244-minimum-rounds-to-complete-all-tasks.js)|Medium| +2390|[Removing Stars From a String](./2390-removing-stars-from-a-string.js)|Medium| 2396|[Strictly Palindromic Number](./2396-strictly-palindromic-number.js)|Medium| 2413|[Smallest Even Multiple](./2413-smallest-even-multiple.js)|Easy| 2427|[Number of Common Factors](./2427-number-of-common-factors.js)|Easy| From 0fe8aaf5c1703762f40f4916c77bef100668e7e0 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 12 Jan 2025 10:12:33 -0600 Subject: [PATCH 456/919] Add solution #2352 --- 2352-equal-row-and-column-pairs.js | 34 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 2352-equal-row-and-column-pairs.js diff --git a/2352-equal-row-and-column-pairs.js b/2352-equal-row-and-column-pairs.js new file mode 100644 index 00000000..5a890518 --- /dev/null +++ b/2352-equal-row-and-column-pairs.js @@ -0,0 +1,34 @@ +/** + * 2352. Equal Row and Column Pairs + * https://leetcode.com/problems/equal-row-and-column-pairs/ + * Difficulty: Medium + * + * Given a 0-indexed n x n integer matrix grid, return the number of pairs (ri, cj) + * such that row ri and column cj are equal. + * + * A row and column pair is considered equal if they contain the same elements in the + * same order (i.e., an equal array). + */ + +/** + * @param {number[][]} grid + * @return {number} + */ +var equalPairs = function(grid) { + const columns = new Map(); + let count = 0; + + for (let i = 0; i < grid.length; i++) { + const column = []; + for (let j = 0; j < grid[i].length; j++) { + column.push(grid[j][i]); + } + columns.set(column.join(), (columns.get(column.join()) ?? 0) + 1); + } + + for (let i = 0; i < grid.length; i++) { + count += columns.get(grid[i].join()) ?? 0; + } + + return count; +}; diff --git a/README.md b/README.md index e6bd4ee3..c03293a3 100644 --- a/README.md +++ b/README.md @@ -390,6 +390,7 @@ 2215|[Find the Difference of Two Arrays](./2215-find-the-difference-of-two-arrays.js)|Easy| 2235|[Add Two Integers](./2235-add-two-integers.js)|Easy| 2244|[Minimum Rounds to Complete All Tasks](./2244-minimum-rounds-to-complete-all-tasks.js)|Medium| +2352|[Equal Row and Column Pairs](./2352-equal-row-and-column-pairs.js)|Medium| 2390|[Removing Stars From a String](./2390-removing-stars-from-a-string.js)|Medium| 2396|[Strictly Palindromic Number](./2396-strictly-palindromic-number.js)|Medium| 2413|[Smallest Even Multiple](./2413-smallest-even-multiple.js)|Easy| From a594bbebae6b3cc39a643b93227ae474ce2788a1 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 12 Jan 2025 10:14:20 -0600 Subject: [PATCH 457/919] Add solution #649 --- 0649-dota2-senate.js | 53 ++++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 54 insertions(+) create mode 100644 0649-dota2-senate.js diff --git a/0649-dota2-senate.js b/0649-dota2-senate.js new file mode 100644 index 00000000..d47cf36c --- /dev/null +++ b/0649-dota2-senate.js @@ -0,0 +1,53 @@ +/** + * 649. Dota2 Senate + * https://leetcode.com/problems/dota2-senate/ + * Difficulty: Medium + * + * In the world of Dota2, there are two parties: the Radiant and the Dire. + * + * The Dota2 senate consists of senators coming from two parties. Now the Senate wants + * to decide on a change in the Dota2 game. The voting for this change is a round-based + * procedure. In each round, each senator can exercise one of the two rights: + * - Ban one senator's right: A senator can make another senator lose all his rights in + * this and all the following rounds. + * - Announce the victory: If this senator found the senators who still have rights to + * vote are all from the same party, he can announce the victory and decide on the + * change in the game. + * + * Given a string senate representing each senator's party belonging. The character 'R' + * and 'D' represent the Radiant party and the Dire party. Then if there are n senators, + * the size of the given string will be n. + * + * The round-based procedure starts from the first senator to the last senator in the + * given order. This procedure will last until the end of voting. All the senators who + * have lost their rights will be skipped during the procedure. + * + * Suppose every senator is smart enough and will play the best strategy for his own + * party. Predict which party will finally announce the victory and change the Dota2 + * game. The output should be "Radiant" or "Dire". +*/ + +/** + * @param {string} senate + * @return {string} + */ +var predictPartyVictory = function(senate) { + const rQueue = []; + const dQueue = []; + + for (let i = 0; i < senate.length; i++) { + if (senate[i] === 'R') rQueue.push(i); + else dQueue.push(i); + } + + while (rQueue.length && dQueue.length) { + const [rIndex, dIndex] = [rQueue.shift(), dQueue.shift()]; + if (rIndex < dIndex) { + rQueue.push(rIndex + senate.length); + } else { + dQueue.push(dIndex + senate.length); + } + } + + return rQueue.length > 0 ? 'Radiant' : 'Dire'; +}; diff --git a/README.md b/README.md index c03293a3..4b765927 100644 --- a/README.md +++ b/README.md @@ -222,6 +222,7 @@ 643|[Maximum Average Subarray I](./0643-maximum-average-subarray-i.js)|Easy| 645|[Set Mismatch](./0645-set-mismatch.js)|Medium| 648|[Replace Words](./0648-replace-words.js)|Medium| +649|[Dota2 Senate](./0649-dota2-senate.js)|Medium| 653|[Two Sum IV - Input is a BST](./0653-two-sum-iv-input-is-a-bst.js)|Easy| 680|[Valid Palindrome II](./0680-valid-palindrome-ii.js)|Easy| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| From 1c752e63f44d70936f8a3ff71925921abfe5d6a0 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 12 Jan 2025 10:15:30 -0600 Subject: [PATCH 458/919] Add solution #933 --- 0933-number-of-recent-calls.js | 35 ++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 36 insertions(+) create mode 100644 0933-number-of-recent-calls.js diff --git a/0933-number-of-recent-calls.js b/0933-number-of-recent-calls.js new file mode 100644 index 00000000..8af36eb7 --- /dev/null +++ b/0933-number-of-recent-calls.js @@ -0,0 +1,35 @@ +/** + * 933. Number of Recent Calls + * https://leetcode.com/problems/number-of-recent-calls/ + * Difficulty: Easy + * + * You have a RecentCounter class which counts the number of recent requests within + * a certain time frame. + * + * Implement the RecentCounter class: + * - RecentCounter() Initializes the counter with zero recent requests. + * - int ping(int t) Adds a new request at time t, where t represents some time in + * milliseconds, and returns the number of requests that has happened in the past + * 3000 milliseconds (including the new request). Specifically, return the number + * of requests that have happened in the inclusive range [t - 3000, t]. + * + * It is guaranteed that every call to ping uses a strictly larger value of t than + * the previous call. + */ + + +var RecentCounter = function() { + this.queue = []; +}; + +/** + * @param {number} t + * @return {number} + */ +RecentCounter.prototype.ping = function(t) { + this.queue.push(t); + while (this.queue[0] < t - 3000) { + this.queue.shift(); + } + return this.queue.length; +}; diff --git a/README.md b/README.md index 4b765927..b1790e0c 100644 --- a/README.md +++ b/README.md @@ -263,6 +263,7 @@ 925|[Long Pressed Name](./0925-long-pressed-name.js)|Easy| 926|[Flip String to Monotone Increasing](./0926-flip-string-to-monotone-increasing.js)|Medium| 929|[Unique Email Addresses](./0929-unique-email-addresses.js)|Easy| +933|[Number of Recent Calls](./0933-number-of-recent-calls.js)|Easy| 966|[Vowel Spellchecker](./0966-vowel-spellchecker.js)|Medium| 970|[Powerful Integers](./0970-powerful-integers.js)|Easy| 976|[Largest Perimeter Triangle](./0976-largest-perimeter-triangle.js)|Easy| From c4a7750c3b989ebcd12a06d3cf5997b529a23375 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 12 Jan 2025 10:17:03 -0600 Subject: [PATCH 459/919] Add solution #394 --- 0394-decode-string.js | 45 +++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 46 insertions(+) create mode 100644 0394-decode-string.js diff --git a/0394-decode-string.js b/0394-decode-string.js new file mode 100644 index 00000000..0dda623f --- /dev/null +++ b/0394-decode-string.js @@ -0,0 +1,45 @@ +/** + * 394. Decode String + * https://leetcode.com/problems/decode-string/ + * Difficulty: Medium + * + * Given an encoded string, return its decoded string. + * + * The encoding rule is: k[encoded_string], where the encoded_string inside the square + * brackets is being repeated exactly k times. Note that k is guaranteed to be a + * positive integer. + * + * You may assume that the input string is always valid; there are no extra white spaces, + * square brackets are well-formed, etc. Furthermore, you may assume that the original + * data does not contain any digits and that digits are only for those repeat numbers, k. + * For example, there will not be input like 3a or 2[4]. + * + * The test cases are generated so that the length of the output will never exceed 105. + */ + +/** + * @param {string} s + * @return {string} + */ +var decodeString = function(s) { + const stack = []; + let result = ''; + let decoder = 0; + + for (const c of s) { + if (!isNaN(c) && Number(c) >= 0 && Number(c) <= 9) { + decoder = Number(c) + decoder * 10; + } else if (c === '[') { + stack.push([result, decoder]); + result = ''; + decoder = 0; + } else if (c === ']') { + const [previous, count] = stack.pop(); + result = previous + result.repeat(count); + } else { + result += c; + } + } + + return result; +}; diff --git a/README.md b/README.md index b1790e0c..d272ba9f 100644 --- a/README.md +++ b/README.md @@ -181,6 +181,7 @@ 383|[Ransom Note](./0383-ransom-note.js)|Easy| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| 392|[Is Subsequence](./0392-is-subsequence.js)|Easy| +394|[Decode String](./0394-decode-string.js)|Medium| 405|[Convert a Number to Hexadecimal](./0405-convert-a-number-to-hexadecimal.js)|Easy| 412|[Fizz Buzz](./0412-fizz-buzz.js)|Easy| 414|[Third Maximum Number](./0414-third-maximum-number.js)|Easy| From b0f103ba7cafec028bb1f9a88a39bb0fd41de2ff Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 12 Jan 2025 10:17:47 -0600 Subject: [PATCH 460/919] Add solution #735 --- 0735-asteroid-collision.js | 40 ++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 41 insertions(+) create mode 100644 0735-asteroid-collision.js diff --git a/0735-asteroid-collision.js b/0735-asteroid-collision.js new file mode 100644 index 00000000..f1712014 --- /dev/null +++ b/0735-asteroid-collision.js @@ -0,0 +1,40 @@ +/** + * 735. Asteroid Collision + * https://leetcode.com/problems/asteroid-collision/ + * Difficulty: Medium + * + * We are given an array asteroids of integers representing asteroids in a row. The indices + * of the asteriod in the array represent their relative position in space. + * + * For each asteroid, the absolute value represents its size, and the sign represents its + * direction (positive meaning right, negative meaning left). Each asteroid moves at the + * same speed. + * + * Find out the state of the asteroids after all collisions. If two asteroids meet, the + * smaller one will explode. If both are the same size, both will explode. Two asteroids + * moving in the same direction will never meet. + */ + +/** + * @param {number[]} asteroids + * @return {number[]} + */ +var asteroidCollision = function(asteroids) { + const result = []; + + for (let i = 0; i < asteroids.length; i++) { + const previous = result[result.length - 1]; + const current = asteroids[i]; + + if (!result.length || previous < 0 || current > 0) { + result.push(current); + } else if (-current === previous) { + result.pop(); + } else if (-current > previous) { + result.pop(); + i--; + } + } + + return result; +}; diff --git a/README.md b/README.md index d272ba9f..98580f3f 100644 --- a/README.md +++ b/README.md @@ -237,6 +237,7 @@ 722|[Remove Comments](./0722-remove-comments.js)|Medium| 724|[Find Pivot Index](./0724-find-pivot-index.js)|Easy| 733|[Flood Fill](./0733-flood-fill.js)|Easy| +735|[Asteroid Collision](./0735-asteroid-collision.js)|Medium| 739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium| 746|[Min Cost Climbing Stairs](./0746-min-cost-climbing-stairs.js)|Easy| 747|[Largest Number At Least Twice of Others](./0747-largest-number-at-least-twice-of-others.js)|Easy| From da63bad8909221e6b1e98a187cbca27b30186a8e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 13 Jan 2025 01:30:11 -0600 Subject: [PATCH 461/919] Add solution #415 --- 0415-add-strings.js | 33 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 0415-add-strings.js diff --git a/0415-add-strings.js b/0415-add-strings.js new file mode 100644 index 00000000..219fe302 --- /dev/null +++ b/0415-add-strings.js @@ -0,0 +1,33 @@ +/** + * 415. Add Strings + * https://leetcode.com/problems/add-strings/ + * Difficulty: Easy + * + * Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and + * num2 as a string. + * + * You must solve the problem without using any built-in library for handling large integers (such + * as BigInteger). You must also not convert the inputs to integers directly. + */ + +/** + * @param {string} num1 + * @param {string} num2 + * @return {string} + */ +var addStrings = function(num1, num2) { + let result = ''; + + for (let i = num1.length - 1, j = num2.length - 1, carry = 0; i > -1 || j > -1 || carry === 1;) { + if (i > -1) { + carry += num1.charCodeAt(i--) - 48; + } + if (j > -1) { + carry += num2.charCodeAt(j--) - 48; + } + result = (carry % 10) + result; + carry = Math.floor(carry / 10); + } + + return result; +}; diff --git a/README.md b/README.md index 98580f3f..66e3319d 100644 --- a/README.md +++ b/README.md @@ -185,6 +185,7 @@ 405|[Convert a Number to Hexadecimal](./0405-convert-a-number-to-hexadecimal.js)|Easy| 412|[Fizz Buzz](./0412-fizz-buzz.js)|Easy| 414|[Third Maximum Number](./0414-third-maximum-number.js)|Easy| +415|[Add Strings](./0415-add-strings.js)|Easy| 419|[Battleships in a Board](./0419-battleships-in-a-board.js)|Medium| 435|[Non-overlapping Intervals](./0435-non-overlapping-intervals.js)|Medium| 442|[Find All Duplicates in an Array](./0442-find-all-duplicates-in-an-array.js)|Medium| From 6f7e40ba82f98736b9503912c429960b8e1a4b79 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 13 Jan 2025 01:31:35 -0600 Subject: [PATCH 462/919] Add solution #1466 --- ...to-make-all-paths-lead-to-the-city-zero.js | 49 +++++++++++++++++++ README.md | 1 + 2 files changed, 50 insertions(+) create mode 100644 1466-reorder-routes-to-make-all-paths-lead-to-the-city-zero.js diff --git a/1466-reorder-routes-to-make-all-paths-lead-to-the-city-zero.js b/1466-reorder-routes-to-make-all-paths-lead-to-the-city-zero.js new file mode 100644 index 00000000..a94de6fd --- /dev/null +++ b/1466-reorder-routes-to-make-all-paths-lead-to-the-city-zero.js @@ -0,0 +1,49 @@ +/** + * 1466. Reorder Routes to Make All Paths Lead to the City Zero + * https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/ + * Difficulty: Medium + * + * There are n cities numbered from 0 to n - 1 and n - 1 roads such that there is only one way + * to travel between two different cities (this network form a tree). Last year, The ministry + * of transport decided to orient the roads in one direction because they are too narrow. + * + * Roads are represented by connections where connections[i] = [ai, bi] represents a road from + * city ai to city bi. + * + * This year, there will be a big event in the capital (city 0), and many people want to travel + * to this city. + * + * Your task consists of reorienting some roads such that each city can visit the city 0. Return + * the minimum number of edges changed. + +It's guaranteed that each city can reach city 0 after reorder. + */ + +/** + * @param {number} n + * @param {number[][]} connections + * @return {number} + */ +var minReorder = function(n, connections) { + const graph = new Array(n).fill(null).map(() => []); + + connections.forEach(([k, v]) => { + graph[k].push([v, 1]); + graph[v].push([k, 0]); + }); + + function dfs(node, parent) { + let count = 0; + + graph[node].forEach(([k, v]) => { + if (k !== parent) { + count += v; + count += dfs(k, node); + } + }); + + return count; + } + + return dfs(0, -1); +}; diff --git a/README.md b/README.md index 66e3319d..edf0ab5e 100644 --- a/README.md +++ b/README.md @@ -336,6 +336,7 @@ 1456|[Maximum Number of Vowels in a Substring of Given Length](./1456-maximum-number-of-vowels-in-a-substring-of-given-length.js)|Medium| 1460|[Make Two Arrays Equal by Reversing Sub-arrays](./1460-make-two-arrays-equal-by-reversing-sub-arrays.js)|Easy| 1464|[Maximum Product of Two Elements in an Array](./1464-maximum-product-of-two-elements-in-an-array.js)|Easy| +1466|[Reorder Routes to Make All Paths Lead to the City Zero](./1466-reorder-routes-to-make-all-paths-lead-to-the-city-zero.js)|Medium| 1470|[Shuffle the Array](./1470-shuffle-the-array.js)|Easy| 1472|[Design Browser History](./1472-design-browser-history.js)|Medium| 1475|[Final Prices With a Special Discount in a Shop](./1475-final-prices-with-a-special-discount-in-a-shop.js)|Easy| From 638d08f491a567d4020f877ac933ee30e46f6751 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 13 Jan 2025 01:32:44 -0600 Subject: [PATCH 463/919] Add solution #547 --- 0547-number-of-provinces.js | 44 +++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 45 insertions(+) create mode 100644 0547-number-of-provinces.js diff --git a/0547-number-of-provinces.js b/0547-number-of-provinces.js new file mode 100644 index 00000000..d0e3bff6 --- /dev/null +++ b/0547-number-of-provinces.js @@ -0,0 +1,44 @@ +/** + * 547. Number of Provinces + * https://leetcode.com/problems/number-of-provinces/ + * Difficulty: Medium + * + * There are n cities. Some of them are connected, while some are not. If city a is connected + * directly with city b, and city b is connected directly with city c, then city a is connected + * indirectly with city c. + * + * A province is a group of directly or indirectly connected cities and no other cities outside + * of the group. + * + * You are given an n x n matrix isConnected where isConnected[i][j] = 1 if the ith city and the + * jth city are directly connected, and isConnected[i][j] = 0 otherwise. + +Return the total number of provinces. + */ + +/** + * @param {number[][]} isConnected + * @return {number} + */ +var findCircleNum = function(isConnected) { + const seen = new Array(isConnected.length).fill(0); + let result = 0; + + function dfs(node) { + seen[node] = 1; + for (let i = 0; i < isConnected.length; i++) { + if (isConnected[node][i] === 1 && !seen[i]) { + dfs(i); + } + } + } + + for (let i = 0; i < isConnected.length; i++) { + if (!seen[i]) { + result++; + dfs(i); + } + } + + return result; +}; diff --git a/README.md b/README.md index edf0ab5e..caa38382 100644 --- a/README.md +++ b/README.md @@ -210,6 +210,7 @@ 520|[Detect Capital](./0520-detect-capital.js)|Easy| 541|[Reverse String II](./0541-reverse-string-ii.js)|Easy| 542|[01 Matrix](./0542-01-matrix.js)|Medium| +547|[Number of Provinces](./0547-number-of-provinces.js)|Medium| 551|[Student Attendance Record I](./0551-student-attendance-record-i.js)|Easy| 557|[Reverse Words in a String III](./0557-reverse-words-in-a-string-iii.js)|Easy| 563|[Binary Tree Tilt](./0563-binary-tree-tilt.js)|Easy| From 3dad2b52b7eeba4590b7287f5ababf2614a15b8c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 13 Jan 2025 01:33:34 -0600 Subject: [PATCH 464/919] Add solution #841 --- 0841-keys-and-rooms.js | 28 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 29 insertions(+) create mode 100644 0841-keys-and-rooms.js diff --git a/0841-keys-and-rooms.js b/0841-keys-and-rooms.js new file mode 100644 index 00000000..dc07a591 --- /dev/null +++ b/0841-keys-and-rooms.js @@ -0,0 +1,28 @@ +/** + * 841. Keys and Rooms + * https://leetcode.com/problems/keys-and-rooms/ + * Difficulty: Medium + * + * 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. + */ + +/** + * @param {number[][]} rooms + * @return {boolean} + */ +var canVisitAllRooms = function(rooms) { + const set = new Set([0]); + for (const key of set) { + rooms[key].forEach(value => set.add(value)); + } + return set.size === rooms.length; +}; diff --git a/README.md b/README.md index caa38382..b8ae353c 100644 --- a/README.md +++ b/README.md @@ -252,6 +252,7 @@ 821|[Shortest Distance to a Character](./0821-shortest-distance-to-a-character.js)|Easy| 824|[Goat Latin](./0824-goat-latin.js)|Easy| 831|[Masking Personal Information](./0831-masking-personal-information.js)|Medium| +841|[Keys and Rooms](./0841-keys-and-rooms.js)|Medium| 844|[Backspace String Compare](./0844-backspace-string-compare.js)|Easy| 846|[Hand of Straights](./0846-hand-of-straights.js)|Medium| 867|[Transpose Matrix](./0867-transpose-matrix.js)|Easy| From f0f2d90566500982f0fbc9aacb5e8711a87ab216 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 13 Jan 2025 01:34:27 -0600 Subject: [PATCH 465/919] Add solution #2130 --- 2130-maximum-twin-sum-of-a-linked-list.js | 41 +++++++++++++++++++++++ README.md | 1 + 2 files changed, 42 insertions(+) create mode 100644 2130-maximum-twin-sum-of-a-linked-list.js diff --git a/2130-maximum-twin-sum-of-a-linked-list.js b/2130-maximum-twin-sum-of-a-linked-list.js new file mode 100644 index 00000000..038554da --- /dev/null +++ b/2130-maximum-twin-sum-of-a-linked-list.js @@ -0,0 +1,41 @@ +/** + * 2130. Maximum Twin Sum of a Linked List + * https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/ + * Difficulty: Medium + * + * In a linked list of size n, where n is even, the ith node (0-indexed) of the linked list is known + * as the twin of the (n-1-i)th node, if 0 <= i <= (n / 2) - 1. + * + * For example, if n = 4, then node 0 is the twin of node 3, and node 1 is the twin of node 2. These + * are the only nodes with twins for n = 4. + * + * The twin sum is defined as the sum of a node and its twin. + * + * Given the head of a linked list with even length, return the maximum twin sum of the linked list. + */ + +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @return {number} + */ +var pairSum = function(head) { + const stack = []; + while (head) { + stack.push(head.val); + head = head.next; + } + + let max = 0; + for (let i = 0; i < stack.length; i++) { + max = Math.max(max, stack[i] + stack[stack.length - 1 - i]); + } + + return max; +}; diff --git a/README.md b/README.md index b8ae353c..f97213b8 100644 --- a/README.md +++ b/README.md @@ -393,6 +393,7 @@ 2114|[Maximum Number of Words Found in Sentences](./2114-maximum-number-of-words-found-in-sentences.js)|Easy| 2116|[Check if a Parentheses String Can Be Valid](./2116-check-if-a-parentheses-string-can-be-valid.js)|Medium| 2129|[Capitalize the Title](./2129-capitalize-the-title.js)|Easy| +2130|[Maximum Twin Sum of a Linked List](./2130-maximum-twin-sum-of-a-linked-list.js)|Medium| 2154|[Keep Multiplying Found Values by Two](./2154-keep-multiplying-found-values-by-two.js)|Easy| 2185|[Counting Words With a Given Prefix](./2185-counting-words-with-a-given-prefix.js)|Easy| 2215|[Find the Difference of Two Arrays](./2215-find-the-difference-of-two-arrays.js)|Easy| From ad1b9b94024d91de0967ee7326300063c89e01a1 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 13 Jan 2025 01:35:18 -0600 Subject: [PATCH 466/919] Add solution #328 --- 0328-odd-even-linked-list.js | 43 ++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 44 insertions(+) create mode 100644 0328-odd-even-linked-list.js diff --git a/0328-odd-even-linked-list.js b/0328-odd-even-linked-list.js new file mode 100644 index 00000000..ca962d4e --- /dev/null +++ b/0328-odd-even-linked-list.js @@ -0,0 +1,43 @@ +/** + * 328. Odd Even Linked List + * https://leetcode.com/problems/odd-even-linked-list/ + * Difficulty: Medium + * + * Given the head of a singly linked list, group all the nodes with odd indices together followed + * by the nodes with even indices, and return the reordered list. + * + * The first node is considered odd, and the second node is even, and so on. + * + * Note that the relative order inside both the even and odd groups should remain as it was in + * the input. + * + * You must solve the problem in O(1) extra space complexity and O(n) time complexity. + */ + +/** + * 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 oddEvenList = function(head) { + if (!head) return head; + + const even = head.next; + let odd = head; + + while (odd.next && odd.next.next) { + const pointer = odd.next; + odd.next = odd.next.next; + odd = odd.next; + pointer.next = odd.next; + } + + odd.next = even; + return head; +}; diff --git a/README.md b/README.md index f97213b8..62f94c6b 100644 --- a/README.md +++ b/README.md @@ -167,6 +167,7 @@ 290|[Word Pattern](./0290-word-pattern.js)|Easy| 316|[Remove Duplicate Letters](./0316-remove-duplicate-letters.js)|Medium| 326|[Power of Three](./0326-power-of-three.js)|Easy| +328|[Odd Even Linked List](./0328-odd-even-linked-list.js)|Medium| 334|[Increasing Triplet Subsequence](./0334-increasing-triplet-subsequence.js)|Medium| 342|[Power of Four](./0342-power-of-four.js)|Easy| 344|[Reverse String](./0344-reverse-string.js)|Easy| From b5b3a7dfbe2d7ae24a791b31af0ca320c30485f5 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 13 Jan 2025 01:36:15 -0600 Subject: [PATCH 467/919] Add solution #3223 --- ...nimum-length-of-string-after-operations.js | 29 +++++++++++++++++++ README.md | 1 + 2 files changed, 30 insertions(+) create mode 100644 3223-minimum-length-of-string-after-operations.js diff --git a/3223-minimum-length-of-string-after-operations.js b/3223-minimum-length-of-string-after-operations.js new file mode 100644 index 00000000..9eb7f0e1 --- /dev/null +++ b/3223-minimum-length-of-string-after-operations.js @@ -0,0 +1,29 @@ +/** + * 3223. Minimum Length of String After Operations + * https://leetcode.com/problems/minimum-length-of-string-after-operations/ + * Difficulty: Medium + * + * You are given a string s. + * + * You can perform the following process on s any number of times: + * - Choose an index i in the string such that there is at least one character to the left of + * index i that is equal to s[i], and at least one character to the right that is also equal + * to s[i]. + * - Delete the closest character to the left of index i that is equal to s[i]. + * - Delete the closest character to the right of index i that is equal to s[i]. + * + * Return the minimum length of the final string s that you can achieve. + */ + +/** + * @param {string} s + * @return {number} + */ +var minimumLength = function(s) { + if (s.length < 3) return s.length; + + const map = new Map(); + s.split('').forEach(c => map.set(c, (map.get(c) ?? 0) + 1)); + + return [...map.values()].reduce((count, n) => count + (n % 2 ? n % 2 : 2), 0); +}; diff --git a/README.md b/README.md index 62f94c6b..48cb50ef 100644 --- a/README.md +++ b/README.md @@ -442,6 +442,7 @@ 2724|[Sort By](./2724-sort-by.js)|Easy| 3042|[Count Prefix and Suffix Pairs I](./3042-count-prefix-and-suffix-pairs-i.js)|Easy| 3110|[Score of a String](./3110-score-of-a-string.js)|Easy| +3223|[Minimum Length of String After Operations](./3223-minimum-length-of-string-after-operations.js)|Medium| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| 3396|[Minimum Number of Operations to Make Elements in Array Distinct](./3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy| 3397|[Maximum Number of Distinct Elements After Operations](./3397-maximum-number-of-distinct-elements-after-operations.js)|Medium| From f99746256aa81814f7b9b81023799a8254044f23 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 14 Jan 2025 00:23:02 -0600 Subject: [PATCH 468/919] Add solution #872 --- 0872-leaf-similar-trees.js | 45 ++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 46 insertions(+) create mode 100644 0872-leaf-similar-trees.js diff --git a/0872-leaf-similar-trees.js b/0872-leaf-similar-trees.js new file mode 100644 index 00000000..6fa8fcf0 --- /dev/null +++ b/0872-leaf-similar-trees.js @@ -0,0 +1,45 @@ +/** + * 872. Leaf-Similar Trees + * https://leetcode.com/problems/leaf-similar-trees/ + * Difficulty: Easy + * + * 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. + */ + +/** + * 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) { + return traverse(root1, []).toString() === traverse(root2, []).toString(); +}; + +function traverse(root, result) { + if (!root.left && !root.right) { + result.push(root.val); + } + if (root.left) { + traverse(root.left, result); + } + if (root.right) { + traverse(root.right, result); + } + return result; +} diff --git a/README.md b/README.md index 48cb50ef..e88028e2 100644 --- a/README.md +++ b/README.md @@ -257,6 +257,7 @@ 844|[Backspace String Compare](./0844-backspace-string-compare.js)|Easy| 846|[Hand of Straights](./0846-hand-of-straights.js)|Medium| 867|[Transpose Matrix](./0867-transpose-matrix.js)|Easy| +872|[Leaf-Similar Trees](./0872-leaf-similar-trees.js)|Easy| 876|[Middle of the Linked List](./0876-middle-of-the-linked-list.js)|Easy| 884|[Uncommon Words from Two Sentences](./0884-uncommon-words-from-two-sentences.js)|Easy| 890|[Find and Replace Pattern](./0890-find-and-replace-pattern.js)|Medium| From 15239ff4b2f1792187067f8394f3dd43da897670 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 14 Jan 2025 00:23:39 -0600 Subject: [PATCH 469/919] Add solution #2723 --- 2723-add-two-promises.js | 18 ++++++++++++++++++ README.md | 1 + 2 files changed, 19 insertions(+) create mode 100644 2723-add-two-promises.js diff --git a/2723-add-two-promises.js b/2723-add-two-promises.js new file mode 100644 index 00000000..13fe5612 --- /dev/null +++ b/2723-add-two-promises.js @@ -0,0 +1,18 @@ +/** + * 2723. Add Two Promises + * https://leetcode.com/problems/add-two-promises/ + * Difficulty: Easy + * + * Given two promises promise1 and promise2, return a new promise. promise1 and promise2 + * will both resolve with a number. The returned promise should resolve with the sum of + * the two numbers. + */ + +/** + * @param {Promise} promise1 + * @param {Promise} promise2 + * @return {Promise} + */ +var addTwoPromises = async function(promise1, promise2) { + return Promise.all([promise1, promise2]).then(([a, b]) => a + b); +}; diff --git a/README.md b/README.md index e88028e2..9cfee7bd 100644 --- a/README.md +++ b/README.md @@ -440,6 +440,7 @@ 2715|[Timeout Cancellation](./2715-timeout-cancellation.js)|Easy| 2721|[Execute Asynchronous Functions in Parallel](./2721-execute-asynchronous-functions-in-parallel.js)|Medium| 2722|[Join Two Arrays by ID](./2722-join-two-arrays-by-id.js)|Medium| +2723|[Add Two Promises](./2723-add-two-promises.js)|Easy| 2724|[Sort By](./2724-sort-by.js)|Easy| 3042|[Count Prefix and Suffix Pairs I](./3042-count-prefix-and-suffix-pairs-i.js)|Easy| 3110|[Score of a String](./3110-score-of-a-string.js)|Easy| From 4e0a1bd2594f8923abaa1dd46f817ed50ec01f84 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 14 Jan 2025 00:25:04 -0600 Subject: [PATCH 470/919] Add solution #2693 --- 2693-call-function-with-custom-context.js | 35 +++++++++++++++++++++++ README.md | 1 + 2 files changed, 36 insertions(+) create mode 100644 2693-call-function-with-custom-context.js diff --git a/2693-call-function-with-custom-context.js b/2693-call-function-with-custom-context.js new file mode 100644 index 00000000..34e60f9b --- /dev/null +++ b/2693-call-function-with-custom-context.js @@ -0,0 +1,35 @@ +/** + * 2693. Call Function with Custom Context + * https://leetcode.com/problems/call-function-with-custom-context/ + * Difficulty: Medium + * + * Enhance all functions to have the callPolyfill method. The method accepts an object obj as + * its first parameter and any number of additional arguments. The obj becomes the this context + * for the function. The additional arguments are passed to the function (that the callPolyfill + * method belongs on). + * + * For example if you had the function: + * + * function tax(price, taxRate) { + * const totalCost = price * (1 + taxRate); + * console.log(`The cost of ${this.item} is ${totalCost}`); + * } + * + * Calling this function like tax(10, 0.1) will log "The cost of undefined is 11". This is + * because the this context was not defined. + * + * However, calling the function like tax.callPolyfill({item: "salad"}, 10, 0.1) will log "The + * cost of salad is 11". The this context was appropriately set, and the function logged an + * appropriate output. + * + * Please solve this without using the built-in Function.call method. + */ + +/** + * @param {Object} context + * @param {Array} args + * @return {null|boolean|number|string|Array|Object} + */ +Function.prototype.callPolyfill = function(context, ...args) { + return this.bind(context)(...args); +} diff --git a/README.md b/README.md index 9cfee7bd..12ca3efb 100644 --- a/README.md +++ b/README.md @@ -433,6 +433,7 @@ 2666|[Allow One Function Call](./2666-allow-one-function-call.js)|Easy| 2667|[Create Hello World Function](./2667-create-hello-world-function.js)|Easy| 2677|[Chunk Array](./2677-chunk-array.js)|Easy| +2693|[Call Function with Custom Context](./2693-call-function-with-custom-context.js)|Medium| 2695|[Array Wrapper](./2695-array-wrapper.js)|Easy| 2703|[Return Length of Arguments Passed](./2703-return-length-of-arguments-passed.js)|Easy| 2704|[To Be Or Not To Be](./2704-to-be-or-not-to-be.js)|Easy| From a6de9398e5c31a130b6f2fe3d1fd3a2f5ec5713d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 14 Jan 2025 00:26:28 -0600 Subject: [PATCH 471/919] Add solution #1005 --- ...maximize-sum-of-array-after-k-negations.js | 27 +++++++++++++++++++ README.md | 1 + 2 files changed, 28 insertions(+) create mode 100644 1005-maximize-sum-of-array-after-k-negations.js diff --git a/1005-maximize-sum-of-array-after-k-negations.js b/1005-maximize-sum-of-array-after-k-negations.js new file mode 100644 index 00000000..c8a65c88 --- /dev/null +++ b/1005-maximize-sum-of-array-after-k-negations.js @@ -0,0 +1,27 @@ +/** + * 1005. Maximize Sum Of Array After K Negations + * https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/ + * Difficulty: Easy + * + * Given an integer array nums and an integer k, modify the array in the following way: + * - choose an index i and replace nums[i] with -nums[i]. + * + * You should apply this process exactly k times. You may choose the same index i + * multiple times. + * + * Return the largest possible sum of the array after modifying it in this way. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var largestSumAfterKNegations = function(nums, k) { + while (k) { + const i = nums.indexOf(Math.min(...nums)); + nums[i] *= -1; + k--; + } + return nums.reduce((sum, n) => sum + n, 0); +}; diff --git a/README.md b/README.md index 12ca3efb..18600c84 100644 --- a/README.md +++ b/README.md @@ -281,6 +281,7 @@ 997|[Find the Town Judge](./0997-find-the-town-judge.js)|Easy| 1002|[Find Common Characters](./1002-find-common-characters.js)|Easy| 1004|[Max Consecutive Ones III](./1004-max-consecutive-ones-iii.js)|Medium| +1005|[Maximize Sum Of Array After K Negations](./1005-maximize-sum-of-array-after-k-negations.js)|Easy| 1009|[Complement of Base 10 Integer](./1009-complement-of-base-10-integer.js)|Easy| 1010|[Pairs of Songs With Total Durations Divisible by 60](./1010-pairs-of-songs-with-total-durations-divisible-by-60.js)|Medium| 1022|[Sum of Root To Leaf Binary Numbers](./1022-sum-of-root-to-leaf-binary-numbers.js)|Easy| From cf53d29ef1f1c77313ec9415df73df13aeb24033 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 14 Jan 2025 00:27:01 -0600 Subject: [PATCH 472/919] Add solution #338 --- 0338-counting-bits.js | 20 ++++++++++++++++++++ README.md | 1 + 2 files changed, 21 insertions(+) create mode 100644 0338-counting-bits.js diff --git a/0338-counting-bits.js b/0338-counting-bits.js new file mode 100644 index 00000000..728daff1 --- /dev/null +++ b/0338-counting-bits.js @@ -0,0 +1,20 @@ +/** + * 338. Counting Bits + * https://leetcode.com/problems/counting-bits/ + * Difficulty: Easy + * + * Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), + * ans[i] is the number of 1's in the binary representation of i. + */ + +/** + * @param {number} n + * @return {number[]} + */ +var countBits = function(n) { + const result = new Array(n + 1).fill(0); + for (let i = 0; i <= n; i++) { + result[i] = result[i >> 1] + (i & 1); + } + return result; +}; diff --git a/README.md b/README.md index 18600c84..1278d521 100644 --- a/README.md +++ b/README.md @@ -169,6 +169,7 @@ 326|[Power of Three](./0326-power-of-three.js)|Easy| 328|[Odd Even Linked List](./0328-odd-even-linked-list.js)|Medium| 334|[Increasing Triplet Subsequence](./0334-increasing-triplet-subsequence.js)|Medium| +338|[Counting Bits](./0338-counting-bits.js)|Easy| 342|[Power of Four](./0342-power-of-four.js)|Easy| 344|[Reverse String](./0344-reverse-string.js)|Easy| 345|[Reverse Vowels of a String](./0345-reverse-vowels-of-a-string.js)|Easy| From 9b136bda364607e8e6707788bdf0a5a2475d7306 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 14 Jan 2025 00:28:37 -0600 Subject: [PATCH 473/919] Add solution #2657 --- ...d-the-prefix-common-array-of-two-arrays.js | 34 +++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 2657-find-the-prefix-common-array-of-two-arrays.js diff --git a/2657-find-the-prefix-common-array-of-two-arrays.js b/2657-find-the-prefix-common-array-of-two-arrays.js new file mode 100644 index 00000000..e284d390 --- /dev/null +++ b/2657-find-the-prefix-common-array-of-two-arrays.js @@ -0,0 +1,34 @@ +/** + * 2657. Find the Prefix Common Array of Two Arrays + * https://leetcode.com/problems/find-the-prefix-common-array-of-two-arrays/ + * Difficulty: Medium + * + * You are given two 0-indexed integer permutations A and B of length n. + * + * A prefix common array of A and B is an array C such that C[i] is equal to the count of + * numbers that are present at or before the index i in both A and B. + * + * Return the prefix common array of A and B. + * + * A sequence of n integers is called a permutation if it contains all integers from 1 to + * n exactly once. + */ + +/** + * @param {number[]} A + * @param {number[]} B + * @return {number[]} + */ +var findThePrefixCommonArray = function(A, B) { + const result = []; + + for (let i = 0, count = 0, set = new Set(); i < A.length; i++) { + if (set.has(A[i])) count++; + if (set.has(B[i])) count++; + if (A[i] === B[i]) count++; + [A[i], B[i]].forEach(n => set.add(n)); + result.push(count); + } + + return result; +}; diff --git a/README.md b/README.md index 1278d521..562454c0 100644 --- a/README.md +++ b/README.md @@ -431,6 +431,7 @@ 2648|[Generate Fibonacci Sequence](./2648-generate-fibonacci-sequence.js)|Easy| 2649|[Nested Array Generator](./2649-nested-array-generator.js)|Medium| 2650|[Design Cancellable Function](./2650-design-cancellable-function.js)|Hard| +2657|[Find the Prefix Common Array of Two Arrays](./2657-find-the-prefix-common-array-of-two-arrays.js)|Medium| 2665|[Counter II](./2665-counter-ii.js)|Easy| 2666|[Allow One Function Call](./2666-allow-one-function-call.js)|Easy| 2667|[Create Hello World Function](./2667-create-hello-world-function.js)|Easy| From 3bef726bef95d187cc1e28ff95b32f00a9e76c74 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 14 Jan 2025 00:40:41 -0600 Subject: [PATCH 474/919] Add solution #621 --- 0621-task-scheduler.js | 37 +++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 38 insertions(+) create mode 100644 0621-task-scheduler.js diff --git a/0621-task-scheduler.js b/0621-task-scheduler.js new file mode 100644 index 00000000..d28cbd2b --- /dev/null +++ b/0621-task-scheduler.js @@ -0,0 +1,37 @@ +/** + * 621. Task Scheduler + * https://leetcode.com/problems/task-scheduler/ + * Difficulty: Medium + * + * You are given an array of CPU tasks, each labeled with a letter from A to Z, and a number n. + * Each CPU interval can be idle or allow the completion of one task. Tasks can be completed + * in any order, but there's a constraint: there has to be a gap of at least n intervals + * between two tasks with the same label. + * + * Return the minimum number of CPU intervals required to complete all tasks. + */ + +/** + * @param {character[]} tasks + * @param {number} n + * @return {number} + */ +var leastInterval = function(tasks, n) { + const map = new Map(); + let maxValue = 0; + let maxCount = 0; + + tasks.forEach(key => { + const value = map.has(key) ? map.get(key) + 1 : 1; + map.set(key, value); + + if (value > maxValue) { + maxValue = value; + maxCount = 1; + } else if (value === maxValue) { + maxCount++; + } + }); + + return Math.max(tasks.length, (maxValue - 1) * (n + 1) + maxCount); +}; diff --git a/README.md b/README.md index 562454c0..305e245a 100644 --- a/README.md +++ b/README.md @@ -223,6 +223,7 @@ 605|[Can Place Flowers](./0605-can-place-flowers.js)|Easy| 606|[Construct String from Binary Tree](./0606-construct-string-from-binary-tree.js)|Easy| 617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy| +621|[Task Scheduler](./0621-task-scheduler.js)|Medium| 628|[Maximum Product of Three Numbers](./0628-maximum-product-of-three-numbers.js)|Easy| 643|[Maximum Average Subarray I](./0643-maximum-average-subarray-i.js)|Easy| 645|[Set Mismatch](./0645-set-mismatch.js)|Medium| From 8c6712855e7b03fb69f6fb85b39c6ba06c3c8acf Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 15 Jan 2025 17:47:53 -0600 Subject: [PATCH 475/919] Add solution #496 --- 0496-next-greater-element-i.js | 33 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 0496-next-greater-element-i.js diff --git a/0496-next-greater-element-i.js b/0496-next-greater-element-i.js new file mode 100644 index 00000000..aad8d9e8 --- /dev/null +++ b/0496-next-greater-element-i.js @@ -0,0 +1,33 @@ +/** + * 496. Next Greater Element I + * https://leetcode.com/problems/next-greater-element-i/ + * Difficulty: Easy + * + * The next greater element of some element x in an array is the first greater element + * that is to the right of x in the same array. + * + * You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is + * a subset of nums2. + * + * For each 0 <= i < nums1.length, find the index j such that nums1[i] == nums2[j] and + * determine the next greater element of nums2[j] in nums2. If there is no next greater + * element, then the answer for this query is -1. + * + * Return an array ans of length nums1.length such that ans[i] is the next greater + * element as described above. + */ + +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number[]} + */ +var nextGreaterElement = function(nums1, nums2) { + return nums1.map(n => { + let index = nums2.indexOf(n); + while (nums2[index] <= n) { + index++; + } + return index >= nums2.length ? -1 : nums2[index]; + }); +}; diff --git a/README.md b/README.md index 305e245a..67285140 100644 --- a/README.md +++ b/README.md @@ -202,6 +202,7 @@ 485|[Max Consecutive Ones](./0485-max-consecutive-ones.js)|Easy| 491|[Non-decreasing Subsequences](./0491-non-decreasing-subsequences.js)|Medium| 492|[Construct the Rectangle](./0492-construct-the-rectangle.js)|Easy| +496|[Next Greater Element I](./0496-next-greater-element-i.js)|Easy| 500|[Keyboard Row](./0500-keyboard-row.js)|Easy| 501|[Find Mode in Binary Search Tree](./0501-find-mode-in-binary-search-tree.js)|Easy| 502|[IPO](./0502-ipo.js)|Hard| From 405f6ac0384260d9eeaef7b097ee342f37483e99 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 15 Jan 2025 17:48:32 -0600 Subject: [PATCH 476/919] Add solution #395 --- ...ng-with-at-least-k-repeating-characters.js | 24 +++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 0395-longest-substring-with-at-least-k-repeating-characters.js diff --git a/0395-longest-substring-with-at-least-k-repeating-characters.js b/0395-longest-substring-with-at-least-k-repeating-characters.js new file mode 100644 index 00000000..1df885e3 --- /dev/null +++ b/0395-longest-substring-with-at-least-k-repeating-characters.js @@ -0,0 +1,24 @@ +/** + * 395. Longest Substring with At Least K Repeating Characters + * https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/ + * Difficulty: Medium + * + * Given a string s and an integer k, return the length of the longest substring of s such + * that the frequency of each character in this substring is greater than or equal to k. + * + * If no such substring exists, return 0. + */ + +/** + * @param {string} s + * @param {number} k + * @return {number} + */ +var longestSubstring = function(s, k) { + for (const char of Array.from(new Set(s))) { + if (s.match(new RegExp(char, 'g')).length < k) { + return Math.max(...s.split(char).map(str => longestSubstring(str, k))); + } + } + return s.length; +}; diff --git a/README.md b/README.md index 67285140..a476ef2b 100644 --- a/README.md +++ b/README.md @@ -184,6 +184,7 @@ 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| 392|[Is Subsequence](./0392-is-subsequence.js)|Easy| 394|[Decode String](./0394-decode-string.js)|Medium| +395|[Longest Substring with At Least K Repeating Characters](./0395-longest-substring-with-at-least-k-repeating-characters.js)|Medium| 405|[Convert a Number to Hexadecimal](./0405-convert-a-number-to-hexadecimal.js)|Easy| 412|[Fizz Buzz](./0412-fizz-buzz.js)|Easy| 414|[Third Maximum Number](./0414-third-maximum-number.js)|Easy| From 4ea5752e7815182eca3561a5c948a666f79aeafc Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 15 Jan 2025 17:49:23 -0600 Subject: [PATCH 477/919] Add solution #389 --- 0389-find-the-difference.js | 24 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 0389-find-the-difference.js diff --git a/0389-find-the-difference.js b/0389-find-the-difference.js new file mode 100644 index 00000000..d789a16e --- /dev/null +++ b/0389-find-the-difference.js @@ -0,0 +1,24 @@ +/** + * 389. Find the Difference + * https://leetcode.com/problems/find-the-difference/ + * Difficulty: Easy + * + * You are given two strings s and t. + * + * String t is generated by random shuffling string s and then add one more letter at + * a random position. + * + * Return the letter that was added to t. + */ + +/** + * @param {string} s + * @param {string} t + * @return {character} + */ +var findTheDifference = function(s, t) { + const map = new Map(); + t.split('').forEach(c => map.set(c, (map.get(c) ?? 0) + 1)); + s.split('').forEach(c => map.set(c, map.get(c) - 1)); + return Array.from(map).find(([letter, count]) => count)[0]; +}; diff --git a/README.md b/README.md index a476ef2b..6e4e16b7 100644 --- a/README.md +++ b/README.md @@ -182,6 +182,7 @@ 374|[Guess Number Higher or Lower](./0374-guess-number-higher-or-lower.js)|Medium| 383|[Ransom Note](./0383-ransom-note.js)|Easy| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| +389|[Find the Difference](./0389-find-the-difference.js)|Easy| 392|[Is Subsequence](./0392-is-subsequence.js)|Easy| 394|[Decode String](./0394-decode-string.js)|Medium| 395|[Longest Substring with At Least K Repeating Characters](./0395-longest-substring-with-at-least-k-repeating-characters.js)|Medium| From 96a6a652b1032c80739f09f9c9efddc47c34f7c4 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 15 Jan 2025 17:50:36 -0600 Subject: [PATCH 478/919] Add solution #2429 --- 2429-minimize-xor.js | 37 +++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 38 insertions(+) create mode 100644 2429-minimize-xor.js diff --git a/2429-minimize-xor.js b/2429-minimize-xor.js new file mode 100644 index 00000000..568f19fc --- /dev/null +++ b/2429-minimize-xor.js @@ -0,0 +1,37 @@ +/** + * 2429. Minimize XOR + * https://leetcode.com/problems/minimize-xor/ + * Difficulty: Medium + * + * Given two positive integers num1 and num2, find the positive integer x such that: + * - x has the same number of set bits as num2, and + * - The value x XOR num1 is minimal. + * + * Note that XOR is the bitwise XOR operation. + * + * Return the integer x. The test cases are generated such that x is uniquely determined. + * + * The number of set bits of an integer is the number of 1's in its binary representation. + */ + +/** + * @param {number} num1 + * @param {number} num2 + * @return {number} + */ +var minimizeXor = function(num1, num2) { + let count1 = num1.toString(2).split('1').length - 1; + const count2 = num2.toString(2).split('1').length - 1; + + while (count1 > count2) { + num1 &= (num1 - 1); + count1--; + } + + while (count1 < count2) { + num1 |= (num1 + 1); + count1++; + } + + return num1; +}; diff --git a/README.md b/README.md index 6e4e16b7..1a5d05cb 100644 --- a/README.md +++ b/README.md @@ -412,6 +412,7 @@ 2396|[Strictly Palindromic Number](./2396-strictly-palindromic-number.js)|Medium| 2413|[Smallest Even Multiple](./2413-smallest-even-multiple.js)|Easy| 2427|[Number of Common Factors](./2427-number-of-common-factors.js)|Easy| +2429|[Minimize XOR](./2429-minimize-xor.js)|Medium| 2469|[Convert the Temperature](./2469-convert-the-temperature.js)|Easy| 2482|[Difference Between Ones and Zeros in Row and Column](./2482-difference-between-ones-and-zeros-in-row-and-column.js)|Medium| 2490|[Circular Sentence](./2490-circular-sentence.js)|Easy| From 171e82445be47e9db4bc4662e11298b577f0d78a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 15 Jan 2025 17:51:24 -0600 Subject: [PATCH 479/919] Add solution #575 --- 0575-distribute-candies.js | 23 +++++++++++++++++++++++ README.md | 1 + 2 files changed, 24 insertions(+) create mode 100644 0575-distribute-candies.js diff --git a/0575-distribute-candies.js b/0575-distribute-candies.js new file mode 100644 index 00000000..7d265797 --- /dev/null +++ b/0575-distribute-candies.js @@ -0,0 +1,23 @@ +/** + * 575. Distribute Candies + * https://leetcode.com/problems/distribute-candies/ + * Difficulty: Easy + * + * Alice has n candies, where the ith candy is of type candyType[i]. Alice noticed that + * she started to gain weight, so she visited a doctor. + * + * The doctor advised Alice to only eat n / 2 of the candies she has (n is always even). + * Alice likes her candies very much, and she wants to eat the maximum number of different + * types of candies while still following the doctor's advice. + * + * Given the integer array candyType of length n, return the maximum number of different + * types of candies she can eat if she only eats n / 2 of them. + */ + +/** + * @param {number[]} candyType + * @return {number} + */ +var distributeCandies = function(candyType) { + return Math.min(new Set(candyType).size, candyType.length / 2); +}; diff --git a/README.md b/README.md index 1a5d05cb..3896b83c 100644 --- a/README.md +++ b/README.md @@ -222,6 +222,7 @@ 565|[Array Nesting](./0565-array-nesting.js)|Medium| 566|[Reshape the Matrix](./0566-reshape-the-matrix.js)|Easy| 567|[Permutation in String](./0567-permutation-in-string.js)|Medium| +575|[Distribute Candies](./0575-distribute-candies.js)|Easy| 599|[Minimum Index Sum of Two Lists](./0599-minimum-index-sum-of-two-lists.js)|Easy| 605|[Can Place Flowers](./0605-can-place-flowers.js)|Easy| 606|[Construct String from Binary Tree](./0606-construct-string-from-binary-tree.js)|Easy| From e9c3a312f959846569611e381abfff21d7694d66 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 16 Jan 2025 17:43:56 -0600 Subject: [PATCH 480/919] Add solution #72 --- 0072-edit-distance.js | 38 ++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 39 insertions(+) create mode 100644 0072-edit-distance.js diff --git a/0072-edit-distance.js b/0072-edit-distance.js new file mode 100644 index 00000000..c3e7a227 --- /dev/null +++ b/0072-edit-distance.js @@ -0,0 +1,38 @@ +/** + * 72. Edit Distance + * https://leetcode.com/problems/edit-distance/ + * Difficulty: Medium + * + * Given two strings word1 and word2, return the minimum number of operations required to + * convert word1 to word2. + * + * You have the following three operations permitted on a word: + * - Insert a character + * - Delete a character + * - Replace a character + */ + +/** + * @param {string} word1 + * @param {string} word2 + * @return {number} + */ +var minDistance = function(word1, word2) { + const cache = new Array(word1.length + 1).fill(0).map(() => new Array(word2.length + 1)); + + for (let i = 0; i <= word1.length; i++) { + for (let j = 0; j <= word2.length; j++) { + if (i === 0) { + cache[0][j] = j; + } else if (j === 0) { + cache[i][0] = i; + } else if (word1[i - 1] == word2[j - 1]) { + cache[i][j] = cache[i - 1][j - 1]; + } else { + cache[i][j] = Math.min(cache[i][j - 1], cache[i - 1][j - 1], cache[i - 1][j]) + 1; + } + } + } + + return cache[word1.length][word2.length]; +}; diff --git a/README.md b/README.md index 3896b83c..c1e264e9 100644 --- a/README.md +++ b/README.md @@ -75,6 +75,7 @@ 69|[Sqrt(x)](./0069-sqrtx.js)|Medium| 70|[Climbing Stairs](./0070-climbing-stairs.js)|Easy| 71|[Simplify Path](./0071-simplify-path.js)|Medium| +72|[Edit Distance](./0072-edit-distance.js)|Medium| 73|[Set Matrix Zeroes](./0073-set-matrix-zeroes.js)|Medium| 74|[Search a 2D Matrix](./0074-search-a-2d-matrix.js)|Medium| 75|[Sort Colors](./0075-sort-colors.js)|Medium| From a45ddfd2acc97e4a3638745eec8d4ac9b9554a23 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 16 Jan 2025 17:45:17 -0600 Subject: [PATCH 481/919] Add solution #68 --- 0068-text-justification.js | 63 ++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 64 insertions(+) create mode 100644 0068-text-justification.js diff --git a/0068-text-justification.js b/0068-text-justification.js new file mode 100644 index 00000000..eb74a4ce --- /dev/null +++ b/0068-text-justification.js @@ -0,0 +1,63 @@ +/** + * 68. Text Justification + * https://leetcode.com/problems/text-justification/ + * Difficulty: Hard + * + * Given an array of strings words and a width maxWidth, format the text such that each + * line has exactly maxWidth characters and is fully (left and right) justified. + * + * You should pack your words in a greedy approach; that is, pack as many words as you + * can in each line. Pad extra spaces ' ' when necessary so that each line has exactly + * maxWidth characters. + * + * Extra spaces between words should be distributed as evenly as possible. If the number + * of spaces on a line does not divide evenly between words, the empty slots on the left + * will be assigned more spaces than the slots on the right. + * + * For the last line of text, it should be left-justified, and no extra space is inserted + * between words. + * + * Note: + * - A word is defined as a character sequence consisting of non-space characters only. + * - Each word's length is guaranteed to be greater than 0 and not exceed maxWidth. + * - The input array words contains at least one word. + */ + +/** + * @param {string[]} words + * @param {number} maxWidth + * @return {string[]} + */ +var fullJustify = function(words, maxWidth) { + const result = [[]]; + result[0].count = 0; + + for (const word of words) { + let row = result[result.length - 1]; + if (row.length && row.count + row.length + word.length > maxWidth) { + result.push([]); + row = result[result.length - 1]; + row.count = 0; + } + row.push(word); + row.count += word.length; + } + + for (let i = 0; i < result.length; i++) { + const row = result[i]; + if (row.length === 1 || i === result.length - 1) { + result[i] = row.join(' ') + ' '.repeat(maxWidth - row.count - row.length + 1); + continue; + } + + const min = ' '.repeat(Math.floor((maxWidth - row.count) / (row.length - 1))); + for (let j = 1; j < row.length; j++) { + const delimiter = j <= (maxWidth - row.count) % (row.length - 1) ? ' ' : ''; + row[0] += min + delimiter + row[j]; + } + + result[i] = row[0]; + } + + return result; +}; diff --git a/README.md b/README.md index c1e264e9..c6b7f5c2 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,7 @@ 65|[Valid Number](./0065-valid-number.js)|Hard| 66|[Plus One](./0066-plus-one.js)|Easy| 67|[Add Binary](./0067-add-binary.js)|Easy| +68|[Text Justification](./0068-text-justification.js)|Hard| 69|[Sqrt(x)](./0069-sqrtx.js)|Medium| 70|[Climbing Stairs](./0070-climbing-stairs.js)|Easy| 71|[Simplify Path](./0071-simplify-path.js)|Medium| From 4eb54a3be90c9f4ea3d84c6a2367743e80f8bd65 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 16 Jan 2025 17:46:41 -0600 Subject: [PATCH 482/919] Add solution #63 --- 0063-unique-paths-ii.js | 37 +++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 38 insertions(+) create mode 100644 0063-unique-paths-ii.js diff --git a/0063-unique-paths-ii.js b/0063-unique-paths-ii.js new file mode 100644 index 00000000..a63c96da --- /dev/null +++ b/0063-unique-paths-ii.js @@ -0,0 +1,37 @@ +/** + * 63. Unique Paths II + * https://leetcode.com/problems/unique-paths-ii/ + * Difficulty: Medium + * + * You are given an m x n integer array grid. There is a robot initially located at + * the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right + * corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at + * any point in time. + * + * An obstacle and space are marked as 1 or 0 respectively in grid. A path that the + * robot takes cannot include any square that is an obstacle. + * + * Return the number of possible unique paths that the robot can take to reach the + * bottom-right corner. + * + * The testcases are generated so that the answer will be less than or equal to 2 * 109. + */ + +/** + * @param {number[][]} grid + * @return {number} + */ +var uniquePathsWithObstacles = function(grid) { + const cache = new Array(grid.length).fill(0).map(v => new Array(grid[0].length).fill(0)); + + function traverse(x, y) { + if (grid[x] === undefined || grid[x][y] === undefined || grid[x][y] === 1) return 0; + if (x === grid.length - 1 && y === grid[0].length - 1) return 1; + if (!cache[x][y]) { + cache[x][y] = traverse(x + 1, y) + traverse(x, y + 1); + } + return cache[x][y]; + } + + return traverse(0, 0); +}; diff --git a/README.md b/README.md index c6b7f5c2..4b31f76f 100644 --- a/README.md +++ b/README.md @@ -68,6 +68,7 @@ 60|[Permutation Sequence](./0060-permutation-sequence.js)|Hard| 61|[Rotate List](./0061-rotate-list.js)|Medium| 62|[Unique Paths](./0062-unique-paths.js)|Medium| +63|[Unique Paths II](./0063-unique-paths-ii.js)|Medium| 64|[Minimum Path Sum](./0064-minimum-path-sum.js)|Medium| 65|[Valid Number](./0065-valid-number.js)|Hard| 66|[Plus One](./0066-plus-one.js)|Easy| From fb7121167c394e854b732750fad284d12b251fca Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 16 Jan 2025 17:47:35 -0600 Subject: [PATCH 483/919] Add solution #482 --- 0482-license-key-formatting.js | 33 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 0482-license-key-formatting.js diff --git a/0482-license-key-formatting.js b/0482-license-key-formatting.js new file mode 100644 index 00000000..1f4a87e7 --- /dev/null +++ b/0482-license-key-formatting.js @@ -0,0 +1,33 @@ +/** + * 482. License Key Formatting + * https://leetcode.com/problems/license-key-formatting/ + * Difficulty: Easy + * + * You are given a license key represented as a string s that consists of only alphanumeric + * characters and dashes. The string is separated into n + 1 groups by n dashes. You are + * also given an integer k. + * + * We want to reformat the string s such that each group contains exactly k characters, + * except for the first group, which could be shorter than k but still must contain at + * least one character. Furthermore, there must be a dash inserted between two groups, + * and you should convert all lowercase letters to uppercase. + * + * Return the reformatted license key. + */ + +/** + * @param {string} s + * @param {number} k + * @return {string} + */ +var licenseKeyFormatting = function(s, k) { + const result = []; + s = s.toUpperCase().replace(/\-+/g, ''); + if (s.length % k) { + result.push(s.substring(0, s.length % k)); + } + for (let i = s.length % k; i < s.length; i += k) { + result.push(s.substring(i, i + k)); + } + return result.join('-'); +}; diff --git a/README.md b/README.md index 4b31f76f..71bdbe3a 100644 --- a/README.md +++ b/README.md @@ -204,6 +204,7 @@ 461|[Hamming Distance](./0461-hamming-distance.js)|Easy| 463|[Island Perimeter](./0463-island-perimeter.js)|Medium| 476|[Number Complement](./0476-number-complement.js)|Easy| +482|[License Key Formatting](./0482-license-key-formatting.js)|Easy| 485|[Max Consecutive Ones](./0485-max-consecutive-ones.js)|Easy| 491|[Non-decreasing Subsequences](./0491-non-decreasing-subsequences.js)|Medium| 492|[Construct the Rectangle](./0492-construct-the-rectangle.js)|Easy| From 2150b582540f341dc2f5a487e8d0ae7ce7493be4 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 16 Jan 2025 17:48:12 -0600 Subject: [PATCH 484/919] Add solution #2425 --- 2425-bitwise-xor-of-all-pairings.js | 22 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 2425-bitwise-xor-of-all-pairings.js diff --git a/2425-bitwise-xor-of-all-pairings.js b/2425-bitwise-xor-of-all-pairings.js new file mode 100644 index 00000000..2ef59ed9 --- /dev/null +++ b/2425-bitwise-xor-of-all-pairings.js @@ -0,0 +1,22 @@ +/** + * 2425. Bitwise XOR of All Pairings + * https://leetcode.com/problems/bitwise-xor-of-all-pairings/ + * Difficulty: Medium + * + * You are given two 0-indexed arrays, nums1 and nums2, consisting of non-negative integers. + * There exists another array, nums3, which contains the bitwise XOR of all pairings of + * integers between nums1 and nums2 (every integer in nums1 is paired with every integer + * in nums2 exactly once). + * + * Return the bitwise XOR of all integers in nums3. + */ + +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number} + */ +var xorAllNums = function(nums1, nums2) { + const xor = (a, b) => a.length % 2 ? b.reduce((x, y) => x ^ y): 0; + return xor(nums1, nums2) ^ xor(nums2, nums1); +}; diff --git a/README.md b/README.md index 71bdbe3a..73f9a2f0 100644 --- a/README.md +++ b/README.md @@ -416,6 +416,7 @@ 2390|[Removing Stars From a String](./2390-removing-stars-from-a-string.js)|Medium| 2396|[Strictly Palindromic Number](./2396-strictly-palindromic-number.js)|Medium| 2413|[Smallest Even Multiple](./2413-smallest-even-multiple.js)|Easy| +2425|[Bitwise XOR of All Pairings](./2425-bitwise-xor-of-all-pairings.js)|Medium| 2427|[Number of Common Factors](./2427-number-of-common-factors.js)|Easy| 2429|[Minimize XOR](./2429-minimize-xor.js)|Medium| 2469|[Convert the Temperature](./2469-convert-the-temperature.js)|Easy| From b1d14ff7eef292fe89006143c33570b38282cf3b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 16 Jan 2025 20:20:12 -0600 Subject: [PATCH 485/919] Add solution #2683 --- 2683-neighboring-bitwise-xor.js | 26 ++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 27 insertions(+) create mode 100644 2683-neighboring-bitwise-xor.js diff --git a/2683-neighboring-bitwise-xor.js b/2683-neighboring-bitwise-xor.js new file mode 100644 index 00000000..523905d5 --- /dev/null +++ b/2683-neighboring-bitwise-xor.js @@ -0,0 +1,26 @@ +/** + * 2683. Neighboring Bitwise XOR + * https://leetcode.com/problems/neighboring-bitwise-xor/ + * Difficulty: Medium + * + * A 0-indexed array derived with length n is derived by computing the bitwise XOR (⊕) + * of adjacent values in a binary array original of length n. + * + * Specifically, for each index i in the range [0, n - 1]: + * - If i = n - 1, then derived[i] = original[i] ⊕ original[0]. + * - Otherwise, derived[i] = original[i] ⊕ original[i + 1]. + * + * Given an array derived, your task is to determine whether there exists a valid binary + * array original that could have formed derived. + * + * Return true if such an array exists or false otherwise. + * - A binary array is an array containing only 0's and 1's + */ + +/** + * @param {number[]} derived + * @return {boolean} + */ +var doesValidArrayExist = function(derived) { + return derived.reduce((xor, n) => xor ^ n, 0) === 0; +}; diff --git a/README.md b/README.md index 73f9a2f0..46fe2f4a 100644 --- a/README.md +++ b/README.md @@ -447,6 +447,7 @@ 2666|[Allow One Function Call](./2666-allow-one-function-call.js)|Easy| 2667|[Create Hello World Function](./2667-create-hello-world-function.js)|Easy| 2677|[Chunk Array](./2677-chunk-array.js)|Easy| +2683|[Neighboring Bitwise XOR](./2683-neighboring-bitwise-xor.js)|Medium| 2693|[Call Function with Custom Context](./2693-call-function-with-custom-context.js)|Medium| 2695|[Array Wrapper](./2695-array-wrapper.js)|Easy| 2703|[Return Length of Arguments Passed](./2703-return-length-of-arguments-passed.js)|Easy| From d702db4762d6925bd4f5ef1dcb927b916dc2117b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 17 Jan 2025 17:09:07 -0600 Subject: [PATCH 486/919] Add solution #146 --- 0146-lru-cache.js | 54 +++++++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 55 insertions(+) create mode 100644 0146-lru-cache.js diff --git a/0146-lru-cache.js b/0146-lru-cache.js new file mode 100644 index 00000000..8598c063 --- /dev/null +++ b/0146-lru-cache.js @@ -0,0 +1,54 @@ +/** + * 146. LRU Cache + * https://leetcode.com/problems/lru-cache/ + * Difficulty: Medium + * + * Design a data structure that follows the constraints of a Least Recently Used (LRU) cache. + * + * Implement the LRUCache class: + * - LRUCache(int capacity) Initialize the LRU cache with positive size capacity. + * - int get(int key) Return the value of the key if the key exists, otherwise return -1. + * - void put(int key, int value) Update the value of the key if the key exists. Otherwise, + * add the key-value pair to the cache. If the number of keys exceeds the capacity from + * this operation, evict the least recently used key. + * + * The functions get and put must each run in O(1) average time complexity. + */ + +/** + * @param {number} capacity + */ +var LRUCache = function(capacity) { + this.cache = new Map(); + this.capacity = capacity; +}; + +/** + * @param {number} key + * @return {number} + */ +LRUCache.prototype.get = function(key) { + if (!this.cache.has(key)) { + return -1; + } + + const value = this.cache.get(key); + this.cache.delete(key); + this.cache.set(key, value); + return this.cache.get(key); +}; + +/** + * @param {number} key + * @param {number} value + * @return {void} + */ +LRUCache.prototype.put = function(key, value) { + if (this.cache.has(key)) { + this.cache.delete(key); + } + this.cache.set(key, value); + if (this.cache.size > this.capacity) { + this.cache.delete(this.cache.keys().next().value); + } +}; diff --git a/README.md b/README.md index 46fe2f4a..363edda6 100644 --- a/README.md +++ b/README.md @@ -126,6 +126,7 @@ 143|[Reorder List](./0143-reorder-list.js)|Medium| 144|[Binary Tree Preorder Traversal](./0144-binary-tree-preorder-traversal.js)|Easy| 145|[Binary Tree Postorder Traversal](./0145-binary-tree-postorder-traversal.js)|Easy| +146|[LRU Cache](./0146-lru-cache.js)|Medium| 148|[Sort List](./0148-sort-list.js)|Medium| 149|[Max Points on a Line](./0149-max-points-on-a-line.js)|Hard| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| From bfeb310856b4ba6340ecd1b6853fd28918f34db8 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 17 Jan 2025 17:09:41 -0600 Subject: [PATCH 487/919] Add solution #110 --- 0110-balanced-binary-tree.js | 30 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 0110-balanced-binary-tree.js diff --git a/0110-balanced-binary-tree.js b/0110-balanced-binary-tree.js new file mode 100644 index 00000000..2f4e7213 --- /dev/null +++ b/0110-balanced-binary-tree.js @@ -0,0 +1,30 @@ +/** + * 110. Balanced Binary Tree + * https://leetcode.com/problems/balanced-binary-tree/ + * Difficulty: Easy + * + * Given a binary tree, determine if it is height-balanced. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {boolean} + */ +var isBalanced = function(root) { + if (!root) return true; + return isBalanced(root.right) && isBalanced(root.left) + && Math.abs(traverse(root.right) - traverse(root.left)) < 2; +}; + +function traverse(node, depth = 0) { + if (!node) return depth; + return Math.max(traverse(node.right, depth + 1), traverse(node.left, depth + 1)); +} diff --git a/README.md b/README.md index 363edda6..e37cd46a 100644 --- a/README.md +++ b/README.md @@ -103,6 +103,7 @@ 101|[Symmetric Tree](./0101-symmetric-tree.js)|Easy| 102|[Binary Tree Level Order Traversal](./0102-binary-tree-level-order-traversal.js)|Medium| 104|[Maximum Depth of Binary Tree](./0104-maximum-depth-of-binary-tree.js)|Easy| +110|[Balanced Binary Tree](./0110-balanced-binary-tree.js)|Easy| 111|[Minimum Depth of Binary Tree](./0111-minimum-depth-of-binary-tree.js)|Easy| 112|[Path Sum](./0112-path-sum.js)|Easy| 116|[Populating Next Right Pointers in Each Node](./0116-populating-next-right-pointers-in-each-node.js)|Medium| From 7b8b614b58745ff4863866cea135789be6446020 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 17 Jan 2025 17:10:29 -0600 Subject: [PATCH 488/919] Add solution #113 --- 0113-path-sum-ii.js | 43 +++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 44 insertions(+) create mode 100644 0113-path-sum-ii.js diff --git a/0113-path-sum-ii.js b/0113-path-sum-ii.js new file mode 100644 index 00000000..6d49afa4 --- /dev/null +++ b/0113-path-sum-ii.js @@ -0,0 +1,43 @@ +/** + * 113. Path Sum II + * https://leetcode.com/problems/path-sum-ii/ + * Difficulty: Medium + * + * Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where + * the sum of the node values in the path equals targetSum. Each path should be returned as a + * list of the node values, not node references. + * + * A root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a + * node with no children. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @param {number} targetSum + * @return {number[][]} + */ +var pathSum = function(root, targetSum) { + if (!root) return []; + return traverse([], targetSum, root); +}; + +function traverse(result, targetSum, node, history = []) { + const values = [...history, node.val]; + + if (!node.left && !node.right && values.reduce((sum, n) => sum + n, 0) === targetSum) { + result.push(values); + } + + if (node.left) traverse(result, targetSum, node.left, values); + if (node.right) traverse(result, targetSum, node.right, values); + + return result; +} diff --git a/README.md b/README.md index e37cd46a..3e0eda11 100644 --- a/README.md +++ b/README.md @@ -106,6 +106,7 @@ 110|[Balanced Binary Tree](./0110-balanced-binary-tree.js)|Easy| 111|[Minimum Depth of Binary Tree](./0111-minimum-depth-of-binary-tree.js)|Easy| 112|[Path Sum](./0112-path-sum.js)|Easy| +113|[Path Sum II](./0113-path-sum-ii.js)|Medium| 116|[Populating Next Right Pointers in Each Node](./0116-populating-next-right-pointers-in-each-node.js)|Medium| 118|[Pascal's Triangle](./0118-pascals-triangle.js)|Easy| 119|[Pascal's Triangle II](./0119-pascals-triangle-ii.js)|Easy| From fced6b31f764086cc4bba2ab7f1b2f657a26078b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 17 Jan 2025 17:11:24 -0600 Subject: [PATCH 489/919] Add solution #216 --- 0216-combination-sum-iii.js | 37 +++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 38 insertions(+) create mode 100644 0216-combination-sum-iii.js diff --git a/0216-combination-sum-iii.js b/0216-combination-sum-iii.js new file mode 100644 index 00000000..04479bca --- /dev/null +++ b/0216-combination-sum-iii.js @@ -0,0 +1,37 @@ +/** + * 216. Combination Sum III + * https://leetcode.com/problems/combination-sum-iii/ + * Difficulty: Medium + * + * Find all valid combinations of k numbers that sum up to n such that the following + * conditions are true: + * - Only numbers 1 through 9 are used. + * - Each number is used at most once. + * + * Return a list of all possible valid combinations. The list must not contain the same + * combination twice, and the combinations may be returned in any order. + */ + +/** + * @param {number} k + * @param {number} n + * @return {number[][]} + */ +var combinationSum3 = function(k, n) { + const result = []; + + function backtrack(history, sum, start) { + if (sum > n) return; + if (history.length === k && sum === n) { + result.push(history); + return; + } + for (let i = start; i < 10; i++) { + backtrack([...history, i], sum + i, i + 1); + } + } + + backtrack([], 0, 1); + + return result; +}; diff --git a/README.md b/README.md index 3e0eda11..fa130097 100644 --- a/README.md +++ b/README.md @@ -151,6 +151,7 @@ 213|[House Robber II](./0213-house-robber-ii.js)|Medium| 214|[Shortest Palindrome](./0214-shortest-palindrome.js)|Hard| 215|[Kth Largest Element in an Array](./0215-kth-largest-element-in-an-array.js)|Medium| +216|[Combination Sum III](./0216-combination-sum-iii.js)|Medium| 217|[Contains Duplicate](./0217-contains-duplicate.js)|Easy| 219|[Contains Duplicate II](./0219-contains-duplicate-ii.js)|Easy| 225|[Implement Stack using Queues](./0225-implement-stack-using-queues.js)|Easy| From c8dcf56c77cf0eb8784724fdf2e29e258f74a38d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 18 Jan 2025 00:01:08 -0600 Subject: [PATCH 490/919] Add solution #1023 --- 1023-camelcase-matching.js | 21 +++++++++++++++++++++ README.md | 1 + 2 files changed, 22 insertions(+) create mode 100644 1023-camelcase-matching.js diff --git a/1023-camelcase-matching.js b/1023-camelcase-matching.js new file mode 100644 index 00000000..01410d1a --- /dev/null +++ b/1023-camelcase-matching.js @@ -0,0 +1,21 @@ +/** + * 1023. Camelcase Matching + * https://leetcode.com/problems/camelcase-matching/ + * Difficulty: Medium + * + * Given an array of strings queries and a string pattern, return a boolean array answer + * where answer[i] is true if queries[i] matches pattern, and false otherwise. + * + * A query word queries[i] matches pattern if you can insert lowercase English letters + * pattern so that it equals the query. You may insert each character at any position + * and you may not insert any characters. + */ + +/** + * @param {string[]} queries + * @param {string} pattern + * @return {boolean[]} + */ +var camelMatch = function(queries, pattern) { + return queries.map(s => s.match(pattern.split(/(.)/).join('[a-z]*'))?.at(0) === s); +}; diff --git a/README.md b/README.md index fa130097..33e9228d 100644 --- a/README.md +++ b/README.md @@ -299,6 +299,7 @@ 1009|[Complement of Base 10 Integer](./1009-complement-of-base-10-integer.js)|Easy| 1010|[Pairs of Songs With Total Durations Divisible by 60](./1010-pairs-of-songs-with-total-durations-divisible-by-60.js)|Medium| 1022|[Sum of Root To Leaf Binary Numbers](./1022-sum-of-root-to-leaf-binary-numbers.js)|Easy| +1023|[Camelcase Matching](./1023-camelcase-matching.js)|Medium| 1037|[Valid Boomerang](./1037-valid-boomerang.js)|Easy| 1041|[Robot Bounded In Circle](./1041-robot-bounded-in-circle.js)|Medium| 1047|[Remove All Adjacent Duplicates In String](./1047-remove-all-adjacent-duplicates-in-string.js)|Easy| From 12c5da5a9f40ae22bcd7072f32abeea4551f9184 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 18 Jan 2025 00:02:02 -0600 Subject: [PATCH 491/919] Add solution #220 --- 0220-contains-duplicate-iii.js | 45 ++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 46 insertions(+) create mode 100644 0220-contains-duplicate-iii.js diff --git a/0220-contains-duplicate-iii.js b/0220-contains-duplicate-iii.js new file mode 100644 index 00000000..4cbe2814 --- /dev/null +++ b/0220-contains-duplicate-iii.js @@ -0,0 +1,45 @@ +/** + * 220. Contains Duplicate III + * https://leetcode.com/problems/contains-duplicate-iii/ + * Difficulty: Hard + * + * You are given an integer array nums and two integers indexDiff and valueDiff. + * + * Find a pair of indices (i, j) such that: + * - i != j, + * - abs(i - j) <= indexDiff. + * - abs(nums[i] - nums[j]) <= valueDiff, and + * + * Return true if such pair exists or false otherwise. + */ + +/** + * @param {number[]} nums + * @param {number} indexDiff + * @param {number} valueDiff + * @return {boolean} + */ +var containsNearbyAlmostDuplicate = function(nums, indexDiff, valueDiff) { + if (valueDiff < 0) return false; + + const map = new Map(); + + for (let i = 0; i < nums.length; i++) { + const limit = valueDiff + 1; + const item = Math.floor(nums[i] / limit); + + if (map.has(item) + || map.has(item - 1) && Math.abs(nums[i] - map.get(item - 1)) < limit + || map.has(item + 1) && Math.abs(nums[i] - map.get(item + 1)) < limit) { + return true; + } + + map.set(item, nums[i]); + + if (i >= indexDiff) { + map.delete(Math.floor(nums[i - indexDiff] / limit)); + } + } + + return false; +}; diff --git a/README.md b/README.md index 33e9228d..168bac20 100644 --- a/README.md +++ b/README.md @@ -154,6 +154,7 @@ 216|[Combination Sum III](./0216-combination-sum-iii.js)|Medium| 217|[Contains Duplicate](./0217-contains-duplicate.js)|Easy| 219|[Contains Duplicate II](./0219-contains-duplicate-ii.js)|Easy| +220|[Contains Duplicate III](./0220-contains-duplicate-iii.js)|Hard| 225|[Implement Stack using Queues](./0225-implement-stack-using-queues.js)|Easy| 226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy| 229|[Majority Element II](./0229-majority-element-ii.js)|Medium| From f253755dbaa569e9d707bbb600bb52ea6b668d0d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 18 Jan 2025 00:03:26 -0600 Subject: [PATCH 492/919] Add solution #295 --- 0295-find-median-from-data-stream.js | 44 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 45 insertions(+) create mode 100644 0295-find-median-from-data-stream.js diff --git a/0295-find-median-from-data-stream.js b/0295-find-median-from-data-stream.js new file mode 100644 index 00000000..cb6ed03e --- /dev/null +++ b/0295-find-median-from-data-stream.js @@ -0,0 +1,44 @@ +/** + * 295. Find Median from Data Stream + * https://leetcode.com/problems/find-median-from-data-stream/ + * Difficulty: Hard + * + * The median is the middle value in an ordered integer list. If the size of the list is + * even, there is no middle value, and the median is the mean of the two middle values. + * + * - For example, for arr = [2,3,4], the median is 3. + * - For example, for arr = [2,3], the median is (2 + 3) / 2 = 2.5. + * + * Implement the MedianFinder class: + * - MedianFinder() initializes the MedianFinder object. + * - void addNum(int num) adds the integer num from the data stream to the data structure. + * - double findMedian() returns the median of all elements so far. Answers within 10-5 of + * the actual answer will be accepted. + */ + + +var MedianFinder = function() { + this.minHeap = new MinPriorityQueue(); + this.maxHeap = new MaxPriorityQueue(); +}; + +/** + * @param {number} num + * @return {void} + */ +MedianFinder.prototype.addNum = function(num) { + this.minHeap.enqueue(num); + this.maxHeap.enqueue(this.minHeap.dequeue().element); + if (this.minHeap.size() < this.maxHeap.size()) { + this.minHeap.enqueue(this.maxHeap.dequeue().element); + } +}; + +/** + * @return {number} + */ +MedianFinder.prototype.findMedian = function() { + return this.minHeap.size() > this.maxHeap.size() + ? this.minHeap.front().element + : (this.minHeap.front().element + this.maxHeap.front().element) / 2; +}; diff --git a/README.md b/README.md index 168bac20..b08745ca 100644 --- a/README.md +++ b/README.md @@ -173,6 +173,7 @@ 278|[First Bad Version](./0278-first-bad-version.js)|Medium| 283|[Move Zeroes](./0283-move-zeroes.js)|Easy| 290|[Word Pattern](./0290-word-pattern.js)|Easy| +295|[Find Median from Data Stream](./0295-find-median-from-data-stream.js)|Hard| 316|[Remove Duplicate Letters](./0316-remove-duplicate-letters.js)|Medium| 326|[Power of Three](./0326-power-of-three.js)|Easy| 328|[Odd Even Linked List](./0328-odd-even-linked-list.js)|Medium| From e828ad2061a1970ff33bf3732cf90dd1dadefe9d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 18 Jan 2025 00:04:14 -0600 Subject: [PATCH 493/919] Add solution #164 --- 0164-maximum-gap.js | 21 +++++++++++++++++++++ README.md | 1 + 2 files changed, 22 insertions(+) create mode 100644 0164-maximum-gap.js diff --git a/0164-maximum-gap.js b/0164-maximum-gap.js new file mode 100644 index 00000000..3a502943 --- /dev/null +++ b/0164-maximum-gap.js @@ -0,0 +1,21 @@ +/** + * 164. Maximum Gap + * https://leetcode.com/problems/maximum-gap/ + * Difficulty: Medium + * + * Given an integer array nums, return the maximum difference between two successive elements in + * its sorted form. If the array contains less than two elements, return 0. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var maximumGap = function(nums) { + nums.sort((a, b) => a - b); + let result = 0; + for (let i = 1; i < nums.length; i++) { + result = Math.max(result, nums[i] - nums[i - 1]); + } + return result; +}; diff --git a/README.md b/README.md index b08745ca..0c9cc111 100644 --- a/README.md +++ b/README.md @@ -134,6 +134,7 @@ 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| 160|[Intersection of Two Linked Lists](./0160-intersection-of-two-linked-lists.js)|Medium| +164|[Maximum Gap](./0164-maximum-gap.js)|Medium| 167|[Two Sum II - Input Array Is Sorted](./0167-two-sum-ii-input-array-is-sorted.js)|Easy| 168|[Excel Sheet Column Title](./0168-excel-sheet-column-title.js)|Easy| 169|[Majority Element](./0169-majority-element.js)|Easy| From afbbbc9b5561039e077c78a6a867d33469b1aaa9 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 18 Jan 2025 00:04:55 -0600 Subject: [PATCH 494/919] Add solution #594 --- 0594-longest-harmonious-subsequence.js | 24 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 0594-longest-harmonious-subsequence.js diff --git a/0594-longest-harmonious-subsequence.js b/0594-longest-harmonious-subsequence.js new file mode 100644 index 00000000..1a3ee5a5 --- /dev/null +++ b/0594-longest-harmonious-subsequence.js @@ -0,0 +1,24 @@ +/** + * 594. Longest Harmonious Subsequence + * https://leetcode.com/problems/longest-harmonious-subsequence/ + * Difficulty: Easy + * + * We define a harmonious array as an array where the difference between its maximum + * value and its minimum value is exactly 1. + * + * Given an integer array nums, return the length of its longest harmonious subsequence + * among all its possible subsequences. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var findLHS = function(nums) { + const map = new Map(); + nums.forEach(n => map.set(n, (map.get(n) ?? 0) + 1)); + + return Array.from(map).reduce((result, [n, count]) => { + return map.has(n + 1) ? Math.max(result, count + map.get(n + 1)) : result; + }, 0); +}; diff --git a/README.md b/README.md index 0c9cc111..e453b4e7 100644 --- a/README.md +++ b/README.md @@ -234,6 +234,7 @@ 566|[Reshape the Matrix](./0566-reshape-the-matrix.js)|Easy| 567|[Permutation in String](./0567-permutation-in-string.js)|Medium| 575|[Distribute Candies](./0575-distribute-candies.js)|Easy| +594|[Longest Harmonious Subsequence](./0594-longest-harmonious-subsequence.js)|Easy| 599|[Minimum Index Sum of Two Lists](./0599-minimum-index-sum-of-two-lists.js)|Easy| 605|[Can Place Flowers](./0605-can-place-flowers.js)|Easy| 606|[Construct String from Binary Tree](./0606-construct-string-from-binary-tree.js)|Easy| From 3cc4f69ea01fa77f381b5f2767dd081f2694f3b3 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 19 Jan 2025 08:42:50 -0600 Subject: [PATCH 495/919] Add solution #407 --- 0407-trapping-rain-water-ii.js | 45 ++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 46 insertions(+) create mode 100644 0407-trapping-rain-water-ii.js diff --git a/0407-trapping-rain-water-ii.js b/0407-trapping-rain-water-ii.js new file mode 100644 index 00000000..67fe17eb --- /dev/null +++ b/0407-trapping-rain-water-ii.js @@ -0,0 +1,45 @@ +/** + * 407. Trapping Rain Water II + * https://leetcode.com/problems/trapping-rain-water-ii/ + * Difficulty: Hard + * + * Given an m x n integer matrix heightMap representing the height of each unit cell in a 2D + * elevation map, return the volume of water it can trap after raining. + */ + +/** + * @param {number[][]} heightMap + * @return {number} + */ +var trapRainWater = function(heightMap) { + const minHeap = new MinPriorityQueue({ priority: ([value]) => value }); + const history = new Array(heightMap.length).fill(0) + .map(() => new Array(heightMap[0].length).fill(false)); + + for (let i = 0; i < heightMap.length; i++) { + for (let j = 0; j < heightMap[0].length; j++) { + if (i === 0 || i === heightMap.length - 1 || j === 0 || j === heightMap[0].length - 1) { + minHeap.enqueue([heightMap[i][j], i, j]); + history[i][j] = true; + } + } + } + + let result = 0; + while (minHeap.size()) { + const [weight, i, j] = minHeap.dequeue().element; + [[0, 1], [1, 0], [0, -1], [-1, 0]].forEach(([x, y]) => { + const [rowIndex, columnIndex] = [i + x, j + y]; + if (rowIndex >= 0 && rowIndex < heightMap.length && columnIndex >= 0 + && columnIndex < heightMap[0].length && !history[rowIndex][columnIndex]) { + result += Math.max(0, weight - heightMap[rowIndex][columnIndex]); + minHeap.enqueue([ + Math.max(weight, heightMap[rowIndex][columnIndex]), rowIndex, columnIndex + ]); + history[rowIndex][columnIndex] = true; + } + }); + } + + return result; +}; diff --git a/README.md b/README.md index e453b4e7..b7a432bd 100644 --- a/README.md +++ b/README.md @@ -197,6 +197,7 @@ 394|[Decode String](./0394-decode-string.js)|Medium| 395|[Longest Substring with At Least K Repeating Characters](./0395-longest-substring-with-at-least-k-repeating-characters.js)|Medium| 405|[Convert a Number to Hexadecimal](./0405-convert-a-number-to-hexadecimal.js)|Easy| +407|[Trapping Rain Water II](./0407-trapping-rain-water-ii.js)|Hard| 412|[Fizz Buzz](./0412-fizz-buzz.js)|Easy| 414|[Third Maximum Number](./0414-third-maximum-number.js)|Easy| 415|[Add Strings](./0415-add-strings.js)|Easy| From ade40647388d0d10e5cebd8eed9c96d2f5a0b73f Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 19 Jan 2025 08:43:34 -0600 Subject: [PATCH 496/919] Add solution #456 --- 0456-132-pattern.js | 30 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 0456-132-pattern.js diff --git a/0456-132-pattern.js b/0456-132-pattern.js new file mode 100644 index 00000000..7e2ade42 --- /dev/null +++ b/0456-132-pattern.js @@ -0,0 +1,30 @@ +/** + * 456. 132 Pattern + * https://leetcode.com/problems/132-pattern/ + * Difficulty: Medium + * + * Given an array of n integers nums, a 132 pattern is a subsequence of three integers nums[i], + * nums[j] and nums[k] such that i < j < k and nums[i] < nums[k] < nums[j]. + * + * Return true if there is a 132 pattern in nums, otherwise, return false. + */ + +/** + * @param {number[]} nums + * @return {boolean} + */ +var find132pattern = function(nums) { + const stack = []; + + for (let i = nums.length - 1, j = -Infinity; i >= 0; i--) { + while (nums[i] > stack[stack.length - 1]) { + j = stack.pop(); + } + if (nums[i] < j) { + return true; + } + stack.push(nums[i]); + } + + return false; +}; diff --git a/README.md b/README.md index b7a432bd..3b3ca0b7 100644 --- a/README.md +++ b/README.md @@ -208,6 +208,7 @@ 448|[Find All Numbers Disappeared in an Array](./0448-find-all-numbers-disappeared-in-an-array.js)|Easy| 451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| 452|[Minimum Number of Arrows to Burst Balloons](./0452-minimum-number-of-arrows-to-burst-balloons.js)|Medium| +456|[132 Pattern](./0456-132-pattern.js)|Medium| 459|[Repeated Substring Pattern](./0459-repeated-substring-pattern.js)|Easy| 461|[Hamming Distance](./0461-hamming-distance.js)|Easy| 463|[Island Perimeter](./0463-island-perimeter.js)|Medium| From b6314b49e49df4ae5cb28fc59fa8fef111e09f02 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 19 Jan 2025 08:44:23 -0600 Subject: [PATCH 497/919] Add solution #507 --- 0507-perfect-number.js | 23 +++++++++++++++++++++++ README.md | 1 + 2 files changed, 24 insertions(+) create mode 100644 0507-perfect-number.js diff --git a/0507-perfect-number.js b/0507-perfect-number.js new file mode 100644 index 00000000..284c04ad --- /dev/null +++ b/0507-perfect-number.js @@ -0,0 +1,23 @@ +/** + * 507. Perfect Number + * https://leetcode.com/problems/perfect-number/ + * Difficulty: Easy + * + * A perfect number is a positive integer that is equal to the sum of its positive + * divisors, excluding the number itself. A divisor of an integer x is an integer + * that can divide x evenly. + * + * Given an integer n, return true if n is a perfect number, otherwise return false. + */ + +/** + * @param {number} num + * @return {boolean} + */ +var checkPerfectNumber = function(num) { + let result = 0; + for (let i = 1; i <= num / 2; i++) { + if (num % i === 0) result += i; + } + return result === num; +}; diff --git a/README.md b/README.md index 3b3ca0b7..d07633c3 100644 --- a/README.md +++ b/README.md @@ -224,6 +224,7 @@ 503|[Next Greater Element II](./0503-next-greater-element-ii.js)|Medium| 504|[Base 7](./0504-base-7.js)|Easy| 506|[Relative Ranks](./0506-relative-ranks.js)|Easy| +507|[Perfect Number](./0507-perfect-number.js)|Easy| 509|[Fibonacci Number](./0509-fibonacci-number.js)|Easy| 520|[Detect Capital](./0520-detect-capital.js)|Easy| 541|[Reverse String II](./0541-reverse-string-ii.js)|Easy| From 461ddd80514989e417e025a584f28d69ea074706 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 19 Jan 2025 08:45:08 -0600 Subject: [PATCH 498/919] Add solution #521 --- 0521-longest-uncommon-subsequence-i.js | 20 ++++++++++++++++++++ README.md | 1 + 2 files changed, 21 insertions(+) create mode 100644 0521-longest-uncommon-subsequence-i.js diff --git a/0521-longest-uncommon-subsequence-i.js b/0521-longest-uncommon-subsequence-i.js new file mode 100644 index 00000000..de08d369 --- /dev/null +++ b/0521-longest-uncommon-subsequence-i.js @@ -0,0 +1,20 @@ +/** + * 521. Longest Uncommon Subsequence I + * https://leetcode.com/problems/longest-uncommon-subsequence-i/ + * Difficulty: Easy + * + * Given two strings a and b, return the length of the longest uncommon subsequence between + * a and b. If no such uncommon subsequence exists, return -1. + * + * An uncommon subsequence between two strings is a string that is a subsequence of exactly + * one of them. + */ + +/** + * @param {string} a + * @param {string} b + * @return {number} + */ +var findLUSlength = function(a, b) { + return a === b ? -1 : Math.max(a.length, b.length); +}; diff --git a/README.md b/README.md index d07633c3..b54bb880 100644 --- a/README.md +++ b/README.md @@ -227,6 +227,7 @@ 507|[Perfect Number](./0507-perfect-number.js)|Easy| 509|[Fibonacci Number](./0509-fibonacci-number.js)|Easy| 520|[Detect Capital](./0520-detect-capital.js)|Easy| +521|[Longest Uncommon Subsequence I](./0521-longest-uncommon-subsequence-i.js)|Easy| 541|[Reverse String II](./0541-reverse-string-ii.js)|Easy| 542|[01 Matrix](./0542-01-matrix.js)|Medium| 547|[Number of Provinces](./0547-number-of-provinces.js)|Medium| From 108a61f79c896885ae974a039e7134a111706b33 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 19 Jan 2025 08:48:20 -0600 Subject: [PATCH 499/919] Add solution #1368 --- ...-make-at-least-one-valid-path-in-a-grid.js | 50 +++++++++++++++++++ README.md | 1 + 2 files changed, 51 insertions(+) create mode 100644 1368-minimum-cost-to-make-at-least-one-valid-path-in-a-grid.js diff --git a/1368-minimum-cost-to-make-at-least-one-valid-path-in-a-grid.js b/1368-minimum-cost-to-make-at-least-one-valid-path-in-a-grid.js new file mode 100644 index 00000000..9cf09d9b --- /dev/null +++ b/1368-minimum-cost-to-make-at-least-one-valid-path-in-a-grid.js @@ -0,0 +1,50 @@ +/** + * 1368. Minimum Cost to Make at Least One Valid Path in a Grid + * https://leetcode.com/problems/minimum-cost-to-make-at-least-one-valid-path-in-a-grid/ + * Difficulty: Hard + * + * Given an m x n grid. Each cell of the grid has a sign pointing to the next cell you should + * visit if you are currently in this cell. The sign of grid[i][j] can be: + * - 1 which means go to the cell to the right. (i.e go from grid[i][j] to grid[i][j + 1]) + * - 2 which means go to the cell to the left. (i.e go from grid[i][j] to grid[i][j - 1]) + * - 3 which means go to the lower cell. (i.e go from grid[i][j] to grid[i + 1][j]) + * - 4 which means go to the upper cell. (i.e go from grid[i][j] to grid[i - 1][j]) + * + * Notice that there could be some signs on the cells of the grid that point outside the grid. + * + * You will initially start at the upper left cell (0, 0). A valid path in the grid is a path + * that starts from the upper left cell (0, 0) and ends at the bottom-right cell (m - 1, n - 1) + * following the signs on the grid. The valid path does not have to be the shortest. + * + * You can modify the sign on a cell with cost = 1. You can modify the sign on a cell one time + * only. + * + * Return the minimum cost to make the grid have at least one valid path. + */ + +/** + * @param {number[][]} grid + * @return {number} + */ +var minCost = function(grid) { + const queue = [[0, 0]]; + const directions = [[0, 1, 1], [0, -1, 2], [1, 0, 3], [-1, 0, 4]]; + const bfs = grid.map(r => r.map(_ => Infinity)); + bfs[0][0] = 0; + + while (queue.length > 0) { + const [x, y] = queue.shift(); + for (const [dx, dy, value] of directions) { + const [cX, cY] = [x + dx, y + dy]; + if (grid[cX]?.[cY]) { + const updatedValue = bfs[x][y] + (grid[x][y] !== value); + if (updatedValue < bfs[cX][cY]) { + bfs[cX][cY] = updatedValue; + queue.push([cX, cY]); + } + } + } + } + + return bfs.at(-1).at(-1); +}; diff --git a/README.md b/README.md index b54bb880..6822c183 100644 --- a/README.md +++ b/README.md @@ -345,6 +345,7 @@ 1356|[Sort Integers by The Number of 1 Bits](./1356-sort-integers-by-the-number-of-1-bits.js)|Easy| 1360|[Number of Days Between Two Dates](./1360-number-of-days-between-two-dates.js)|Easy| 1365|[How Many Numbers Are Smaller Than the Current Number](./1365-how-many-numbers-are-smaller-than-the-current-number.js)|Easy| +1368|[Minimum Cost to Make at Least One Valid Path in a Grid](./1368-minimum-cost-to-make-at-least-one-valid-path-in-a-grid.js)|Hard| 1374|[Generate a String With Characters That Have Odd Counts](./1374-generate-a-string-with-characters-that-have-odd-counts.js)|Easy| 1380|[Lucky Numbers in a Matrix](./1380-lucky-numbers-in-a-matrix.js)|Easy| 1389|[Create Target Array in the Given Order](./1389-create-target-array-in-the-given-order.js)|Easy| From d9b03a2e5fac3d1f27ff82b0b84c05c76834e1d9 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 20 Jan 2025 15:22:10 -0600 Subject: [PATCH 500/919] Add solution #2661 --- ...-first-completely-painted-row-or-column.js | 38 +++++++++++++++++++ README.md | 1 + 2 files changed, 39 insertions(+) create mode 100644 2661-first-completely-painted-row-or-column.js diff --git a/2661-first-completely-painted-row-or-column.js b/2661-first-completely-painted-row-or-column.js new file mode 100644 index 00000000..14848c0c --- /dev/null +++ b/2661-first-completely-painted-row-or-column.js @@ -0,0 +1,38 @@ +/** + * 2661. First Completely Painted Row or Column + * https://leetcode.com/problems/first-completely-painted-row-or-column/ + * Difficulty: Medium + * + * You are given a 0-indexed integer array arr, and an m x n integer matrix mat. arr and mat + * both contain all the integers in the range [1, m * n]. + * + * Go through each index i in arr starting from index 0 and paint the cell in mat containing + * the integer arr[i]. + * + * Return the smallest index i at which either a row or a column will be completely painted + * in mat. + */ + +/** + * @param {number[]} arr + * @param {number[][]} mat + * @return {number} + */ +var firstCompleteIndex = function(arr, mat) { + const rows = new Array(mat.length).fill(0); + const columns = new Array(mat[0].length).fill(0); + const map = new Map(); + + for (let i = 0; i < mat.length; i++) { + for (let j = 0; j < mat[i].length; j++) { + map.set(mat[i][j], [i, j]); + } + } + + for (let i = 0; i < arr.length; i++) { + const [rowIndex, columnIndex] = map.get(arr[i]); + if (++rows[rowIndex] === mat[0].length || ++columns[columnIndex] === mat.length) { + return i; + } + } +}; diff --git a/README.md b/README.md index 6822c183..a5908c91 100644 --- a/README.md +++ b/README.md @@ -457,6 +457,7 @@ 2649|[Nested Array Generator](./2649-nested-array-generator.js)|Medium| 2650|[Design Cancellable Function](./2650-design-cancellable-function.js)|Hard| 2657|[Find the Prefix Common Array of Two Arrays](./2657-find-the-prefix-common-array-of-two-arrays.js)|Medium| +2661|[First Completely Painted Row or Column](./2661-first-completely-painted-row-or-column.js)|Medium| 2665|[Counter II](./2665-counter-ii.js)|Easy| 2666|[Allow One Function Call](./2666-allow-one-function-call.js)|Easy| 2667|[Create Hello World Function](./2667-create-hello-world-function.js)|Easy| From b50efbd3c75cc4dfae506b427593e8260bb14ada Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 20 Jan 2025 15:23:19 -0600 Subject: [PATCH 501/919] Add solution #108 --- ...vert-sorted-array-to-binary-search-tree.js | 31 +++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 0108-convert-sorted-array-to-binary-search-tree.js diff --git a/0108-convert-sorted-array-to-binary-search-tree.js b/0108-convert-sorted-array-to-binary-search-tree.js new file mode 100644 index 00000000..b0b61efb --- /dev/null +++ b/0108-convert-sorted-array-to-binary-search-tree.js @@ -0,0 +1,31 @@ +/** + * 108. Convert Sorted Array to Binary Search Tree + * https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/ + * Difficulty: Easy + * + * Given an integer array nums where the elements are sorted in ascending order, convert it + * to a height-balanced binary search 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) + * } + */ +/** + * @param {number[]} nums + * @return {TreeNode} + */ +var sortedArrayToBST = function(nums) { + if (!nums.length) return null; + + const middleIndex = Math.floor(nums.length / 2); + const root = new TreeNode(nums[middleIndex]); + root.left = sortedArrayToBST(nums.slice(0, middleIndex)); + root.right = sortedArrayToBST(nums.slice(middleIndex + 1)); + + return root; +}; diff --git a/README.md b/README.md index a5908c91..4317fb61 100644 --- a/README.md +++ b/README.md @@ -103,6 +103,7 @@ 101|[Symmetric Tree](./0101-symmetric-tree.js)|Easy| 102|[Binary Tree Level Order Traversal](./0102-binary-tree-level-order-traversal.js)|Medium| 104|[Maximum Depth of Binary Tree](./0104-maximum-depth-of-binary-tree.js)|Easy| +108|[Convert Sorted Array to Binary Search Tree](./0108-convert-sorted-array-to-binary-search-tree.js)|Easy| 110|[Balanced Binary Tree](./0110-balanced-binary-tree.js)|Easy| 111|[Minimum Depth of Binary Tree](./0111-minimum-depth-of-binary-tree.js)|Easy| 112|[Path Sum](./0112-path-sum.js)|Easy| From 1b009067229738fd1d0ecee0092d6cfbab035cef Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 20 Jan 2025 15:24:05 -0600 Subject: [PATCH 502/919] Add solution #114 --- 0114-flatten-binary-tree-to-linked-list.js | 39 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 40 insertions(+) create mode 100644 0114-flatten-binary-tree-to-linked-list.js diff --git a/0114-flatten-binary-tree-to-linked-list.js b/0114-flatten-binary-tree-to-linked-list.js new file mode 100644 index 00000000..eeacae52 --- /dev/null +++ b/0114-flatten-binary-tree-to-linked-list.js @@ -0,0 +1,39 @@ +/** + * 114. Flatten Binary Tree to Linked List + * https://leetcode.com/problems/flatten-binary-tree-to-linked-list/ + * Difficulty: Medium + * + * Given the root of a binary tree, flatten the tree into a "linked list": + * - The "linked list" should use the same TreeNode class where the right child pointer points + * to the next node in the list and the left child pointer is always null. + * - The "linked list" should be in the same order as a pre-order traversal of the 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) + * } + */ +/** + * @param {TreeNode} root + * @return {void} Do not return anything, modify root in-place instead. + */ +var flatten = function(root) { + if (root === null) return; + + if (root.left) { + let previous = root.left; + while (previous.right) { + previous = previous.right; + } + const rightNode = root.right; + root.right = root.left; + previous.right = rightNode; + root.left = null; + } + + flatten(root.right); +}; diff --git a/README.md b/README.md index 4317fb61..52d0d1bb 100644 --- a/README.md +++ b/README.md @@ -108,6 +108,7 @@ 111|[Minimum Depth of Binary Tree](./0111-minimum-depth-of-binary-tree.js)|Easy| 112|[Path Sum](./0112-path-sum.js)|Easy| 113|[Path Sum II](./0113-path-sum-ii.js)|Medium| +114|[Flatten Binary Tree to Linked List](./0114-flatten-binary-tree-to-linked-list.js)|Medium| 116|[Populating Next Right Pointers in Each Node](./0116-populating-next-right-pointers-in-each-node.js)|Medium| 118|[Pascal's Triangle](./0118-pascals-triangle.js)|Easy| 119|[Pascal's Triangle II](./0119-pascals-triangle-ii.js)|Easy| From ffbf11912c6febbc1610696252da248854e926ef Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 20 Jan 2025 15:25:03 -0600 Subject: [PATCH 503/919] Add solution #115 --- 0115-distinct-subsequences.js | 29 +++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 30 insertions(+) create mode 100644 0115-distinct-subsequences.js diff --git a/0115-distinct-subsequences.js b/0115-distinct-subsequences.js new file mode 100644 index 00000000..a6826f93 --- /dev/null +++ b/0115-distinct-subsequences.js @@ -0,0 +1,29 @@ +/** + * 115. Distinct Subsequences + * https://leetcode.com/problems/distinct-subsequences/ + * Difficulty: Hard + * + * Given two strings s and t, return the number of distinct subsequences of s which equals t. + * + * The test cases are generated so that the answer fits on a 32-bit signed integer. + */ + +/** + * @param {string} s + * @param {string} t + * @return {number} + */ +var numDistinct = function(s, t) { + const nums = new Array(t.length + 1).fill(0); + nums[0] = 1; + + for (let i = 0; i < s.length; i++) { + for (let j = nums.length - 1; j >= 0; j--) { + if (s[i] === t[j]) { + nums[j + 1] += nums[j]; + } + } + } + + return nums[t.length]; +}; diff --git a/README.md b/README.md index 52d0d1bb..dd792ec8 100644 --- a/README.md +++ b/README.md @@ -109,6 +109,7 @@ 112|[Path Sum](./0112-path-sum.js)|Easy| 113|[Path Sum II](./0113-path-sum-ii.js)|Medium| 114|[Flatten Binary Tree to Linked List](./0114-flatten-binary-tree-to-linked-list.js)|Medium| +115|[Distinct Subsequences](./0115-distinct-subsequences.js)|Hard| 116|[Populating Next Right Pointers in Each Node](./0116-populating-next-right-pointers-in-each-node.js)|Medium| 118|[Pascal's Triangle](./0118-pascals-triangle.js)|Easy| 119|[Pascal's Triangle II](./0119-pascals-triangle-ii.js)|Easy| From 6fe5d3e50049baa2a0d356e56d08ca3969d3798b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 20 Jan 2025 15:25:51 -0600 Subject: [PATCH 504/919] Add solution #92 --- 0092-reverse-linked-list-ii.js | 42 ++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 43 insertions(+) create mode 100644 0092-reverse-linked-list-ii.js diff --git a/0092-reverse-linked-list-ii.js b/0092-reverse-linked-list-ii.js new file mode 100644 index 00000000..32097020 --- /dev/null +++ b/0092-reverse-linked-list-ii.js @@ -0,0 +1,42 @@ +/** + * 92. Reverse Linked List II + * https://leetcode.com/problems/reverse-linked-list-ii/ + * Difficulty: Medium + * + * Given the head of a singly linked list and two integers left and right where + * left <= right, reverse the nodes of the list from position left to position + * right, and return the reversed list. + */ + +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @param {number} left + * @param {number} right + * @return {ListNode} + */ +var reverseBetween = function(head, left, right) { + const result = new ListNode(0, head); + let previous = result; + let currentIndex = 1; + + while (currentIndex++ < left) { + previous = previous.next; + } + + const tail = previous.next; + while (left++ < right) { + const next = tail.next; + tail.next = next.next; + next.next = previous.next; + previous.next = next; + } + + return result.next; +}; diff --git a/README.md b/README.md index dd792ec8..7feab42e 100644 --- a/README.md +++ b/README.md @@ -93,6 +93,7 @@ 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| 89|[Gray Code](./0089-gray-code.js)|Medium| 90|[Subsets II](./0090-subsets-ii.js)|Medium| +92|[Reverse Linked List II](./0092-reverse-linked-list-ii.js)|Medium| 93|[Restore IP Addresses](./0093-restore-ip-addresses.js)|Medium| 94|[Binary Tree Inorder Traversal](./0094-binary-tree-inorder-traversal.js)|Easy| 95|[Unique Binary Search Trees II](./0095-unique-binary-search-trees-ii.js)|Medium| From ec08bcfad8e6cb95a874e3110beda7e3d4017cea Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 21 Jan 2025 17:41:40 -0600 Subject: [PATCH 505/919] Add solution #1217 --- ...cost-to-move-chips-to-the-same-position.js | 23 +++++++++++++++++++ README.md | 1 + 2 files changed, 24 insertions(+) create mode 100644 1217-minimum-cost-to-move-chips-to-the-same-position.js diff --git a/1217-minimum-cost-to-move-chips-to-the-same-position.js b/1217-minimum-cost-to-move-chips-to-the-same-position.js new file mode 100644 index 00000000..f6334444 --- /dev/null +++ b/1217-minimum-cost-to-move-chips-to-the-same-position.js @@ -0,0 +1,23 @@ +/** + * 1217. Minimum Cost to Move Chips to The Same Position + * https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/ + * Difficulty: Easy + * + * We have n chips, where the position of the ith chip is position[i]. + * + * We need to move all the chips to the same position. In one step, we can change the position + * of the ith chip from position[i] to: + * - position[i] + 2 or position[i] - 2 with cost = 0. + * - position[i] + 1 or position[i] - 1 with cost = 1. + * + * Return the minimum cost needed to move all the chips to the same position. + */ + +/** + * @param {number[]} position + * @return {number} + */ +var minCostToMoveChips = function(position) { + const count = position.reduce((result, n) => n % 2 ? ++result : result, 0); + return count >= position.length / 2 ? position.length - count : count; +}; diff --git a/README.md b/README.md index 7feab42e..1c049527 100644 --- a/README.md +++ b/README.md @@ -323,6 +323,7 @@ 1122|[Relative Sort Array](./1122-relative-sort-array.js)|Easy| 1189|[Maximum Number of Balloons](./1189-maximum-number-of-balloons.js)|Easy| 1207|[Unique Number of Occurrences](./1207-unique-number-of-occurrences.js)|Easy| +1217|[Minimum Cost to Move Chips to The Same Position](./1217-minimum-cost-to-move-chips-to-the-same-position.js)|Easy| 1232|[Check If It Is a Straight Line](./1232-check-if-it-is-a-straight-line.js)|Easy| 1233|[Remove Sub-Folders from the Filesystem](./1233-remove-sub-folders-from-the-filesystem.js)|Medium| 1249|[Minimum Remove to Make Valid Parentheses](./1249-minimum-remove-to-make-valid-parentheses.js)|Medium| From 5cd4b1a0cee2a25b946272305fb967cd1de36ab0 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 21 Jan 2025 17:42:36 -0600 Subject: [PATCH 506/919] Add solution #1208 --- 1208-get-equal-substrings-within-budget.js | 35 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 36 insertions(+) create mode 100644 1208-get-equal-substrings-within-budget.js diff --git a/1208-get-equal-substrings-within-budget.js b/1208-get-equal-substrings-within-budget.js new file mode 100644 index 00000000..3c67e55b --- /dev/null +++ b/1208-get-equal-substrings-within-budget.js @@ -0,0 +1,35 @@ +/** + * 1208. Get Equal Substrings Within Budget + * https://leetcode.com/problems/get-equal-substrings-within-budget/ + * Difficulty: Medium + * + * You are given two strings s and t of the same length and an integer maxCost. + * + * You want to change s to t. Changing the ith character of s to ith character of t costs + * |s[i] - t[i]| (i.e., the absolute difference between the ASCII values of the characters). + * + * Return the maximum length of a substring of s that can be changed to be the same as the + * corresponding substring of t with a cost less than or equal to maxCost. If there is no + * substring from s that can be changed to its corresponding substring from t, return 0. + */ + +/** + * @param {string} s + * @param {string} t + * @param {number} maxCost + * @return {number} + */ +var equalSubstring = function(s, t, maxCost) { + let left = -1; + + for (let right = 0; right < s.length; right++) { + maxCost -= Math.abs(s.charCodeAt(right) - t.charCodeAt(right)); + + if (maxCost < 0) { + left++; + maxCost += Math.abs(s.charCodeAt(left) - t.charCodeAt(left)); + } + } + + return s.length - left - 1; +}; diff --git a/README.md b/README.md index 1c049527..1cc2f7ea 100644 --- a/README.md +++ b/README.md @@ -323,6 +323,7 @@ 1122|[Relative Sort Array](./1122-relative-sort-array.js)|Easy| 1189|[Maximum Number of Balloons](./1189-maximum-number-of-balloons.js)|Easy| 1207|[Unique Number of Occurrences](./1207-unique-number-of-occurrences.js)|Easy| +1208|[Get Equal Substrings Within Budget](./1208-get-equal-substrings-within-budget.js)|Medium| 1217|[Minimum Cost to Move Chips to The Same Position](./1217-minimum-cost-to-move-chips-to-the-same-position.js)|Easy| 1232|[Check If It Is a Straight Line](./1232-check-if-it-is-a-straight-line.js)|Easy| 1233|[Remove Sub-Folders from the Filesystem](./1233-remove-sub-folders-from-the-filesystem.js)|Medium| From c92d853cafbda5c1c55e7d0bf6dd15ee58ba6e80 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 21 Jan 2025 17:45:03 -0600 Subject: [PATCH 507/919] Add solution #1206 --- 1206-design-skiplist.js | 62 +++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 63 insertions(+) create mode 100644 1206-design-skiplist.js diff --git a/1206-design-skiplist.js b/1206-design-skiplist.js new file mode 100644 index 00000000..a53ce2d3 --- /dev/null +++ b/1206-design-skiplist.js @@ -0,0 +1,62 @@ +/** + * 1206. Design Skiplist + * https://leetcode.com/problems/design-skiplist/ + * Difficulty: Hard + * + * Design a Skiplist without using any built-in libraries. + * + * A skiplist is a data structure that takes O(log(n)) time to add, erase and search. Comparing with + * treap and red-black tree which has the same function and performance, the code length of Skiplist + * can be comparatively short and the idea behind Skiplists is just simple linked lists. + * + * For example, we have a Skiplist containing [30,40,50,60,70,90] and we want to add 80 and 45 into + * it. The Skiplist works this way: + * + * You can see there are many layers in the Skiplist. Each layer is a sorted linked list. With the + * help of the top layers, add, erase and search can be faster than O(n). It can be proven that the + * average time complexity for each operation is O(log(n)) and space complexity is O(n). + * + * See more about Skiplist: https://en.wikipedia.org/wiki/Skip_list + * Implement the Skiplist class: + * - Skiplist() Initializes the object of the skiplist. + * - bool search(int target) Returns true if the integer target exists in the Skiplist or false + * otherwise. + * - void add(int num) Inserts the value num into the SkipList. + * - bool erase(int num) Removes the value num from the Skiplist and returns true. If num does not + * exist in the Skiplist, do nothing and return false. If there exist multiple num values, + * removing any one of them is fine. + */ + +var Skiplist = function() { + this.values = {}; +}; + +/** + * @param {number} target + * @return {boolean} + */ +Skiplist.prototype.search = function(target) { + return target in this.values; +}; + +/** + * @param {number} num + * @return {void} + */ +Skiplist.prototype.add = function(num) { + this.values[num] = (this.values[num] ?? 0) + 1; +}; + +/** + * @param {number} num + * @return {boolean} + */ +Skiplist.prototype.erase = function(num) { + if (!(num in this.values)) { + return false; + } + if (!--this.values[num]) { + delete this.values[num]; + } + return true; +}; diff --git a/README.md b/README.md index 1cc2f7ea..f3fa7fdb 100644 --- a/README.md +++ b/README.md @@ -322,6 +322,7 @@ 1108|[Defanging an IP Address](./1108-defanging-an-ip-address.js)|Easy| 1122|[Relative Sort Array](./1122-relative-sort-array.js)|Easy| 1189|[Maximum Number of Balloons](./1189-maximum-number-of-balloons.js)|Easy| +1206|[Design Skiplist](./1206-design-skiplist.js)|Hard| 1207|[Unique Number of Occurrences](./1207-unique-number-of-occurrences.js)|Easy| 1208|[Get Equal Substrings Within Budget](./1208-get-equal-substrings-within-budget.js)|Medium| 1217|[Minimum Cost to Move Chips to The Same Position](./1217-minimum-cost-to-move-chips-to-the-same-position.js)|Easy| From 57b236f9b5e35ab8d3fe72ef115dc277f1ae9bc5 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 21 Jan 2025 17:46:19 -0600 Subject: [PATCH 508/919] Add solution #2017 --- 2017-grid-game.js | 38 ++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 39 insertions(+) create mode 100644 2017-grid-game.js diff --git a/2017-grid-game.js b/2017-grid-game.js new file mode 100644 index 00000000..a3a4445a --- /dev/null +++ b/2017-grid-game.js @@ -0,0 +1,38 @@ +/** + * 2017. Grid Game + * https://leetcode.com/problems/grid-game/ + * Difficulty: Medium + * + * You are given a 0-indexed 2D array grid of size 2 x n, where grid[r][c] represents the number + * of points at position (r, c) on the matrix. Two robots are playing a game on this matrix. + * + * Both robots initially start at (0, 0) and want to reach (1, n-1). Each robot may only move + * to the right ((r, c) to (r, c + 1)) or down ((r, c) to (r + 1, c)). + * + * At the start of the game, the first robot moves from (0, 0) to (1, n-1), collecting all the + * points from the cells on its path. For all cells (r, c) traversed on the path, grid[r][c] is + * set to 0. Then, the second robot moves from (0, 0) to (1, n-1), collecting the points on its + * path. Note that their paths may intersect with one another. + * + * The first robot wants to minimize the number of points collected by the second robot. In + * contrast, the second robot wants to maximize the number of points it collects. If both + * robots play optimally, return the number of points collected by the second robot. + */ + +/** + * @param {number[][]} grid + * @return {number} + */ +var gridGame = function(grid) { + let result = Infinity; + let sum1 = grid[0].reduce((a, b) => a + b, 0); + let sum2 = 0; + + for (let i = 0; i < grid[0].length; i++) { + sum1 -= grid[0][i]; + result = Math.min(result, Math.max(sum1, sum2)); + sum2 += grid[1][i]; + } + + return result; +}; diff --git a/README.md b/README.md index f3fa7fdb..f5620252 100644 --- a/README.md +++ b/README.md @@ -417,6 +417,7 @@ 2000|[Reverse Prefix of Word](./2000-reverse-prefix-of-word.js)|Easy| 2011|[Final Value of Variable After Performing Operations](./2011-final-value-of-variable-after-performing-operations.js)|Easy| 2016|[Maximum Difference Between Increasing Elements](./2016-maximum-difference-between-increasing-elements.js)|Easy| +2017|[Grid Game](./2017-grid-game.js)|Medium| 2027|[Minimum Moves to Convert String](./2027-minimum-moves-to-convert-string.js)|Easy| 2037|[Minimum Number of Moves to Seat Everyone](./2037-minimum-number-of-moves-to-seat-everyone.js)|Easy| 2047|[Number of Valid Words in a Sentence](./2047-number-of-valid-words-in-a-sentence.js)|Easy| From f71851820ad97af0a597e54538a3d7f221037d86 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 21 Jan 2025 17:47:43 -0600 Subject: [PATCH 509/919] Add solution #1200 --- 1200-minimum-absolute-difference.js | 29 +++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 30 insertions(+) create mode 100644 1200-minimum-absolute-difference.js diff --git a/1200-minimum-absolute-difference.js b/1200-minimum-absolute-difference.js new file mode 100644 index 00000000..ac283556 --- /dev/null +++ b/1200-minimum-absolute-difference.js @@ -0,0 +1,29 @@ +/** + * 1200. Minimum Absolute Difference + * https://leetcode.com/problems/minimum-absolute-difference/ + * Difficulty: Easy + * + * Given an array of distinct integers arr, find all pairs of elements with the minimum absolute + * difference of any two elements. + * + * Return a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows: + * - a, b are from arr + * - a < b + * - b - a equals to the minimum absolute difference of any two elements in arr + */ + +/** + * @param {number[]} arr + * @return {number[][]} + */ +var minimumAbsDifference = function(arr) { + arr.sort((a, b) => a - b); + + const min = arr.reduce((m, n, i) => Math.min(m, n - (arr[i - 1] ?? -Infinity)), Infinity); + return arr.reduce((result, n, i) => { + if (min === n - arr[i - 1]) { + result.push([arr[i - 1], n]); + } + return result; + }, []); +}; diff --git a/README.md b/README.md index f5620252..01d6a3f7 100644 --- a/README.md +++ b/README.md @@ -322,6 +322,7 @@ 1108|[Defanging an IP Address](./1108-defanging-an-ip-address.js)|Easy| 1122|[Relative Sort Array](./1122-relative-sort-array.js)|Easy| 1189|[Maximum Number of Balloons](./1189-maximum-number-of-balloons.js)|Easy| +1200|[Minimum Absolute Difference](./1200-minimum-absolute-difference.js)|Easy| 1206|[Design Skiplist](./1206-design-skiplist.js)|Hard| 1207|[Unique Number of Occurrences](./1207-unique-number-of-occurrences.js)|Easy| 1208|[Get Equal Substrings Within Budget](./1208-get-equal-substrings-within-budget.js)|Medium| From d8a104145c476780688e293f3629cdaeaf59ee6b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 22 Jan 2025 17:42:09 -0600 Subject: [PATCH 510/919] Add solution #868 --- 0868-binary-gap.js | 20 ++++++++++++++++++++ README.md | 1 + 2 files changed, 21 insertions(+) create mode 100644 0868-binary-gap.js diff --git a/0868-binary-gap.js b/0868-binary-gap.js new file mode 100644 index 00000000..bad3ba48 --- /dev/null +++ b/0868-binary-gap.js @@ -0,0 +1,20 @@ +/** + * 868. Binary Gap + * https://leetcode.com/problems/binary-gap/ + * Difficulty: Easy + * + * 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. + */ + +/** + * @param {number} n + * @return {number} + */ +var binaryGap = function(n) { + return Math.max(0, ...n.toString(2).split('1').slice(1, -1).map(s => s.length + 1)); +}; diff --git a/README.md b/README.md index 01d6a3f7..e04bc6af 100644 --- a/README.md +++ b/README.md @@ -283,6 +283,7 @@ 844|[Backspace String Compare](./0844-backspace-string-compare.js)|Easy| 846|[Hand of Straights](./0846-hand-of-straights.js)|Medium| 867|[Transpose Matrix](./0867-transpose-matrix.js)|Easy| +868|[Binary Gap](./0868-binary-gap.js)|Easy| 872|[Leaf-Similar Trees](./0872-leaf-similar-trees.js)|Easy| 876|[Middle of the Linked List](./0876-middle-of-the-linked-list.js)|Easy| 884|[Uncommon Words from Two Sentences](./0884-uncommon-words-from-two-sentences.js)|Easy| From 0a1300742f430dee190ad0a9bb217b2ac528e7c1 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 22 Jan 2025 17:43:04 -0600 Subject: [PATCH 511/919] Add solution #697 --- 0697-degree-of-an-array.js | 39 ++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 40 insertions(+) create mode 100644 0697-degree-of-an-array.js diff --git a/0697-degree-of-an-array.js b/0697-degree-of-an-array.js new file mode 100644 index 00000000..b0131f34 --- /dev/null +++ b/0697-degree-of-an-array.js @@ -0,0 +1,39 @@ +/** + * 697. Degree of an Array + * https://leetcode.com/problems/degree-of-an-array/ + * Difficulty: Easy + * + * Given a non-empty array of non-negative integers nums, the degree of this array is + * defined as the maximum frequency of any one of its elements. + * + * Your task is to find the smallest possible length of a (contiguous) subarray of + * nums, that has the same degree as nums. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var findShortestSubArray = function(nums) { + const map = new Map(); + + nums.forEach((key, index) => { + if (!map.has(key)) { + map.set(key, { start: index, end: index, count: 1 }); + } + const { start, end, count } = map.get(key); + map.set(key, { start, end: index, count: count + 1 }); + }); + + let max = 0; + let result = Infinity; + Array.from(map).forEach(([_, { start, end, count }]) => { + const min = (end - start) + 1; + if (count > max || (min < result && count === max)) { + result = min; + max = count; + } + }); + + return result; +}; diff --git a/README.md b/README.md index e04bc6af..1ac2816d 100644 --- a/README.md +++ b/README.md @@ -257,6 +257,7 @@ 680|[Valid Palindrome II](./0680-valid-palindrome-ii.js)|Easy| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| 695|[Max Area of Island](./0695-max-area-of-island.js)|Medium| +697|[Degree of an Array](./0697-degree-of-an-array.js)|Easy| 700|[Search in a Binary Search Tree](./0700-search-in-a-binary-search-tree.js)|Easy| 701|[Insert into a Binary Search Tree](./0701-insert-into-a-binary-search-tree.js)|Medium| 704|[Binary Search](./0704-binary-search.js)|Easy| From d4a4ab0846f9f06f517c69adfb7f2a709a4f3281 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 22 Jan 2025 17:44:06 -0600 Subject: [PATCH 512/919] Add solution #187 --- 0187-repeated-dna-sequences.js | 33 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 0187-repeated-dna-sequences.js diff --git a/0187-repeated-dna-sequences.js b/0187-repeated-dna-sequences.js new file mode 100644 index 00000000..089100ff --- /dev/null +++ b/0187-repeated-dna-sequences.js @@ -0,0 +1,33 @@ +/** + * 187. Repeated DNA Sequences + * https://leetcode.com/problems/repeated-dna-sequences/ + * Difficulty: Medium + * + * The DNA sequence is composed of a series of nucleotides abbreviated as 'A', 'C', 'G', and 'T': + * - For example, "ACGAATTCCG" is a DNA sequence. + * + * When studying DNA, it is useful to identify repeated sequences within the DNA. + * + * Given a string s that represents a DNA sequence, return all the 10-letter-long sequences + * (substrings) that occur more than once in a DNA molecule. You may return the answer in any order. + */ + +/** + * @param {string} s + * @return {string[]} + */ +var findRepeatedDnaSequences = function(s) { + let substring = s.slice(0, 10); + const set = new Set([substring]); + const result = new Set(); + + for (let i = 10; i < s.length; i++) { + substring = substring.slice(1) + s[i]; + if (set.has(substring)) { + result.add(substring); + } + set.add(substring); + } + + return [...result]; +}; diff --git a/README.md b/README.md index 1ac2816d..33bff922 100644 --- a/README.md +++ b/README.md @@ -143,6 +143,7 @@ 168|[Excel Sheet Column Title](./0168-excel-sheet-column-title.js)|Easy| 169|[Majority Element](./0169-majority-element.js)|Easy| 179|[Largest Number](./0179-largest-number.js)|Medium| +187|[Repeated DNA Sequences](./0187-repeated-dna-sequences.js)|Medium| 189|[Rotate Array](./0189-rotate-array.js)|Medium| 190|[Reverse Bits](./0190-reverse-bits.js)|Easy| 191|[Number of 1 Bits](./0191-number-of-1-bits.js)|Easy| From 8200d57b559e430f68432d2daa7e3cc4fa7411be Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 22 Jan 2025 17:45:00 -0600 Subject: [PATCH 513/919] Add solution #79 --- 0079-word-search.js | 52 +++++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 53 insertions(+) create mode 100644 0079-word-search.js diff --git a/0079-word-search.js b/0079-word-search.js new file mode 100644 index 00000000..233063e4 --- /dev/null +++ b/0079-word-search.js @@ -0,0 +1,52 @@ +/** + * 79. Word Search + * https://leetcode.com/problems/word-search/ + * Difficulty: Medium + * + * Given an m x n grid of characters board and a string word, return true if word exists + * in the grid. + * + * The word can be constructed from letters of sequentially adjacent cells, where adjacent + * cells are horizontally or vertically neighboring. The same letter cell may not be used + * more than once. + */ + +/** + * @param {character[][]} board + * @param {string} word + * @return {boolean} + */ +var exist = function(board, word) { + function backtrack(x, y, k) { + if (board[x][y] !== word[k]) { + return false; + } else if (k === word.length - 1) { + return true; + } + + board[x][y] = '-'; + + for (const direction of [[-1, 0], [0, 1], [1, 0], [0, -1]]) { + const [i, j] = [x + direction[0], y + direction[1]]; + if (i >= 0 && i < board.length && j >= 0 && j < board[0].length) { + if (backtrack(i, j, k + 1)) { + return true; + } + } + } + + board[x][y] = word[k]; + + return false; + } + + for (let i = 0; i < board.length; i++) { + for (let j = 0; j < board[0].length; j++) { + if (backtrack(i, j, 0)) { + return true; + } + } + } + + return false; +}; diff --git a/README.md b/README.md index 33bff922..519a1bb7 100644 --- a/README.md +++ b/README.md @@ -83,6 +83,7 @@ 75|[Sort Colors](./0075-sort-colors.js)|Medium| 77|[Combinations](./0077-combinations.js)|Medium| 78|[Subsets](./0078-subsets.js)|Medium| +79|[Word Search](./0079-word-search.js)|Medium| 80|[Remove Duplicates from Sorted Array II](./0080-remove-duplicates-from-sorted-array-ii.js)|Medium| 81|[Search in Rotated Sorted Array II](./0081-search-in-rotated-sorted-array-ii.js)|Medium| 82|[Remove Duplicates from Sorted List II](./0082-remove-duplicates-from-sorted-list-ii.js)|Medium| From 0f0bceee75db0577956c4e686d8bbe1126347ee5 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 22 Jan 2025 17:46:38 -0600 Subject: [PATCH 514/919] Add solution #1765 --- 1765-map-of-highest-peak.js | 44 +++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 45 insertions(+) create mode 100644 1765-map-of-highest-peak.js diff --git a/1765-map-of-highest-peak.js b/1765-map-of-highest-peak.js new file mode 100644 index 00000000..c1918d8a --- /dev/null +++ b/1765-map-of-highest-peak.js @@ -0,0 +1,44 @@ +/** + * 1765. Map of Highest Peak + * https://leetcode.com/problems/map-of-highest-peak/ + * Difficulty: Medium + * + * You are given an integer matrix isWater of size m x n that represents a map of land and + * water cells: + * - If isWater[i][j] == 0, cell (i, j) is a land cell. + * - If isWater[i][j] == 1, cell (i, j) is a water cell. + * + * You must assign each cell a height in a way that follows these rules: + * - The height of each cell must be non-negative. + * - If the cell is a water cell, its height must be 0. + * - Any two adjacent cells must have an absolute height difference of at most 1. A cell is + * adjacent to another cell if the former is directly north, east, south, or west of the + * latter (i.e., their sides are touching). + * + * Find an assignment of heights such that the maximum height in the matrix is maximized. + * + * Return an integer matrix height of size m x n where height[i][j] is cell (i, j)'s height. + * If there are multiple solutions, return any of them. + */ + +/** + * @param {number[][]} isWater + * @return {number[][]} + */ +var highestPeak = function(isWater) { + const map = isWater.map(row => row.map(() => 0)); + const values = isWater.map((row, i) => { + return row.map((value, j) => value ? [i, j] : 0); + }).flat().filter(Boolean); + + for (let value = 0; values.length > value;) { + const [i, j] = values[value++]; + const level = map[i][j] + 1; + [[1, 0], [-1, 0], [0, -1], [0, 1]] + .map(direction => [i + direction[0], j + direction[1]]) + .filter(([x, y]) => 0 === isWater[x]?.[y] && !map[x][y]) + .forEach(([x, y]) => (map[x][y] = level, values.push([x, y]))); + } + + return map; +}; diff --git a/README.md b/README.md index 519a1bb7..23c5929a 100644 --- a/README.md +++ b/README.md @@ -406,6 +406,7 @@ 1716|[Calculate Money in Leetcode Bank](./1716-calculate-money-in-leetcode-bank.js)|Easy| 1732|[Find the Highest Altitude](./1732-find-the-highest-altitude.js)|Easy| 1748|[Sum of Unique Elements](./1748-sum-of-unique-elements.js)|Easy| +1765|[Map of Highest Peak](./1765-map-of-highest-peak.js)|Medium| 1768|[Merge Strings Alternately](./1768-merge-strings-alternately.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| 1791|[Find Center of Star Graph](./1791-find-center-of-star-graph.js)|Easy| From 3f99575c76c23d98ce348fc219b1e8e9360abb03 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 23 Jan 2025 17:34:59 -0600 Subject: [PATCH 515/919] Add solution #2727 --- 2727-is-object-empty.js | 20 ++++++++++++++++++++ README.md | 1 + 2 files changed, 21 insertions(+) create mode 100644 2727-is-object-empty.js diff --git a/2727-is-object-empty.js b/2727-is-object-empty.js new file mode 100644 index 00000000..9f501d47 --- /dev/null +++ b/2727-is-object-empty.js @@ -0,0 +1,20 @@ +/** + * 2727. Is Object Empty + * https://leetcode.com/problems/is-object-empty/ + * Difficulty: Easy + * + * Given an object or an array, return if it is empty. + * + * - An empty object contains no key-value pairs. + * - An empty array contains no elements. + * + * You may assume the object or array is the output of JSON.parse. + */ + +/** + * @param {Object|Array} obj + * @return {boolean} + */ +var isEmpty = function(obj) { + return !Object.keys(obj).length; +}; diff --git a/README.md b/README.md index 23c5929a..1edeaf36 100644 --- a/README.md +++ b/README.md @@ -487,6 +487,7 @@ 2722|[Join Two Arrays by ID](./2722-join-two-arrays-by-id.js)|Medium| 2723|[Add Two Promises](./2723-add-two-promises.js)|Easy| 2724|[Sort By](./2724-sort-by.js)|Easy| +2727|[Is Object Empty](./2727-is-object-empty.js)|Easy| 3042|[Count Prefix and Suffix Pairs I](./3042-count-prefix-and-suffix-pairs-i.js)|Easy| 3110|[Score of a String](./3110-score-of-a-string.js)|Easy| 3223|[Minimum Length of String After Operations](./3223-minimum-length-of-string-after-operations.js)|Medium| From a44e53a266ba91a223c057dfbfdb5e5e932c96b3 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 23 Jan 2025 17:36:31 -0600 Subject: [PATCH 516/919] Add solution #2694 --- 2694-event-emitter.js | 66 +++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 67 insertions(+) create mode 100644 2694-event-emitter.js diff --git a/2694-event-emitter.js b/2694-event-emitter.js new file mode 100644 index 00000000..dc15da06 --- /dev/null +++ b/2694-event-emitter.js @@ -0,0 +1,66 @@ +/** + * 2694. Event Emitter + * https://leetcode.com/problems/event-emitter/ + * Difficulty: Medium + * + * Design an EventEmitter class. This interface is similar (but with some differences) to the one + * found in Node.js or the Event Target interface of the DOM. The EventEmitter should allow for + * subscribing to events and emitting them. + * + * Your EventEmitter class should have the following two methods: + * - subscribe - This method takes in two arguments: the name of an event as a string and a callback + * function. This callback function will later be called when the event is emitted. + * An event should be able to have multiple listeners for the same event. When emitting an event + * with multiple callbacks, each should be called in the order in which they were subscribed. + * An array of results should be returned. You can assume no callbacks passed to subscribe are + * referentially identical. + * The subscribe method should also return an object with an unsubscribe method that enables the + * user to unsubscribe. When it is called, the callback should be removed from the list of + * subscriptions and undefined should be returned. + * - emit - This method takes in two arguments: the name of an event as a string and an optional + * array of arguments that will be passed to the callback(s). If there are no callbacks subscribed + * to the given event, return an empty array. Otherwise, return an array of the results of all + * callback calls in the order they were subscribed. + */ + +class EventEmitter { + constructor() { + this.events = new Map(); + } + + /** + * @param {string} eventName + * @param {Function} callback + * @return {Object} + */ + subscribe(eventName, callback) { + if (!this.events.has(eventName)) { + this.events.set(eventName, []); + } + + const listeners = this.events.get(eventName); + listeners.push(callback); + + return { + unsubscribe: () => { + const index = listeners.indexOf(callback); + if (index !== -1) { + listeners.splice(index, 1); + } + } + }; + } + + /** + * @param {string} eventName + * @param {Array} args + * @return {Array} + */ + emit(eventName, args = []) { + if (!this.events.has(eventName)) { + return []; + } + + return this.events.get(eventName).map(listener => listener(...args)); + } +} diff --git a/README.md b/README.md index 1edeaf36..f3f68a4a 100644 --- a/README.md +++ b/README.md @@ -478,6 +478,7 @@ 2677|[Chunk Array](./2677-chunk-array.js)|Easy| 2683|[Neighboring Bitwise XOR](./2683-neighboring-bitwise-xor.js)|Medium| 2693|[Call Function with Custom Context](./2693-call-function-with-custom-context.js)|Medium| +2694|[Event Emitter](./2694-event-emitter.js)|Medium| 2695|[Array Wrapper](./2695-array-wrapper.js)|Easy| 2703|[Return Length of Arguments Passed](./2703-return-length-of-arguments-passed.js)|Easy| 2704|[To Be Or Not To Be](./2704-to-be-or-not-to-be.js)|Easy| From 032ba2f2a30acb8234c1c40de410dbb091857ea3 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 23 Jan 2025 17:39:28 -0600 Subject: [PATCH 517/919] Add solution #2726 --- 2726-calculator-with-method-chaining.js | 89 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 90 insertions(+) create mode 100644 2726-calculator-with-method-chaining.js diff --git a/2726-calculator-with-method-chaining.js b/2726-calculator-with-method-chaining.js new file mode 100644 index 00000000..c3ac6809 --- /dev/null +++ b/2726-calculator-with-method-chaining.js @@ -0,0 +1,89 @@ +/** + * 2726. Calculator with Method Chaining + * https://leetcode.com/problems/calculator-with-method-chaining/ + * Difficulty: Easy + * + * Design a Calculator class. The class should provide the mathematical operations of addition, + * subtraction, multiplication, division, and exponentiation. It should also allow consecutive + * operations to be performed using method chaining. The Calculator class constructor should + * accept a number which serves as the initial value of result. + * + * Your Calculator class should have the following methods: + * - add - This method adds the given number value to the result and returns the updated Calculator. + * - subtract - This method subtracts the given number value from the result and returns the + * updated Calculator. + * - multiply - This method multiplies the result by the given number value and returns the + * updated Calculator. + * - divide - This method divides the result by the given number value and returns the updated + * Calculator. If the passed value is 0, an error "Division by zero is not allowed" should + * be thrown. + * - power - This method raises the result to the power of the given number value and returns + * the updated Calculator. + * - getResult - This method returns the result. + * + * Solutions within 10-5 of the actual result are considered correct. + */ + +class Calculator { + /** + * @param {number} value + */ + constructor(value) { + this.value = value; + } + + /** + * @param {number} value + * @return {Calculator} + */ + add(value) { + this.value += value; + return this; + } + + /** + * @param {number} value + * @return {Calculator} + */ + subtract(value) { + this.value -= value; + return this; + } + + /** + * @param {number} value + * @return {Calculator} + */ + multiply(value) { + this.value *= value; + return this; + } + + /** + * @param {number} value + * @return {Calculator} + */ + divide(value) { + if (value === 0) { + throw new Error('Division by zero is not allowed'); + } + this.value /= value; + return this; + } + + /** + * @param {number} value + * @return {Calculator} + */ + power(value) { + this.value **= value; + return this; + } + + /** + * @return {number} + */ + getResult() { + return this.value; + } +} diff --git a/README.md b/README.md index f3f68a4a..d49d46b8 100644 --- a/README.md +++ b/README.md @@ -488,6 +488,7 @@ 2722|[Join Two Arrays by ID](./2722-join-two-arrays-by-id.js)|Medium| 2723|[Add Two Promises](./2723-add-two-promises.js)|Easy| 2724|[Sort By](./2724-sort-by.js)|Easy| +2726|[Calculator with Method Chaining](./2726-calculator-with-method-chaining.js)|Easy| 2727|[Is Object Empty](./2727-is-object-empty.js)|Easy| 3042|[Count Prefix and Suffix Pairs I](./3042-count-prefix-and-suffix-pairs-i.js)|Easy| 3110|[Score of a String](./3110-score-of-a-string.js)|Easy| From 9343c4587a4baa03225b42741bf039cb34cbb119 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 23 Jan 2025 17:40:17 -0600 Subject: [PATCH 518/919] Add solution #2725 --- 2725-interval-cancellation.js | 26 ++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 27 insertions(+) create mode 100644 2725-interval-cancellation.js diff --git a/2725-interval-cancellation.js b/2725-interval-cancellation.js new file mode 100644 index 00000000..3118da62 --- /dev/null +++ b/2725-interval-cancellation.js @@ -0,0 +1,26 @@ +/** + * 2725. Interval Cancellation + * https://leetcode.com/problems/interval-cancellation/ + * Difficulty: Easy + * + * Given a function fn, an array of arguments args, and an interval time t, return a cancel + * function cancelFn. + * + * After a delay of cancelTimeMs, the returned cancel function cancelFn will be invoked. + * > setTimeout(cancelFn, cancelTimeMs) + * + * The function fn should be called with args immediately and then called again every t + * milliseconds until cancelFn is called at cancelTimeMs ms. + */ + +/** + * @param {Function} fn + * @param {Array} args + * @param {number} t + * @return {Function} + */ +var cancellable = function(fn, args, t) { + fn(...args); + const timer = setInterval(() => fn(...args), t); + return () => clearInterval(timer); +}; diff --git a/README.md b/README.md index d49d46b8..0691b0d0 100644 --- a/README.md +++ b/README.md @@ -488,6 +488,7 @@ 2722|[Join Two Arrays by ID](./2722-join-two-arrays-by-id.js)|Medium| 2723|[Add Two Promises](./2723-add-two-promises.js)|Easy| 2724|[Sort By](./2724-sort-by.js)|Easy| +2725|[Interval Cancellation](./2725-interval-cancellation.js)|Easy| 2726|[Calculator with Method Chaining](./2726-calculator-with-method-chaining.js)|Easy| 2727|[Is Object Empty](./2727-is-object-empty.js)|Easy| 3042|[Count Prefix and Suffix Pairs I](./3042-count-prefix-and-suffix-pairs-i.js)|Easy| From 505be72a10a50369fa550ec5efe93df4e22531ed Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 23 Jan 2025 17:41:14 -0600 Subject: [PATCH 519/919] Add solution #97 --- 0097-interleaving-string.js | 39 +++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 40 insertions(+) create mode 100644 0097-interleaving-string.js diff --git a/0097-interleaving-string.js b/0097-interleaving-string.js new file mode 100644 index 00000000..796a96d9 --- /dev/null +++ b/0097-interleaving-string.js @@ -0,0 +1,39 @@ +/** + * 97. Interleaving String + * https://leetcode.com/problems/interleaving-string/ + * Difficulty: Medium + * + * Given strings s1, s2, and s3, find whether s3 is formed by an interleaving of s1 and s2. + * + * An interleaving of two strings s and t is a configuration where s and t are divided into + * n and m substrings respectively, such that: + * - s = s1 + s2 + ... + sn + * - t = t1 + t2 + ... + tm + * - |n - m| <= 1 + * - The interleaving is s1 + t1 + s2 + t2 + s3 + t3 + ... or t1 + s1 + t2 + s2 + t3 + s3 + ... + * + * Note: a + b is the concatenation of strings a and b. + */ + +/** + * @param {string} s1 + * @param {string} s2 + * @param {string} s3 + * @return {boolean} + */ +var isInterleave = function(s1, s2, s3) { + const values = new Array(s1.length + 1).fill().map(() => []); + + if (s1.length + s2.length !== s3.length) { + return false; + } + + for (let i = 0; i <= s1.length; i++) { + for (let j = 0; j <= s2.length; j++) { + values[i][j] = i && values[i - 1][j] && s3[i + j - 1] === s1[i - 1] + || j && values[i][j - 1] && s3[i + j - 1] === s2[j - 1] || !i && !j; + } + } + + return Boolean(values.pop().pop()); +}; diff --git a/README.md b/README.md index 0691b0d0..099834ce 100644 --- a/README.md +++ b/README.md @@ -99,6 +99,7 @@ 94|[Binary Tree Inorder Traversal](./0094-binary-tree-inorder-traversal.js)|Easy| 95|[Unique Binary Search Trees II](./0095-unique-binary-search-trees-ii.js)|Medium| 96|[Unique Binary Search Trees](./0096-unique-binary-search-trees.js)|Medium| +97|[Interleaving String](./0097-interleaving-string.js)|Medium| 98|[Validate Binary Search Tree](./0098-validate-binary-search-tree.js)|Medium| 99|[Recover Binary Search Tree](./0099-recover-binary-search-tree.js)|Medium| 100|[Same Tree](./0100-same-tree.js)|Easy| From a0c4a0fd3fe019b66dd5a2021470558786de3b5d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 23 Jan 2025 17:42:20 -0600 Subject: [PATCH 520/919] Add solution #76 --- 0076-minimum-window-substring.js | 44 ++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 45 insertions(+) create mode 100644 0076-minimum-window-substring.js diff --git a/0076-minimum-window-substring.js b/0076-minimum-window-substring.js new file mode 100644 index 00000000..7879c4ac --- /dev/null +++ b/0076-minimum-window-substring.js @@ -0,0 +1,44 @@ +/** + * 76. Minimum Window Substring + * https://leetcode.com/problems/minimum-window-substring/ + * Difficulty: Hard + * + * Given two strings s and t of lengths m and n respectively, return the minimum window substring + * of s such that every character in t (including duplicates) is included in the window. If there + * is no such substring, return the empty string "". + * + * The testcases will be generated such that the answer is unique. + */ + +/** + * @param {string} s + * @param {string} t + * @return {string} + */ +var minWindow = function(s, t) { + const values = new Array(128).fill(0); + let [start, end] = [-Infinity, Infinity]; + + for (let i = 0; i < t.length; i++) { + values[t.charCodeAt(i)]++; + } + + for (let i = 0, j = 0, total = t.length; i < s.length; i++) { + if (values[s.charCodeAt(i)] > 0) { + total--; + } + values[s.charCodeAt(i)]--; + while (!total) { + if (end - start > i - j) { + [start, end] = [j, i]; + } + values[s.charCodeAt(j)]++; + if (values[s.charCodeAt(j)] > 0) { + total++; + } + j++; + } + } + + return end !== Infinity ? s.slice(start, end + 1) : ''; +}; diff --git a/README.md b/README.md index 099834ce..d344e184 100644 --- a/README.md +++ b/README.md @@ -81,6 +81,7 @@ 73|[Set Matrix Zeroes](./0073-set-matrix-zeroes.js)|Medium| 74|[Search a 2D Matrix](./0074-search-a-2d-matrix.js)|Medium| 75|[Sort Colors](./0075-sort-colors.js)|Medium| +76|[Minimum Window Substring](./0076-minimum-window-substring.js)|Hard| 77|[Combinations](./0077-combinations.js)|Medium| 78|[Subsets](./0078-subsets.js)|Medium| 79|[Word Search](./0079-word-search.js)|Medium| From 65bd4d152ced13e30319aaf94c376f982d274f2e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 23 Jan 2025 17:42:53 -0600 Subject: [PATCH 521/919] Add solution #1267 --- 1267-count-servers-that-communicate.js | 41 ++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 42 insertions(+) create mode 100644 1267-count-servers-that-communicate.js diff --git a/1267-count-servers-that-communicate.js b/1267-count-servers-that-communicate.js new file mode 100644 index 00000000..a972f4f5 --- /dev/null +++ b/1267-count-servers-that-communicate.js @@ -0,0 +1,41 @@ +/** + * 1267. Count Servers that Communicate + * https://leetcode.com/problems/count-servers-that-communicate/ + * Difficulty: Medium + * + * You are given a map of a server center, represented as a m * n integer matrix grid, + * where 1 means that on that cell there is a server and 0 means that it is no server. + * Two servers are said to communicate if they are on the same row or on the same column. + * + * Return the number of servers that communicate with any other server. + */ + +/** + * @param {number[][]} grid + * @return {number} + */ +var countServers = function(grid) { + const rows = new Array(grid.length).fill(0); + const columns = new Array(grid[0].length).fill(0); + + for (let i = 0; i < grid.length; i++) { + for (let j = 0; j < grid[i].length; j++) { + if (grid[i][j]) { + rows[i]++; + columns[j]++; + } + } + } + + let result = 0; + for (let i = 0; i < grid.length; i++) { + for (let j = 0; j < grid[i].length; j++) { + if (!grid[i][j] || (rows[i] < 2 && columns[j] < 2)) { + continue; + } + result++; + } + } + + return result; +}; diff --git a/README.md b/README.md index d344e184..9a0300f4 100644 --- a/README.md +++ b/README.md @@ -337,6 +337,7 @@ 1233|[Remove Sub-Folders from the Filesystem](./1233-remove-sub-folders-from-the-filesystem.js)|Medium| 1249|[Minimum Remove to Make Valid Parentheses](./1249-minimum-remove-to-make-valid-parentheses.js)|Medium| 1252|[Cells with Odd Values in a Matrix](./1252-cells-with-odd-values-in-a-matrix.js)|Easy| +1267|[Count Servers that Communicate](./1267-count-servers-that-communicate.js)|Medium| 1287|[Element Appearing More Than 25% In Sorted Array](./1287-element-appearing-more-than-25-in-sorted-array.js)|Easy| 1290|[Convert Binary Number in a Linked List to Integer](./1290-convert-binary-number-in-a-linked-list-to-integer.js)|Easy| 1291|[Sequential Digits](./1291-sequential-digits.js)|Medium| From f2a332fc1794269d3d304e22a65fedb6dc4f36f5 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 24 Jan 2025 22:15:03 -0600 Subject: [PATCH 522/919] Add solution #748 --- 0748-shortest-completing-word.js | 39 ++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 40 insertions(+) create mode 100644 0748-shortest-completing-word.js diff --git a/0748-shortest-completing-word.js b/0748-shortest-completing-word.js new file mode 100644 index 00000000..8016a758 --- /dev/null +++ b/0748-shortest-completing-word.js @@ -0,0 +1,39 @@ +/** + * 748. Shortest Completing Word + * https://leetcode.com/problems/shortest-completing-word/ + * Difficulty: Easy + * + * Given a string licensePlate and an array of strings words, find the shortest completing + * word in words. + * + * A completing word is a word that contains all the letters in licensePlate. Ignore numbers + * and spaces in licensePlate, and treat letters as case insensitive. If a letter appears more + * than once in licensePlate, then it must appear in the word the same number of times or more. + * + * For example, if licensePlate = "aBc 12c", then it contains letters 'a', 'b' (ignoring case), + * and 'c' twice. Possible completing words are "abccdef", "caaacab", and "cbca". + * + * Return the shortest completing word in words. It is guaranteed an answer exists. If there + * are multiple shortest completing words, return the first one that occurs in words. + */ + +/** + * @param {string} licensePlate + * @param {string[]} words + * @return {string} + */ +var shortestCompletingWord = function(licensePlate, words) { + const license = licensePlate.toLowerCase().replace(/[\d\s]+/g, ''); + const sortedWords = [...words].sort((a, b) => a.length - b.length); + + for (const word of sortedWords) { + let updatedLicense = license; + + for (let i = 0; i < word.length; i++) { + updatedLicense = updatedLicense.replace(word[i], ''); + if (!updatedLicense) { + return word; + } + } + } +}; diff --git a/README.md b/README.md index 9a0300f4..8b501333 100644 --- a/README.md +++ b/README.md @@ -275,6 +275,7 @@ 739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium| 746|[Min Cost Climbing Stairs](./0746-min-cost-climbing-stairs.js)|Easy| 747|[Largest Number At Least Twice of Others](./0747-largest-number-at-least-twice-of-others.js)|Easy| +748|[Shortest Completing Word](./0748-shortest-completing-word.js)|Easy| 762|[Prime Number of Set Bits in Binary Representation](./0762-prime-number-of-set-bits-in-binary-representation.js)|Easy| 784|[Letter Case Permutation](./0784-letter-case-permutation.js)|Medium| 791|[Custom Sort String](./0791-custom-sort-string.js)|Medium| From 02c3f3f666af13c62a242faaa3dc2969533b3612 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 24 Jan 2025 22:15:57 -0600 Subject: [PATCH 523/919] Add solution #745 --- 0745-prefix-and-suffix-search.js | 45 ++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 46 insertions(+) create mode 100644 0745-prefix-and-suffix-search.js diff --git a/0745-prefix-and-suffix-search.js b/0745-prefix-and-suffix-search.js new file mode 100644 index 00000000..c70d377e --- /dev/null +++ b/0745-prefix-and-suffix-search.js @@ -0,0 +1,45 @@ +/** + * 745. Prefix and Suffix Search + * https://leetcode.com/problems/prefix-and-suffix-search/ + * Difficulty: Hard + * + * Design a special dictionary that searches the words in it by a prefix and a suffix. + * + * Implement the WordFilter class: + * - WordFilter(string[] words) Initializes the object with the words in the dictionary. + * - f(string pref, string suff) Returns the index of the word in the dictionary, which + * has the prefix pref and the suffix suff. If there is more than one valid index, + * return the largest of them. If there is no such word in the dictionary, return -1. + */ + +/** + * @param {string[]} words + */ +var WordFilter = function(words) { + this.map = new Map(); + + for (let i = 0; i < words.length; i++) { + let prefix = ''; + + for (let j = 0; j <= words[i].length; j++) { + let suffix = ''; + + for (let k = 0; k <= words[i].length; k++) { + suffix = words[i].slice(k); + this.map.set(prefix + '#' + suffix, i); + } + + prefix += words[i][j]; + } + } +}; + +/** + * @param {string} pref + * @param {string} suff + * @return {number} + */ +WordFilter.prototype.f = function(pref, suff) { + const target = `${pref}#${suff}`; + return this.map.has(target) ? this.map.get(target) : -1; +}; diff --git a/README.md b/README.md index 8b501333..c07626cb 100644 --- a/README.md +++ b/README.md @@ -273,6 +273,7 @@ 733|[Flood Fill](./0733-flood-fill.js)|Easy| 735|[Asteroid Collision](./0735-asteroid-collision.js)|Medium| 739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium| +745|[Prefix and Suffix Search](./0745-prefix-and-suffix-search.js)|Hard| 746|[Min Cost Climbing Stairs](./0746-min-cost-climbing-stairs.js)|Easy| 747|[Largest Number At Least Twice of Others](./0747-largest-number-at-least-twice-of-others.js)|Easy| 748|[Shortest Completing Word](./0748-shortest-completing-word.js)|Easy| From 9aabee1185887926b3a5a532ea7122e44fe59e72 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 24 Jan 2025 22:16:36 -0600 Subject: [PATCH 524/919] Add solution #744 --- ...ind-smallest-letter-greater-than-target.js | 20 +++++++++++++++++++ README.md | 1 + 2 files changed, 21 insertions(+) create mode 100644 0744-find-smallest-letter-greater-than-target.js diff --git a/0744-find-smallest-letter-greater-than-target.js b/0744-find-smallest-letter-greater-than-target.js new file mode 100644 index 00000000..bfd2bfb2 --- /dev/null +++ b/0744-find-smallest-letter-greater-than-target.js @@ -0,0 +1,20 @@ +/** + * 744. Find Smallest Letter Greater Than Target + * https://leetcode.com/problems/find-smallest-letter-greater-than-target/ + * Difficulty: Easy + * + * You are given an array of characters letters that is sorted in non-decreasing order, + * and a character target. There are at least two different characters in letters. + * + * Return the smallest character in letters that is lexicographically greater than target. + * If such a character does not exist, return the first character in letters. + */ + +/** + * @param {character[]} letters + * @param {character} target + * @return {character} + */ +var nextGreatestLetter = function(letters, target) { + return letters.find(l => l > target) || letters[0]; +}; diff --git a/README.md b/README.md index c07626cb..8f5d5167 100644 --- a/README.md +++ b/README.md @@ -273,6 +273,7 @@ 733|[Flood Fill](./0733-flood-fill.js)|Easy| 735|[Asteroid Collision](./0735-asteroid-collision.js)|Medium| 739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium| +744|[Find Smallest Letter Greater Than Target](./0744-find-smallest-letter-greater-than-target.js)|Easy| 745|[Prefix and Suffix Search](./0745-prefix-and-suffix-search.js)|Hard| 746|[Min Cost Climbing Stairs](./0746-min-cost-climbing-stairs.js)|Easy| 747|[Largest Number At Least Twice of Others](./0747-largest-number-at-least-twice-of-others.js)|Easy| From 9eeacd746a46da4ef001ac8a07221c91a8a3e776 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 24 Jan 2025 22:17:29 -0600 Subject: [PATCH 525/919] Add solution #743 --- 0743-network-delay-time.js | 42 ++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 43 insertions(+) create mode 100644 0743-network-delay-time.js diff --git a/0743-network-delay-time.js b/0743-network-delay-time.js new file mode 100644 index 00000000..c47842f1 --- /dev/null +++ b/0743-network-delay-time.js @@ -0,0 +1,42 @@ +/** + * 743. Network Delay Time + * https://leetcode.com/problems/network-delay-time/ + * Difficulty: Medium + * + * You are given a network of n nodes, labeled from 1 to n. You are also given times, a + * list of travel times as directed edges times[i] = (ui, vi, wi), where ui is the source + * node, vi is the target node, and wi is the time it takes for a signal to travel from + * source to target. + * + * We will send a signal from a given node k. Return the minimum time it takes for all + * the n nodes to receive the signal. If it is impossible for all the n nodes to receive + * the signal, return -1. + */ + +/** + * @param {number[][]} times + * @param {number} n + * @param {number} k + * @return {number} + */ +var networkDelayTime = function(times, n, k) { + const time = new Array(n + 1).fill(Infinity); + + time[k] = 0; + + for (let i = 0; i < n; i++) { + for (const [u, v, w] of times) { + if (time[u] === Infinity) continue; + if (time[v] > time[u] + w) { + time[v] = time[u] + w; + } + } + } + + let result = 0; + for (let i = 1; i <= n; i++) { + result = Math.max(result, time[i]); + } + + return result === Infinity ? -1 : result; +}; diff --git a/README.md b/README.md index 8f5d5167..fa238657 100644 --- a/README.md +++ b/README.md @@ -273,6 +273,7 @@ 733|[Flood Fill](./0733-flood-fill.js)|Easy| 735|[Asteroid Collision](./0735-asteroid-collision.js)|Medium| 739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium| +743|[Network Delay Time](./0743-network-delay-time.js)|Medium| 744|[Find Smallest Letter Greater Than Target](./0744-find-smallest-letter-greater-than-target.js)|Easy| 745|[Prefix and Suffix Search](./0745-prefix-and-suffix-search.js)|Hard| 746|[Min Cost Climbing Stairs](./0746-min-cost-climbing-stairs.js)|Easy| From 23116436b01b0708451af066884686d7a9dda1f3 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 24 Jan 2025 22:18:17 -0600 Subject: [PATCH 526/919] Add solution #802 --- 0802-find-eventual-safe-states.js | 36 +++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 37 insertions(+) create mode 100644 0802-find-eventual-safe-states.js diff --git a/0802-find-eventual-safe-states.js b/0802-find-eventual-safe-states.js new file mode 100644 index 00000000..cb911112 --- /dev/null +++ b/0802-find-eventual-safe-states.js @@ -0,0 +1,36 @@ +/** + * 802. Find Eventual Safe States + * https://leetcode.com/problems/find-eventual-safe-states/ + * Difficulty: Medium + * + * 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. + */ + +/** + * @param {number[][]} graph + * @return {number[]} + */ +var eventualSafeNodes = function(graph) { + const nodes = graph.map(() => []); + const totals = graph.map(n => n.length); + const queue = totals.map((v, i) => v ? -1 : i).filter(v => v >= 0); + const result = []; + + graph.forEach((n, i) => n.forEach(v => nodes[v].push(i))); + + while (queue.length) { + const node = queue.shift(); + result.push(node); + nodes[node].forEach(v => !--totals[v] && queue.push(v)); + } + + return result.sort((a, b) => a - b); +}; diff --git a/README.md b/README.md index fa238657..4b898f66 100644 --- a/README.md +++ b/README.md @@ -283,6 +283,7 @@ 784|[Letter Case Permutation](./0784-letter-case-permutation.js)|Medium| 791|[Custom Sort String](./0791-custom-sort-string.js)|Medium| 796|[Rotate String](./0796-rotate-string.js)|Easy| +802|[Find Eventual Safe States](./0802-find-eventual-safe-states.js)|Medium| 804|[Unique Morse Code Words](./0804-unique-morse-code-words.js)|Easy| 819|[Most Common Word](./0819-most-common-word.js)|Easy| 821|[Shortest Distance to a Character](./0821-shortest-distance-to-a-character.js)|Easy| From fc65cfa94d7ffe4c9b3546337a105360ca658c94 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 25 Jan 2025 17:03:09 -0600 Subject: [PATCH 527/919] Add solution #199 --- 0199-binary-tree-right-side-view.js | 27 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 28 insertions(+) create mode 100644 0199-binary-tree-right-side-view.js diff --git a/0199-binary-tree-right-side-view.js b/0199-binary-tree-right-side-view.js new file mode 100644 index 00000000..7362a9bd --- /dev/null +++ b/0199-binary-tree-right-side-view.js @@ -0,0 +1,27 @@ +/** + * 199. Binary Tree Right Side View + * https://leetcode.com/problems/binary-tree-right-side-view/ + * Difficulty: Medium + * + * Given the root of a binary tree, imagine yourself standing on the right side of it, return the + * values of the nodes you can see ordered from top to bottom. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number[]} + */ +var rightSideView = function(root, result = [], depth = 0) { + if (!root) return result; + result[depth] = root.val; + rightSideView(root.left, result, depth + 1); + return rightSideView(root.right, result, depth + 1); +}; diff --git a/README.md b/README.md index 4b898f66..6b862b84 100644 --- a/README.md +++ b/README.md @@ -151,6 +151,7 @@ 190|[Reverse Bits](./0190-reverse-bits.js)|Easy| 191|[Number of 1 Bits](./0191-number-of-1-bits.js)|Easy| 198|[House Robber](./0198-house-robber.js)|Medium| +199|[Binary Tree Right Side View](./0199-binary-tree-right-side-view.js)|Medium| 202|[Happy Number](./0202-happy-number.js)|Easy| 203|[Remove Linked List Elements](./0203-remove-linked-list-elements.js)|Easy| 204|[Count Primes](./0204-count-primes.js)|Medium| From 51bbe5a314e54ab7f5fe5f9b359bd8dab856f245 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 25 Jan 2025 17:03:46 -0600 Subject: [PATCH 528/919] Add solution #200 --- 0200-number-of-islands.js | 43 +++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 44 insertions(+) create mode 100644 0200-number-of-islands.js diff --git a/0200-number-of-islands.js b/0200-number-of-islands.js new file mode 100644 index 00000000..dca02dc0 --- /dev/null +++ b/0200-number-of-islands.js @@ -0,0 +1,43 @@ +/** + * 200. Number of Islands + * https://leetcode.com/problems/number-of-islands/ + * Difficulty: Medium + * + * Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), + * return the number of islands. + * + * An island is surrounded by water and is formed by connecting adjacent lands horizontally + * or vertically. You may assume all four edges of the grid are all surrounded by water. + */ + +/** + * @param {character[][]} grid + * @return {number} + */ +var numIslands = function(grid) { + let count = 0; + + for (let i = 0; i < grid.length; i++) { + for (let j = 0; j < grid[i].length; j++) { + if (grid[i][j] === '1') { + count++; + dfs(i, j); + } + } + } + + function dfs(i, j) { + if (i < 0 || i >= grid.length || j < 0 || j >= grid[i].length || grid[i][j] === '0') { + return; + } + + grid[i][j] = '0'; + + dfs(i + 1, j); + dfs(i - 1, j); + dfs(i, j + 1); + dfs(i, j - 1); + } + + return count; +}; diff --git a/README.md b/README.md index 6b862b84..3eaf32dd 100644 --- a/README.md +++ b/README.md @@ -152,6 +152,7 @@ 191|[Number of 1 Bits](./0191-number-of-1-bits.js)|Easy| 198|[House Robber](./0198-house-robber.js)|Medium| 199|[Binary Tree Right Side View](./0199-binary-tree-right-side-view.js)|Medium| +200|[Number of Islands](./0200-number-of-islands.js)|Medium| 202|[Happy Number](./0202-happy-number.js)|Easy| 203|[Remove Linked List Elements](./0203-remove-linked-list-elements.js)|Easy| 204|[Count Primes](./0204-count-primes.js)|Medium| From 13ee6bb5905303caaa62a3001dd83be86ad4b47f Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 25 Jan 2025 17:04:45 -0600 Subject: [PATCH 529/919] Add solution #703 --- 0703-kth-largest-element-in-a-stream.js | 48 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 49 insertions(+) create mode 100644 0703-kth-largest-element-in-a-stream.js diff --git a/0703-kth-largest-element-in-a-stream.js b/0703-kth-largest-element-in-a-stream.js new file mode 100644 index 00000000..d0b45129 --- /dev/null +++ b/0703-kth-largest-element-in-a-stream.js @@ -0,0 +1,48 @@ +/** + * 703. Kth Largest Element in a Stream + * https://leetcode.com/problems/kth-largest-element-in-a-stream/ + * Difficulty: Easy + * + * You are part of a university admissions office and need to keep track of the kth highest test + * score from applicants in real-time. This helps to determine cut-off marks for interviews and + * admissions dynamically as new applicants submit their scores. + * + * You are tasked to implement a class which, for a given integer k, maintains a stream of test + * scores and continuously returns the kth highest test score after a new score has been submitted. + * More specifically, we are looking for the kth highest score in the sorted list of all scores. + * + * Implement the KthLargest class: + * - KthLargest(int k, int[] nums) Initializes the object with the integer k and the stream of + * test scores nums. + * - int add(int val) Adds a new test score val to the stream and returns the element representing + * the kth largest element in the pool of test scores so far. + */ + +/** + * @param {number} k + * @param {number[]} nums + */ +var KthLargest = function(k, nums) { + this.main = new MinPriorityQueue(); + this.k = k; + + nums.forEach(n => this.main.enqueue(n)); + + while (this.main.size() > k) { + this.main.dequeue().element; + } +}; + +/** + * @param {number} val + * @return {number} + */ +KthLargest.prototype.add = function(val) { + this.main.enqueue(val); + + if (this.main.size() > this.k) { + this.main.dequeue().element; + } + + return this.main.front().element; +}; diff --git a/README.md b/README.md index 3eaf32dd..c4a405ed 100644 --- a/README.md +++ b/README.md @@ -266,6 +266,7 @@ 697|[Degree of an Array](./0697-degree-of-an-array.js)|Easy| 700|[Search in a Binary Search Tree](./0700-search-in-a-binary-search-tree.js)|Easy| 701|[Insert into a Binary Search Tree](./0701-insert-into-a-binary-search-tree.js)|Medium| +703|[Kth Largest Element in a Stream](./0703-kth-largest-element-in-a-stream.js)|Easy| 704|[Binary Search](./0704-binary-search.js)|Easy| 705|[Design HashSet](./0705-design-hashset.js)|Easy| 706|[Design HashMap](./0706-design-hashmap.js)|Easy| From 98acd5ef69e54f0ff6bf88a48f54feed0503e8fe Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 25 Jan 2025 17:05:55 -0600 Subject: [PATCH 530/919] Add solution #2948 --- ...lly-smallest-array-by-swapping-elements.js | 45 +++++++++++++++++++ README.md | 1 + 2 files changed, 46 insertions(+) create mode 100644 2948-make-lexicographically-smallest-array-by-swapping-elements.js diff --git a/2948-make-lexicographically-smallest-array-by-swapping-elements.js b/2948-make-lexicographically-smallest-array-by-swapping-elements.js new file mode 100644 index 00000000..468d6a44 --- /dev/null +++ b/2948-make-lexicographically-smallest-array-by-swapping-elements.js @@ -0,0 +1,45 @@ +/** + * 2948. Make Lexicographically Smallest Array by Swapping Elements + * https://leetcode.com/problems/make-lexicographically-smallest-array-by-swapping-elements/ + * Difficulty: Medium + * + * You are given a 0-indexed array of positive integers nums and a positive integer limit. + * + * In one operation, you can choose any two indices i and j and swap nums[i] and nums[j] + * if |nums[i] - nums[j]| <= limit. + * + * Return the lexicographically smallest array that can be obtained by performing the + * operation any number of times. + * + * An array a is lexicographically smaller than an array b if in the first position where + * a and b differ, array a has an element that is less than the corresponding element in b. + * For example, the array [2,10,3] is lexicographically smaller than the array [10,2,3] + * because they differ at index 0 and 2 < 10. + */ + +/** + * @param {number[]} nums + * @param {number} limit + * @return {number[]} + */ +var lexicographicallySmallestArray = function(nums, limit) { + const keys = new Array(nums.length).fill(0).map((_, i) => i); + keys.sort((i, j) => nums[i] - nums[j]); + + const result = new Array(nums.length).fill(0); + for (let i = 0; i < nums.length;) { + let j = i + 1; + + while (j < nums.length && nums[keys[j]] - nums[keys[j - 1]] <= limit) { + j++; + } + + const keyRange = keys.slice(i, j).sort((a, b) => a - b); + for (let k = 0; k < keyRange.length; k++) { + result[keyRange[k]] = nums[keys[i + k]]; + } + i = j; + } + + return result; +}; diff --git a/README.md b/README.md index c4a405ed..826a8fbc 100644 --- a/README.md +++ b/README.md @@ -502,6 +502,7 @@ 2725|[Interval Cancellation](./2725-interval-cancellation.js)|Easy| 2726|[Calculator with Method Chaining](./2726-calculator-with-method-chaining.js)|Easy| 2727|[Is Object Empty](./2727-is-object-empty.js)|Easy| +2948|[Make Lexicographically Smallest Array by Swapping Elements](./2948-make-lexicographically-smallest-array-by-swapping-elements.js)|Medium| 3042|[Count Prefix and Suffix Pairs I](./3042-count-prefix-and-suffix-pairs-i.js)|Easy| 3110|[Score of a String](./3110-score-of-a-string.js)|Easy| 3223|[Minimum Length of String After Operations](./3223-minimum-length-of-string-after-operations.js)|Medium| From 60f3b620558c4d2e4ed850715fa72360eb2210ae Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 25 Jan 2025 17:07:07 -0600 Subject: [PATCH 531/919] Add solution #87 --- 0087-scramble-string.js | 48 +++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 49 insertions(+) create mode 100644 0087-scramble-string.js diff --git a/0087-scramble-string.js b/0087-scramble-string.js new file mode 100644 index 00000000..8f647350 --- /dev/null +++ b/0087-scramble-string.js @@ -0,0 +1,48 @@ +/** + * 87. Scramble String + * https://leetcode.com/problems/scramble-string/ + * Difficulty: Hard + * + * We can scramble a string s to get a string t using the following algorithm: + * + * 1. If the length of the string is 1, stop. + * 2. If the length of the string is > 1, do the following: + * - Split the string into two non-empty substrings at a random index, i.e., if the string + * is s, divide it to x and y where s = x + y. + * - Randomly decide to swap the two substrings or to keep them in the same order. i.e., + * after this step, s may become s = x + y or s = y + x. + * - Apply step 1 recursively on each of the two substrings x and y. + * + * Given two strings s1 and s2 of the same length, return true if s2 is a scrambled string + * of s1, otherwise, return false. + */ + +/** + * @param {string} s1 + * @param {string} s2 + * @return {boolean} + */ +var isScramble = function(s1, s2) { + const n = s1.length; + const dp = new Array(n).fill().map(() => new Array(n).fill().map(() => new Array(n).fill(null))); + + function dfs(i1, j1, i2) { + if (dp[i1][j1][i2] !== null) { + return dp[i1][j1][i2]; + } + if (i1 == j1) { + return dp[i1][j1][i2] = s1[i1] === s2[i2]; + } + + const j2 = j1 - i1 + i2; + let result = false; + for (let i = i1; i < j1; i++) { + result = result || (dfs(i1, i, i2) && dfs(i + 1, j1, i2 + i - i1 + 1)) + || (dfs(i1, i, j2 - i + i1) && dfs(i + 1, j1, i2)); + } + + return dp[i1][j1][i2] = result; + } + + return dfs(0, n - 1, 0); +}; diff --git a/README.md b/README.md index 826a8fbc..daf699ee 100644 --- a/README.md +++ b/README.md @@ -92,6 +92,7 @@ 84|[Largest Rectangle in Histogram](./0084-largest-rectangle-in-histogram.js)|Hard| 85|[Maximal Rectangle](./0085-maximal-rectangle.js)|Hard| 86|[Partition List](./0086-partition-list.js)|Medium| +87|[Scramble String](./0087-scramble-string.js)|Hard| 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| 89|[Gray Code](./0089-gray-code.js)|Medium| 90|[Subsets II](./0090-subsets-ii.js)|Medium| From c50465f0c64ed120addd0914664b5163fb48d2b7 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 26 Jan 2025 17:07:26 -0600 Subject: [PATCH 532/919] Add solution #103 --- ...inary-tree-zigzag-level-order-traversal.js | 42 +++++++++++++++++++ README.md | 1 + 2 files changed, 43 insertions(+) create mode 100644 0103-binary-tree-zigzag-level-order-traversal.js diff --git a/0103-binary-tree-zigzag-level-order-traversal.js b/0103-binary-tree-zigzag-level-order-traversal.js new file mode 100644 index 00000000..61d4dab8 --- /dev/null +++ b/0103-binary-tree-zigzag-level-order-traversal.js @@ -0,0 +1,42 @@ +/** + * 103. Binary Tree Zigzag Level Order Traversal + * https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/ + * Difficulty: Medium + * + * Given the root of a binary tree, return the zigzag level order traversal of its nodes' values. + * (i.e., from left to right, then right to left for the next level and alternate between). + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number[][]} + */ +var zigzagLevelOrder = function(root) { + const result = []; + + function traverse(node, depth) { + if (node == null) return; + if (result[depth] == null) result[depth] = []; + + if (depth % 2 === 0) { + result[depth].push(node.val); + } else { + result[depth].unshift(node.val); + } + + traverse(node.left, depth + 1); + traverse(node.right, depth + 1); + } + + traverse(root, 0); + + return result; +}; diff --git a/README.md b/README.md index daf699ee..65211ba0 100644 --- a/README.md +++ b/README.md @@ -107,6 +107,7 @@ 100|[Same Tree](./0100-same-tree.js)|Easy| 101|[Symmetric Tree](./0101-symmetric-tree.js)|Easy| 102|[Binary Tree Level Order Traversal](./0102-binary-tree-level-order-traversal.js)|Medium| +103|[Binary Tree Zigzag Level Order Traversal](./0103-binary-tree-zigzag-level-order-traversal.js)|Medium| 104|[Maximum Depth of Binary Tree](./0104-maximum-depth-of-binary-tree.js)|Easy| 108|[Convert Sorted Array to Binary Search Tree](./0108-convert-sorted-array-to-binary-search-tree.js)|Easy| 110|[Balanced Binary Tree](./0110-balanced-binary-tree.js)|Easy| From 39657554ecec2f2d44e0b315d9df32444ac9b1a2 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 26 Jan 2025 17:07:58 -0600 Subject: [PATCH 533/919] Add solution #105 --- ...ree-from-preorder-and-inorder-traversal.js | 34 +++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 0105-construct-binary-tree-from-preorder-and-inorder-traversal.js diff --git a/0105-construct-binary-tree-from-preorder-and-inorder-traversal.js b/0105-construct-binary-tree-from-preorder-and-inorder-traversal.js new file mode 100644 index 00000000..f4651799 --- /dev/null +++ b/0105-construct-binary-tree-from-preorder-and-inorder-traversal.js @@ -0,0 +1,34 @@ +/** + * 105. Construct Binary Tree from Preorder and Inorder Traversal + * https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/ + * Difficulty: Medium + * + * Given two integer arrays preorder and inorder where preorder is the preorder traversal of a + * binary tree and inorder is the inorder traversal of the same tree, construct and return the + * 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) + * } + */ +/** + * @param {number[]} preorder + * @param {number[]} inorder + * @return {TreeNode} + */ +var buildTree = function(preorder, inorder) { + if (!preorder.length || !inorder.length) return null; + + const root = new TreeNode(preorder[0]); + const mid = inorder.indexOf(preorder[0]); + + root.left = buildTree(preorder.slice(1, mid + 1), inorder.slice(0, mid)); + root.right = buildTree(preorder.slice(mid + 1), inorder.slice(mid + 1)); + + return root; +}; diff --git a/README.md b/README.md index 65211ba0..f5adcb02 100644 --- a/README.md +++ b/README.md @@ -109,6 +109,7 @@ 102|[Binary Tree Level Order Traversal](./0102-binary-tree-level-order-traversal.js)|Medium| 103|[Binary Tree Zigzag Level Order Traversal](./0103-binary-tree-zigzag-level-order-traversal.js)|Medium| 104|[Maximum Depth of Binary Tree](./0104-maximum-depth-of-binary-tree.js)|Easy| +105|[Construct Binary Tree from Preorder and Inorder Traversal](./0105-construct-binary-tree-from-preorder-and-inorder-traversal.js)|Medium| 108|[Convert Sorted Array to Binary Search Tree](./0108-convert-sorted-array-to-binary-search-tree.js)|Easy| 110|[Balanced Binary Tree](./0110-balanced-binary-tree.js)|Easy| 111|[Minimum Depth of Binary Tree](./0111-minimum-depth-of-binary-tree.js)|Easy| From 807e0bae1de86747621b6d892aa512054c293751 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 26 Jan 2025 17:10:19 -0600 Subject: [PATCH 534/919] Add solution #91 --- 0091-decode-ways.js | 57 +++++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 58 insertions(+) create mode 100644 0091-decode-ways.js diff --git a/0091-decode-ways.js b/0091-decode-ways.js new file mode 100644 index 00000000..a8ed298c --- /dev/null +++ b/0091-decode-ways.js @@ -0,0 +1,57 @@ +/** + * 91. Decode Ways + * https://leetcode.com/problems/decode-ways/ + * Difficulty: Medium + * + * You have intercepted a secret message encoded as a string of numbers. The message + * is decoded via the following mapping: + * "1" -> 'A' + * "2" -> 'B' + * ... + * "25" -> 'Y' + * "26" -> 'Z' + * + * However, while decoding the message, you realize that there are many different + * ways you can decode the message because some codes are contained in other codes + * ("2" and "5" vs "25"). + * + * For example, "11106" can be decoded into: + * - "AAJF" with the grouping (1, 1, 10, 6) + * - "KJF" with the grouping (11, 10, 6) + * - The grouping (1, 11, 06) is invalid because "06" is not a valid code (only "6" + * is valid). + * + * Note: there may be strings that are impossible to decode. + * + * Given a string s containing only digits, return the number of ways to decode it. + * If the entire string cannot be decoded in any valid way, return 0. + * + * The test cases are generated so that the answer fits in a 32-bit integer. + */ + +/** + * @param {string} s + * @return {number} + */ +var numDecodings = function(s) { + if (s == null || s.length === 0) return 0; + if (s[0] === '0') return 0; + + const group = new Array(s.length + 1).fill(0); + group[0] = 1; + group[1] = 1; + + for (let i = 2; i <= s.length; i++) { + const a = Number(s.slice(i - 1, i)); + if (a >= 1 && a <= 9) { + group[i] += group[i - 1]; + } + + const b = Number(s.slice(i - 2, i)); + if (b >= 10 && b <= 26) { + group[i] += group[i - 2]; + } + } + + return group[s.length]; +}; diff --git a/README.md b/README.md index f5adcb02..c9d979d6 100644 --- a/README.md +++ b/README.md @@ -96,6 +96,7 @@ 88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy| 89|[Gray Code](./0089-gray-code.js)|Medium| 90|[Subsets II](./0090-subsets-ii.js)|Medium| +91|[Decode Ways](./0091-decode-ways.js)|Medium| 92|[Reverse Linked List II](./0092-reverse-linked-list-ii.js)|Medium| 93|[Restore IP Addresses](./0093-restore-ip-addresses.js)|Medium| 94|[Binary Tree Inorder Traversal](./0094-binary-tree-inorder-traversal.js)|Easy| From 692b5fae0e3e7944f43ed89f4212cc3fc87c44e7 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 26 Jan 2025 17:11:36 -0600 Subject: [PATCH 535/919] Add solution #937 --- 0937-reorder-data-in-log-files.js | 40 +++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 41 insertions(+) create mode 100644 0937-reorder-data-in-log-files.js diff --git a/0937-reorder-data-in-log-files.js b/0937-reorder-data-in-log-files.js new file mode 100644 index 00000000..d17033a6 --- /dev/null +++ b/0937-reorder-data-in-log-files.js @@ -0,0 +1,40 @@ +/** + * 937. Reorder Data in Log Files + * https://leetcode.com/problems/reorder-data-in-log-files/ + * Difficulty: Medium + * + * You are given an array of logs. Each log is a space-delimited string of words, + * where the first word is the identifier. + * + * There are two types of logs: + * - Letter-logs: All words (except the identifier) consist of lowercase English + * letters. + * - Digit-logs: All words (except the identifier) consist of digits. + * + * Reorder these logs so that: + * 1. The letter-logs come before all digit-logs. + * 2. The letter-logs are sorted lexicographically by their contents. If their + * contents are the same, then sort them lexicographically by their identifiers. + * 3. The digit-logs maintain their relative ordering. + * + * Return the final order of the logs. + */ + +/** + * @param {string[]} logs + * @return {string[]} + */ +var reorderLogFiles = function(logs) { + const split = logs.map(l => l.split(' ')); + const sortedA = split.filter(l => isNaN(parseInt(l[1], 10))).sort((a, b) => { + return a[1] !== b[1] + ? a[1].localeCompare(b[1]) : a[2] !== b[2] + ? a[2].localeCompare(b[2]) : a.length === b.length + ? a[0].localeCompare(b[0]) : a.length - b.length; + }).map(l => l.join(' ')); + const sortedB = split.filter(l => !isNaN(parseInt(l[1], 10))) + .sort((a, b) => b - a) + .map(l => l.join(' ')); + + return [...sortedA, ...sortedB]; +}; diff --git a/README.md b/README.md index c9d979d6..6cd1af59 100644 --- a/README.md +++ b/README.md @@ -315,6 +315,7 @@ 926|[Flip String to Monotone Increasing](./0926-flip-string-to-monotone-increasing.js)|Medium| 929|[Unique Email Addresses](./0929-unique-email-addresses.js)|Easy| 933|[Number of Recent Calls](./0933-number-of-recent-calls.js)|Easy| +937|[Reorder Data in Log Files](./0937-reorder-data-in-log-files.js)|Medium| 966|[Vowel Spellchecker](./0966-vowel-spellchecker.js)|Medium| 970|[Powerful Integers](./0970-powerful-integers.js)|Easy| 976|[Largest Perimeter Triangle](./0976-largest-perimeter-triangle.js)|Easy| From 5ebdbc7043d1e6ca67494b1707b26be3ea2c261e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 26 Jan 2025 17:12:55 -0600 Subject: [PATCH 536/919] Add solution #2127 --- ...um-employees-to-be-invited-to-a-meeting.js | 56 +++++++++++++++++++ README.md | 1 + 2 files changed, 57 insertions(+) create mode 100644 2127-maximum-employees-to-be-invited-to-a-meeting.js diff --git a/2127-maximum-employees-to-be-invited-to-a-meeting.js b/2127-maximum-employees-to-be-invited-to-a-meeting.js new file mode 100644 index 00000000..717f3216 --- /dev/null +++ b/2127-maximum-employees-to-be-invited-to-a-meeting.js @@ -0,0 +1,56 @@ +/** + * 2127. Maximum Employees to Be Invited to a Meeting + * https://leetcode.com/problems/maximum-employees-to-be-invited-to-a-meeting/ + * Difficulty: Hard + * + * A company is organizing a meeting and has a list of n employees, waiting to be invited. + * They have arranged for a large circular table, capable of seating any number of employees. + * + * The employees are numbered from 0 to n - 1. Each employee has a favorite person and they + * will attend the meeting only if they can sit next to their favorite person at the table. + * The favorite person of an employee is not themself. + * + * Given a 0-indexed integer array favorite, where favorite[i] denotes the favorite person of + * the ith employee, return the maximum number of employees that can be invited to the meeting. + */ + +/** + * @param {number[]} fav + * @return {number} + */ +var maximumInvitations = function(fav) { + const n = fav.length; + const graph = new Array(n).fill().map(() => []); + const seen = new Set(); + let result = 0; + + for (let i = 0; i < n; i++) { + graph[fav[i]].push(i); + } + + for (let i = 0; i < n; i++) { + result += i < fav[i] || fav[fav[i]] != i ? 0 : dfs(i, fav[i]) + dfs(fav[i], i); + } + + for (let i = 0; i < n; i++) { + let j = i; + + if (!seen.has(i)) { + const m = new Map(); + + for (let k = 0; !seen.has(j); k++) { + seen.add(j); + m.set(j, k); + j = fav[j]; + } + + result = Math.max(result, m.size - m.get(j) || 0); + } + } + + function dfs(i, j) { + return graph[i].reduce((max, n) => Math.max(max, n == j ? 0 : dfs(n, j)), 0) + 1; + }; + + return result; +}; diff --git a/README.md b/README.md index 6cd1af59..e983af45 100644 --- a/README.md +++ b/README.md @@ -449,6 +449,7 @@ 2099|[Find Subsequence of Length K With the Largest Sum](./2099-find-subsequence-of-length-k-with-the-largest-sum.js)|Medium| 2114|[Maximum Number of Words Found in Sentences](./2114-maximum-number-of-words-found-in-sentences.js)|Easy| 2116|[Check if a Parentheses String Can Be Valid](./2116-check-if-a-parentheses-string-can-be-valid.js)|Medium| +2127|[Maximum Employees to Be Invited to a Meeting](./2127-maximum-employees-to-be-invited-to-a-meeting.js)|Hard| 2129|[Capitalize the Title](./2129-capitalize-the-title.js)|Easy| 2130|[Maximum Twin Sum of a Linked List](./2130-maximum-twin-sum-of-a-linked-list.js)|Medium| 2154|[Keep Multiplying Found Values by Two](./2154-keep-multiplying-found-values-by-two.js)|Easy| From 75ed1dba740e576cd6c3575cdaf73775b1225fad Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 27 Jan 2025 01:12:48 -0600 Subject: [PATCH 537/919] Add solution #1462 --- 1462-course-schedule-iv.js | 43 ++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 44 insertions(+) create mode 100644 1462-course-schedule-iv.js diff --git a/1462-course-schedule-iv.js b/1462-course-schedule-iv.js new file mode 100644 index 00000000..890149bf --- /dev/null +++ b/1462-course-schedule-iv.js @@ -0,0 +1,43 @@ +/** + * 1462. Course Schedule IV + * https://leetcode.com/problems/course-schedule-iv/ + * Difficulty: Medium + * + * There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. + * You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you + * must take course ai first if you want to take course bi. + * + * - For example, the pair [0, 1] indicates that you have to take course 0 before you can take + * course 1. + * + * Prerequisites can also be indirect. If course a is a prerequisite of course b, and course b + * is a prerequisite of course c, then course a is a prerequisite of course c. + * + * You are also given an array queries where queries[j] = [uj, vj]. For the jth query, you + * should answer whether course uj is a prerequisite of course vj or not. + * + * Return a boolean array answer, where answer[j] is the answer to the jth query. + */ + +/** + * @param {number} numCourses + * @param {number[][]} prerequisites + * @param {number[][]} queries + * @return {boolean[]} + */ +var checkIfPrerequisite = function(numCourses, prerequisites, queries) { + const lookup = new Array(numCourses).fill().map(() => new Array(numCourses).fill(false)); + prerequisites.forEach(([u, v]) => lookup[u][v] = true); + + for (let i = 0; i < numCourses; i++) { + for (let j = 0; j < numCourses; j++) { + for (let k = 0; k < numCourses; k++) { + if (lookup[j][i] && lookup[i][k]) { + lookup[j][k] = true; + } + } + } + } + + return queries.map(([u, v]) => lookup[u][v]); +}; diff --git a/README.md b/README.md index e983af45..31adccd6 100644 --- a/README.md +++ b/README.md @@ -392,6 +392,7 @@ 1455|[Check If a Word Occurs As a Prefix of Any Word in a Sentence](./1455-check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence.js)|Easy| 1456|[Maximum Number of Vowels in a Substring of Given Length](./1456-maximum-number-of-vowels-in-a-substring-of-given-length.js)|Medium| 1460|[Make Two Arrays Equal by Reversing Sub-arrays](./1460-make-two-arrays-equal-by-reversing-sub-arrays.js)|Easy| +1462|[Course Schedule IV](./1462-course-schedule-iv.js)|Medium| 1464|[Maximum Product of Two Elements in an Array](./1464-maximum-product-of-two-elements-in-an-array.js)|Easy| 1466|[Reorder Routes to Make All Paths Lead to the City Zero](./1466-reorder-routes-to-make-all-paths-lead-to-the-city-zero.js)|Medium| 1470|[Shuffle the Array](./1470-shuffle-the-array.js)|Easy| From 90242a9d04b0d028c20bd6477219a3370e56e28c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 27 Jan 2025 01:14:04 -0600 Subject: [PATCH 538/919] Add solution #1366 --- 1366-rank-teams-by-votes.js | 49 +++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 50 insertions(+) create mode 100644 1366-rank-teams-by-votes.js diff --git a/1366-rank-teams-by-votes.js b/1366-rank-teams-by-votes.js new file mode 100644 index 00000000..50d59812 --- /dev/null +++ b/1366-rank-teams-by-votes.js @@ -0,0 +1,49 @@ +/** + * 1366. Rank Teams by Votes + * https://leetcode.com/problems/rank-teams-by-votes/ + * Difficulty: Medium + * + * In a special ranking system, each voter gives a rank from highest to lowest to all + * teams participating in the competition. + * + * The ordering of teams is decided by who received the most position-one votes. If two + * or more teams tie in the first position, we consider the second position to resolve + * the conflict, if they tie again, we continue this process until the ties are resolved. + * If two or more teams are still tied after considering all positions, we rank them + * alphabetically based on their team letter. + * + * You are given an array of strings votes which is the votes of all voters in the ranking + * systems. Sort all teams according to the ranking system described above. + * + * Return a string of all teams sorted by the ranking system. + */ + +/** + * @param {string[]} votes + * @return {string} + */ +var rankTeams = function(votes) { + if (votes.length === 1) { + return votes[0]; + } + + const map = new Map(votes[0].split('').map(s => { + return [s, new Array(votes[0].length).fill(0)]; + })); + + for (vote of votes) { + for (let i = 0; i < vote.length; i++) { + map.get(vote[i])[i]++; + } + } + + const result = votes[0].split('').sort((a, b) => { + for (let i = 0; i < votes[0].length; i++) { + if (map.get(a)[i] > map.get(b)[i]) return -1; + if (map.get(a)[i] < map.get(b)[i]) return 1; + } + return a < b ? -1 : 1; + }); + + return result.join(''); +}; diff --git a/README.md b/README.md index 31adccd6..ac0a6e9e 100644 --- a/README.md +++ b/README.md @@ -373,6 +373,7 @@ 1356|[Sort Integers by The Number of 1 Bits](./1356-sort-integers-by-the-number-of-1-bits.js)|Easy| 1360|[Number of Days Between Two Dates](./1360-number-of-days-between-two-dates.js)|Easy| 1365|[How Many Numbers Are Smaller Than the Current Number](./1365-how-many-numbers-are-smaller-than-the-current-number.js)|Easy| +1366|[Rank Teams by Votes](./1366-rank-teams-by-votes.js)|Medium| 1368|[Minimum Cost to Make at Least One Valid Path in a Grid](./1368-minimum-cost-to-make-at-least-one-valid-path-in-a-grid.js)|Hard| 1374|[Generate a String With Characters That Have Odd Counts](./1374-generate-a-string-with-characters-that-have-odd-counts.js)|Easy| 1380|[Lucky Numbers in a Matrix](./1380-lucky-numbers-in-a-matrix.js)|Easy| From 3ddf277c047619c2173227fec8cfdfab8a804de4 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 27 Jan 2025 01:15:02 -0600 Subject: [PATCH 539/919] Add solution #1535 --- 1535-find-the-winner-of-an-array-game.js | 35 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 36 insertions(+) create mode 100644 1535-find-the-winner-of-an-array-game.js diff --git a/1535-find-the-winner-of-an-array-game.js b/1535-find-the-winner-of-an-array-game.js new file mode 100644 index 00000000..5eccbafb --- /dev/null +++ b/1535-find-the-winner-of-an-array-game.js @@ -0,0 +1,35 @@ +/** + * 1535. Find the Winner of an Array Game + * https://leetcode.com/problems/find-the-winner-of-an-array-game/ + * Difficulty: Medium + * + * Given an integer array arr of distinct integers and an integer k. + * + * A game will be played between the first two elements of the array (i.e. arr[0] and arr[1]). + * In each round of the game, we compare arr[0] with arr[1], the larger integer wins and + * remains at position 0, and the smaller integer moves to the end of the array. The game + * ends when an integer wins k consecutive rounds. + * + * Return the integer which will win the game. + * + * It is guaranteed that there will be a winner of the game. + */ + +/** + * @param {number[]} arr + * @param {number} k + * @return {number} + */ +var getWinner = function(arr, k) { + let result = arr[0]; + + for (let i = 1, count = 0; i < arr.length && count < k; i++) { + if (result < arr[i]) { + result = arr[i]; + count = 0; + } + count++; + } + + return result; +}; diff --git a/README.md b/README.md index ac0a6e9e..593baa25 100644 --- a/README.md +++ b/README.md @@ -411,6 +411,7 @@ 1512|[Number of Good Pairs](./1512-number-of-good-pairs.js)|Easy| 1519|[Number of Nodes in the Sub-Tree With the Same Label](./1519-number-of-nodes-in-the-sub-tree-with-the-same-label.js)|Medium| 1528|[Shuffle String](./1528-shuffle-string.js)|Easy| +1535|[Find the Winner of an Array Game](./1535-find-the-winner-of-an-array-game.js)|Medium| 1550|[Three Consecutive Odds](./1550-three-consecutive-odds.js)|Easy| 1551|[Minimum Operations to Make Array Equal](./1551-minimum-operations-to-make-array-equal.js)|Medium| 1566|[Detect Pattern of Length M Repeated K or More Times](./1566-detect-pattern-of-length-m-repeated-k-or-more-times.js)|Easy| From edd6b7a131b7b89a5378a974d92de7f2a2f6e9d5 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 27 Jan 2025 01:16:00 -0600 Subject: [PATCH 540/919] Add solution #1764 --- ...oncatenating-subarrays-of-another-array.js | 37 +++++++++++++++++++ README.md | 1 + 2 files changed, 38 insertions(+) create mode 100644 1764-form-array-by-concatenating-subarrays-of-another-array.js diff --git a/1764-form-array-by-concatenating-subarrays-of-another-array.js b/1764-form-array-by-concatenating-subarrays-of-another-array.js new file mode 100644 index 00000000..a555dc82 --- /dev/null +++ b/1764-form-array-by-concatenating-subarrays-of-another-array.js @@ -0,0 +1,37 @@ +/** + * 1764. Form Array by Concatenating Subarrays of Another Array + * https://leetcode.com/problems/form-array-by-concatenating-subarrays-of-another-array/ + * Difficulty: Medium + * + * You are given a 2D integer array groups of length n. You are also given an integer array nums. + * + * You are asked if you can choose n disjoint subarrays from the array nums such that the ith + * subarray is equal to groups[i] (0-indexed), and if i > 0, the (i-1)th subarray appears before + * the ith subarray in nums (i.e. the subarrays must be in the same order as groups). + * + * Return true if you can do this task, and false otherwise. + * + * Note that the subarrays are disjoint if and only if there is no index k such that nums[k] + * belongs to more than one subarray. A subarray is a contiguous sequence of elements within + * an array. + */ + +/** + * @param {number[][]} groups + * @param {number[]} nums + * @return {boolean} + */ +var canChoose = function(groups, nums) { + const rows = groups.map(row => ',' + row.join(',') + ','); + const joined = `,${nums.join(',')},`; + + for (let i = 0, offset = 0; i < rows.length; i++) { + offset = joined.indexOf(rows[i], offset); + if (offset === -1) { + return false; + } + offset += rows[i].length - 1; + } + + return true; +}; diff --git a/README.md b/README.md index 593baa25..80c30fec 100644 --- a/README.md +++ b/README.md @@ -425,6 +425,7 @@ 1716|[Calculate Money in Leetcode Bank](./1716-calculate-money-in-leetcode-bank.js)|Easy| 1732|[Find the Highest Altitude](./1732-find-the-highest-altitude.js)|Easy| 1748|[Sum of Unique Elements](./1748-sum-of-unique-elements.js)|Easy| +1764|[Form Array by Concatenating Subarrays of Another Array](./1764-form-array-by-concatenating-subarrays-of-another-array.js)|Medium| 1765|[Map of Highest Peak](./1765-map-of-highest-peak.js)|Medium| 1768|[Merge Strings Alternately](./1768-merge-strings-alternately.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| From 5ca6a58a203b4cf97210f44514455fb540b87d98 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 27 Jan 2025 01:16:52 -0600 Subject: [PATCH 541/919] Add solution #1985 --- ...nd-the-kth-largest-integer-in-the-array.js | 23 +++++++++++++++++++ README.md | 1 + 2 files changed, 24 insertions(+) create mode 100644 1985-find-the-kth-largest-integer-in-the-array.js diff --git a/1985-find-the-kth-largest-integer-in-the-array.js b/1985-find-the-kth-largest-integer-in-the-array.js new file mode 100644 index 00000000..2a5f5be1 --- /dev/null +++ b/1985-find-the-kth-largest-integer-in-the-array.js @@ -0,0 +1,23 @@ +/** + * 1985. Find the Kth Largest Integer in the Array + * https://leetcode.com/problems/find-the-kth-largest-integer-in-the-array/ + * Difficulty: Medium + * + * You are given an array of strings nums and an integer k. Each string in nums + * represents an integer without leading zeros. + * + * Return the string that represents the kth largest integer in nums. + * + * Note: Duplicate numbers should be counted distinctly. For example, if nums is + * ["1","2","2"], "2" is the first largest integer, "2" is the second-largest + * integer, and "1" is the third-largest integer. + */ + +/** + * @param {string[]} nums + * @param {number} k + * @return {string} + */ +var kthLargestNumber = function(nums, k) { + return String(nums.map(BigInt).sort((a, b) => b - a >= 0 ? 1 : -1)[k - 1]); +}; diff --git a/README.md b/README.md index 80c30fec..a9f6cadb 100644 --- a/README.md +++ b/README.md @@ -439,6 +439,7 @@ 1920|[Build Array from Permutation](./1920-build-array-from-permutation.js)|Easy| 1929|[Concatenation of Array](./1929-concatenation-of-array.js)|Easy| 1935|[Maximum Number of Words You Can Type](./1935-maximum-number-of-words-you-can-type.js)|Easy| +1985|[Find the Kth Largest Integer in the Array](./1985-find-the-kth-largest-integer-in-the-array.js)|Medium| 1996|[The Number of Weak Characters in the Game](./1996-the-number-of-weak-characters-in-the-game.js)|Medium| 2000|[Reverse Prefix of Word](./2000-reverse-prefix-of-word.js)|Easy| 2011|[Final Value of Variable After Performing Operations](./2011-final-value-of-variable-after-performing-operations.js)|Easy| From 36000ee579b2ceedc635686fa8e2f8d2a9636c1e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 28 Jan 2025 15:30:15 -0600 Subject: [PATCH 542/919] Add solution #2658 --- 2658-maximum-number-of-fish-in-a-grid.js | 45 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 46 insertions(+) create mode 100644 2658-maximum-number-of-fish-in-a-grid.js diff --git a/2658-maximum-number-of-fish-in-a-grid.js b/2658-maximum-number-of-fish-in-a-grid.js new file mode 100644 index 00000000..5b061c52 --- /dev/null +++ b/2658-maximum-number-of-fish-in-a-grid.js @@ -0,0 +1,45 @@ +/** + * 2658. Maximum Number of Fish in a Grid + * https://leetcode.com/problems/maximum-number-of-fish-in-a-grid/ + * Difficulty: Medium + * + * You are given a 0-indexed 2D matrix grid of size m x n, where (r, c) represents: + * - A land cell if grid[r][c] = 0, or + * - A water cell containing grid[r][c] fish, if grid[r][c] > 0. + * + * A fisher can start at any water cell (r, c) and can do the following operations + * any number of times: + * - Catch all the fish at cell (r, c), or + * - Move to any adjacent water cell. + * + * Return the maximum number of fish the fisher can catch if he chooses his starting + * cell optimally, or 0 if no water cell exists. + * + * An adjacent cell of the cell (r, c), is one of the cells (r, c + 1), (r, c - 1), + * (r + 1, c) or (r - 1, c) if it exists. + */ + +/** + * @param {number[][]} grid + * @return {number} + */ +var findMaxFish = function(grid) { + function traverse(i, j) { + if (i >= grid.length || i < 0 || j >= grid[i].length || j < 0 || grid[i][j] === 0) { + return 0; + } + let count = grid[i][j]; + grid[i][j] = 0; + + count += traverse(i + 1, j); + count += traverse(i, j + 1); + count += traverse(i - 1, j); + count += traverse(i, j - 1); + + return count; + } + + return grid.reduce((result, r, i) => { + return r.reduce((result, c, j) => r[j] > 0 ? Math.max(result, traverse(i, j)) : result, result); + }, 0); +}; diff --git a/README.md b/README.md index a9f6cadb..5325dab5 100644 --- a/README.md +++ b/README.md @@ -493,6 +493,7 @@ 2649|[Nested Array Generator](./2649-nested-array-generator.js)|Medium| 2650|[Design Cancellable Function](./2650-design-cancellable-function.js)|Hard| 2657|[Find the Prefix Common Array of Two Arrays](./2657-find-the-prefix-common-array-of-two-arrays.js)|Medium| +2658|[Maximum Number of Fish in a Grid](./2658-maximum-number-of-fish-in-a-grid.js)|Medium| 2661|[First Completely Painted Row or Column](./2661-first-completely-painted-row-or-column.js)|Medium| 2665|[Counter II](./2665-counter-ii.js)|Easy| 2666|[Allow One Function Call](./2666-allow-one-function-call.js)|Easy| From e5fc7eeb8eb7a6b47f97598749a2534961c644e1 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 28 Jan 2025 15:31:06 -0600 Subject: [PATCH 543/919] Add solution #162 --- 0162-find-peak-element.js | 34 ++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 0162-find-peak-element.js diff --git a/0162-find-peak-element.js b/0162-find-peak-element.js new file mode 100644 index 00000000..89ebb1bb --- /dev/null +++ b/0162-find-peak-element.js @@ -0,0 +1,34 @@ +/** + * 162. Find Peak Element + * https://leetcode.com/problems/find-peak-element/ + * Difficulty: Medium + * + * A peak element is an element that is strictly greater than its neighbors. + * + * Given a 0-indexed integer array nums, find a peak element, and return its index. + * If the array contains multiple peaks, return the index to any of the peaks. + * + * You may imagine that nums[-1] = nums[n] = -∞. In other words, an element is + * always considered to be strictly greater than a neighbor that is outside the array. + * + * You must write an algorithm that runs in O(log n) time. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var findPeakElement = function(nums) { + let left = 0; + + for (let right = nums.length - 1, middle = 0; left < right;) { + middle = Math.floor((right + left) / 2); + if (nums[middle] > nums[middle + 1]) { + right = middle; + } else { + left = middle + 1; + } + } + + return left; +}; diff --git a/README.md b/README.md index 5325dab5..978cd3a1 100644 --- a/README.md +++ b/README.md @@ -145,6 +145,7 @@ 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| 160|[Intersection of Two Linked Lists](./0160-intersection-of-two-linked-lists.js)|Medium| +162|[Find Peak Element](./0162-find-peak-element.js)|Medium| 164|[Maximum Gap](./0164-maximum-gap.js)|Medium| 167|[Two Sum II - Input Array Is Sorted](./0167-two-sum-ii-input-array-is-sorted.js)|Easy| 168|[Excel Sheet Column Title](./0168-excel-sheet-column-title.js)|Easy| From 89bc129f3d1a6011146baf3d15a6bc21bfebfa19 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 28 Jan 2025 15:31:44 -0600 Subject: [PATCH 544/919] Add solution #106 --- ...ee-from-inorder-and-postorder-traversal.js | 35 +++++++++++++++++++ README.md | 1 + 2 files changed, 36 insertions(+) create mode 100644 0106-construct-binary-tree-from-inorder-and-postorder-traversal.js diff --git a/0106-construct-binary-tree-from-inorder-and-postorder-traversal.js b/0106-construct-binary-tree-from-inorder-and-postorder-traversal.js new file mode 100644 index 00000000..9e7f7d26 --- /dev/null +++ b/0106-construct-binary-tree-from-inorder-and-postorder-traversal.js @@ -0,0 +1,35 @@ +/** + * 106. Construct Binary Tree from Inorder and Postorder Traversal + * https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/ + * Difficulty: Medium + * + * Given two integer arrays inorder and postorder where inorder is the inorder traversal of a + * binary tree and postorder is the postorder traversal of the same tree, construct and return + * the 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) + * } + */ +/** + * @param {number[]} inorder + * @param {number[]} postorder + * @return {TreeNode} + */ +var buildTree = function(inorder, postorder) { + if (inorder.length === 0) return null; + + const root = postorder[postorder.length - 1]; + const index = inorder.indexOf(root); + + return { + val: root, + left: buildTree(inorder.slice(0, index), postorder.slice(0, index)), + right: buildTree(inorder.slice(index + 1), postorder.slice(index, -1)) + }; +}; diff --git a/README.md b/README.md index 978cd3a1..547a365a 100644 --- a/README.md +++ b/README.md @@ -111,6 +111,7 @@ 103|[Binary Tree Zigzag Level Order Traversal](./0103-binary-tree-zigzag-level-order-traversal.js)|Medium| 104|[Maximum Depth of Binary Tree](./0104-maximum-depth-of-binary-tree.js)|Easy| 105|[Construct Binary Tree from Preorder and Inorder Traversal](./0105-construct-binary-tree-from-preorder-and-inorder-traversal.js)|Medium| +106|[Construct Binary Tree from Inorder and Postorder Traversal](./0106-construct-binary-tree-from-inorder-and-postorder-traversal.js)|Medium| 108|[Convert Sorted Array to Binary Search Tree](./0108-convert-sorted-array-to-binary-search-tree.js)|Easy| 110|[Balanced Binary Tree](./0110-balanced-binary-tree.js)|Easy| 111|[Minimum Depth of Binary Tree](./0111-minimum-depth-of-binary-tree.js)|Easy| From 7c23999ce8a3781a69766e4f2d7229a7147ccace Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 28 Jan 2025 15:32:12 -0600 Subject: [PATCH 545/919] Add solution #107 --- 0107-binary-tree-level-order-traversal-ii.js | 44 ++++++++++++++++++++ README.md | 1 + 2 files changed, 45 insertions(+) create mode 100644 0107-binary-tree-level-order-traversal-ii.js diff --git a/0107-binary-tree-level-order-traversal-ii.js b/0107-binary-tree-level-order-traversal-ii.js new file mode 100644 index 00000000..e8c6b03c --- /dev/null +++ b/0107-binary-tree-level-order-traversal-ii.js @@ -0,0 +1,44 @@ +/** + * 107. Binary Tree Level Order Traversal II + * https://leetcode.com/problems/binary-tree-level-order-traversal-ii/ + * Difficulty: Medium + * + * Given the root of a binary tree, return the bottom-up level order traversal of its nodes' values. + * (i.e., from left to right, level by level from leaf to root). + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number[][]} + */ +var levelOrderBottom = function(root) { + if (!root) return []; + + const result = []; + const stack = [root]; + + while (stack.length > 0) { + const level = []; + const n = stack.length; + + for (let i = 0; i < n; i++) { + const node = stack.shift(); + level.push(node.val); + + if (node.left) stack.push(node.left); + if (node.right) stack.push(node.right); + } + + result.unshift(level); + } + + return result; +}; diff --git a/README.md b/README.md index 547a365a..c0d45233 100644 --- a/README.md +++ b/README.md @@ -112,6 +112,7 @@ 104|[Maximum Depth of Binary Tree](./0104-maximum-depth-of-binary-tree.js)|Easy| 105|[Construct Binary Tree from Preorder and Inorder Traversal](./0105-construct-binary-tree-from-preorder-and-inorder-traversal.js)|Medium| 106|[Construct Binary Tree from Inorder and Postorder Traversal](./0106-construct-binary-tree-from-inorder-and-postorder-traversal.js)|Medium| +107|[Binary Tree Level Order Traversal II](./0107-binary-tree-level-order-traversal-ii.js)|Medium| 108|[Convert Sorted Array to Binary Search Tree](./0108-convert-sorted-array-to-binary-search-tree.js)|Easy| 110|[Balanced Binary Tree](./0110-balanced-binary-tree.js)|Easy| 111|[Minimum Depth of Binary Tree](./0111-minimum-depth-of-binary-tree.js)|Easy| From 5dfc8f547a367e310b72171716d839150990d4ba Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 28 Jan 2025 15:32:49 -0600 Subject: [PATCH 546/919] Add solution #109 --- ...nvert-sorted-list-to-binary-search-tree.js | 52 +++++++++++++++++++ README.md | 1 + 2 files changed, 53 insertions(+) create mode 100644 0109-convert-sorted-list-to-binary-search-tree.js diff --git a/0109-convert-sorted-list-to-binary-search-tree.js b/0109-convert-sorted-list-to-binary-search-tree.js new file mode 100644 index 00000000..77a993e2 --- /dev/null +++ b/0109-convert-sorted-list-to-binary-search-tree.js @@ -0,0 +1,52 @@ +/** + * 109. Convert Sorted List to Binary Search Tree + * https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/ + * Difficulty: Medium + * + * Given the head of a singly linked list where elements are sorted in ascending order, + * convert it to a height-balanced binary search tree. + */ + +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * 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 {ListNode} head + * @return {TreeNode} + */ +var sortedListToBST = function(head) { + if (!head) return null; + if (!head.next) return new TreeNode(head.val); + + let fast = head; + let slow = head; + let previous = head; + while (fast && fast.next) { + previous = slow; + slow = slow.next; + fast = fast.next.next; + } + + const root = new TreeNode(slow.val); + previous.next = null; + + const newHead = slow.next; + slow.next = null; + + root.left = sortedListToBST(head); + root.right = sortedListToBST(newHead); + + return root; +}; diff --git a/README.md b/README.md index c0d45233..06db2927 100644 --- a/README.md +++ b/README.md @@ -114,6 +114,7 @@ 106|[Construct Binary Tree from Inorder and Postorder Traversal](./0106-construct-binary-tree-from-inorder-and-postorder-traversal.js)|Medium| 107|[Binary Tree Level Order Traversal II](./0107-binary-tree-level-order-traversal-ii.js)|Medium| 108|[Convert Sorted Array to Binary Search Tree](./0108-convert-sorted-array-to-binary-search-tree.js)|Easy| +109|[Convert Sorted List to Binary Search Tree](./0109-convert-sorted-list-to-binary-search-tree.js)|Medium| 110|[Balanced Binary Tree](./0110-balanced-binary-tree.js)|Easy| 111|[Minimum Depth of Binary Tree](./0111-minimum-depth-of-binary-tree.js)|Easy| 112|[Path Sum](./0112-path-sum.js)|Easy| From ab0ac82ea8e58f80bbe938826548358b06109fb9 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 29 Jan 2025 16:43:25 -0600 Subject: [PATCH 547/919] Add solution #684 --- 0684-redundant-connection.js | 46 ++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 47 insertions(+) create mode 100644 0684-redundant-connection.js diff --git a/0684-redundant-connection.js b/0684-redundant-connection.js new file mode 100644 index 00000000..f5cb872c --- /dev/null +++ b/0684-redundant-connection.js @@ -0,0 +1,46 @@ +/** + * 684. Redundant Connection + * https://leetcode.com/problems/redundant-connection/ + * Difficulty: Medium + * + * In this problem, a tree is an undirected graph that is connected and has no cycles. + * + * You are given a graph that started as a tree with n nodes labeled from 1 to n, with + * one additional edge added. The added edge has two different vertices chosen from 1 + * to n, and was not an edge that already existed. The graph is represented as an array + * edges of length n where edges[i] = [ai, bi] indicates that there is an edge between + * nodes ai and bi in the graph. + * + * Return an edge that can be removed so that the resulting graph is a tree of n nodes. + * If there are multiple answers, return the answer that occurs last in the input. + */ + +/** + * @param {number[][]} edges + * @return {number[]} + */ +var findRedundantConnection = function(edges) { + const adjacency = new Map(); + + function traverse(node, target, prev) { + if (node === target) { + return true; + } + for (const nextNode of adjacency.get(node)) { + if (nextNode !== prev && traverse(nextNode, target, node)) { + return true; + } + } + return false; + } + + for (const edge of edges) { + const [a, b] = edge; + adjacency.set(a, !adjacency.has(a) ? [b] : [...adjacency.get(a), b]); + adjacency.set(b, !adjacency.has(b) ? [a] : [...adjacency.get(b), a]); + + if (traverse(b, a, a)) { + return [a, b]; + } + } +}; diff --git a/README.md b/README.md index 06db2927..2a5f7a33 100644 --- a/README.md +++ b/README.md @@ -269,6 +269,7 @@ 649|[Dota2 Senate](./0649-dota2-senate.js)|Medium| 653|[Two Sum IV - Input is a BST](./0653-two-sum-iv-input-is-a-bst.js)|Easy| 680|[Valid Palindrome II](./0680-valid-palindrome-ii.js)|Easy| +684|[Redundant Connection](./0684-redundant-connection.js)|Medium| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| 695|[Max Area of Island](./0695-max-area-of-island.js)|Medium| 697|[Degree of an Array](./0697-degree-of-an-array.js)|Easy| From 7e39ae993363d8d5856d3d9794f8b56f1fcb2772 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 29 Jan 2025 16:44:05 -0600 Subject: [PATCH 548/919] Add solution #117 --- ...ing-next-right-pointers-in-each-node-ii.js | 49 +++++++++++++++++++ README.md | 1 + 2 files changed, 50 insertions(+) create mode 100644 0117-populating-next-right-pointers-in-each-node-ii.js diff --git a/0117-populating-next-right-pointers-in-each-node-ii.js b/0117-populating-next-right-pointers-in-each-node-ii.js new file mode 100644 index 00000000..31bfe6e2 --- /dev/null +++ b/0117-populating-next-right-pointers-in-each-node-ii.js @@ -0,0 +1,49 @@ +/** + * 117. Populating Next Right Pointers in Each Node II + * https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/ + * Difficulty: Medium + * + * Given a binary tree, populate each next pointer to point to its next right node. + * If there is no next right node, the next pointer should be set to NULL. + * + * Initially, all next pointers are set to NULL. + */ + +/** + * // Definition for a _Node. + * function _Node(val, left, right, next) { + * this.val = val === undefined ? null : val; + * this.left = left === undefined ? null : left; + * this.right = right === undefined ? null : right; + * this.next = next === undefined ? null : next; + * }; + */ + +/** + * @param {_Node} root + * @return {_Node} + */ +var connect = function(root) { + if (root === null) return root; + + const depth = 0; + const stack = [[root, depth]]; + + while (stack.length) { + const [node, depth] = stack.shift(); + if (stack.length) { + const [nextNode, nextDepth] = stack[0]; + if (depth === nextDepth) { + node.next = nextNode; + } + } + if (node.left) { + stack.push([node.left, depth + 1]); + } + if (node.right) { + stack.push([node.right, depth + 1]); + } + } + + return root; +}; diff --git a/README.md b/README.md index 2a5f7a33..136e3358 100644 --- a/README.md +++ b/README.md @@ -122,6 +122,7 @@ 114|[Flatten Binary Tree to Linked List](./0114-flatten-binary-tree-to-linked-list.js)|Medium| 115|[Distinct Subsequences](./0115-distinct-subsequences.js)|Hard| 116|[Populating Next Right Pointers in Each Node](./0116-populating-next-right-pointers-in-each-node.js)|Medium| +117|[Populating Next Right Pointers in Each Node II](./0117-populating-next-right-pointers-in-each-node-ii.js)|Medium| 118|[Pascal's Triangle](./0118-pascals-triangle.js)|Easy| 119|[Pascal's Triangle II](./0119-pascals-triangle-ii.js)|Easy| 120|[Triangle](./0120-triangle.js)|Medium| From 9be3b14b42f7db73e132194242111eed22fc16f8 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 29 Jan 2025 16:45:00 -0600 Subject: [PATCH 549/919] Add solution #165 --- 0165-compare-version-numbers.js | 35 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 36 insertions(+) create mode 100644 0165-compare-version-numbers.js diff --git a/0165-compare-version-numbers.js b/0165-compare-version-numbers.js new file mode 100644 index 00000000..615125f6 --- /dev/null +++ b/0165-compare-version-numbers.js @@ -0,0 +1,35 @@ +/** + * 165. Compare Version Numbers + * https://leetcode.com/problems/compare-version-numbers/ + * Difficulty: Medium + * + * Given two version strings, version1 and version2, compare them. A version string + * consists of revisions separated by dots '.'. The value of the revision is its + * integer conversion ignoring leading zeros. + * + * To compare version strings, compare their revision values in left-to-right order. + * If one of the version strings has fewer revisions, treat the missing revision + * values as 0. + * + * Return the following: + * - If version1 < version2, return -1. + * - If version1 > version2, return 1. + * - Otherwise, return 0. + */ + +/** + * @param {string} version1 + * @param {string} version2 + * @return {number} + */ +var compareVersion = function(version1, version2) { + const [v1, v2] = [version1.split(/\./), version2.split(/\./)]; + + while (v1.length || v2.length) { + const [a, b] = [v1.shift(), v2.shift()].map(s => Number(s ?? 0)); + if (a < b) return -1; + if (a > b) return 1; + } + + return 0; +}; diff --git a/README.md b/README.md index 136e3358..7b6c1ac8 100644 --- a/README.md +++ b/README.md @@ -151,6 +151,7 @@ 160|[Intersection of Two Linked Lists](./0160-intersection-of-two-linked-lists.js)|Medium| 162|[Find Peak Element](./0162-find-peak-element.js)|Medium| 164|[Maximum Gap](./0164-maximum-gap.js)|Medium| +165|[Compare Version Numbers](./0165-compare-version-numbers.js)|Medium| 167|[Two Sum II - Input Array Is Sorted](./0167-two-sum-ii-input-array-is-sorted.js)|Easy| 168|[Excel Sheet Column Title](./0168-excel-sheet-column-title.js)|Easy| 169|[Majority Element](./0169-majority-element.js)|Easy| From c5040892d68b9e3d2e1f8bb31b4a0c77cca38604 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 29 Jan 2025 16:45:45 -0600 Subject: [PATCH 550/919] Add solution #166 --- 0166-fraction-to-recurring-decimal.js | 51 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 52 insertions(+) create mode 100644 0166-fraction-to-recurring-decimal.js diff --git a/0166-fraction-to-recurring-decimal.js b/0166-fraction-to-recurring-decimal.js new file mode 100644 index 00000000..a135effc --- /dev/null +++ b/0166-fraction-to-recurring-decimal.js @@ -0,0 +1,51 @@ +/** + * 166. Fraction to Recurring Decimal + * https://leetcode.com/problems/fraction-to-recurring-decimal/ + * Difficulty: Medium + * + * Given two integers representing the numerator and denominator of a fraction, return + * the fraction in string format. + * + * If the fractional part is repeating, enclose the repeating part in parentheses. + * + * If multiple answers are possible, return any of them. + * + * It is guaranteed that the length of the answer string is less than 104 for all the + * given inputs. + */ + +/** + * @param {number} numerator + * @param {number} denominator + * @return {string} + */ +var fractionToDecimal = function(numerator, denominator) { + if (numerator === 0) return '0'; + + const map = new Map(); + let result = ''; + + if (Math.sign(numerator) !== Math.sign(denominator)) { + result += '-'; + } + + numerator = Math.abs(numerator); + denominator = Math.abs(denominator); + result += Math.floor(numerator / denominator); + + let remainder = numerator % denominator; + while (remainder) { + result = result.indexOf('.') === -1 ? `${result}.` : result; + if (map.has(remainder)) { + const index = map.get(remainder); + result = `${result.slice(0, index)}(${result.slice(index)})`; + break; + } + map.set(remainder, result.length); + remainder *= 10; + result += Math.floor(remainder / denominator); + remainder %= denominator; + } + + return result; +}; diff --git a/README.md b/README.md index 7b6c1ac8..76e03d51 100644 --- a/README.md +++ b/README.md @@ -152,6 +152,7 @@ 162|[Find Peak Element](./0162-find-peak-element.js)|Medium| 164|[Maximum Gap](./0164-maximum-gap.js)|Medium| 165|[Compare Version Numbers](./0165-compare-version-numbers.js)|Medium| +166|[Fraction to Recurring Decimal](./0166-fraction-to-recurring-decimal.js)|Medium| 167|[Two Sum II - Input Array Is Sorted](./0167-two-sum-ii-input-array-is-sorted.js)|Easy| 168|[Excel Sheet Column Title](./0168-excel-sheet-column-title.js)|Easy| 169|[Majority Element](./0169-majority-element.js)|Easy| From 13878aed002a1d5baf98bba6e08493c030264d40 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 29 Jan 2025 16:46:27 -0600 Subject: [PATCH 551/919] Add solution #1161 --- 1161-maximum-level-sum-of-a-binary-tree.js | 42 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 43 insertions(+) create mode 100644 1161-maximum-level-sum-of-a-binary-tree.js diff --git a/1161-maximum-level-sum-of-a-binary-tree.js b/1161-maximum-level-sum-of-a-binary-tree.js new file mode 100644 index 00000000..fef02031 --- /dev/null +++ b/1161-maximum-level-sum-of-a-binary-tree.js @@ -0,0 +1,42 @@ +/** + * 1161. Maximum Level Sum of a Binary Tree + * https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree/ + * Difficulty: Medium + * + * Given the root of a binary tree, the level of its root is 1, the level of its + * children is 2, and so on. + * + * Return the smallest level x such that the sum of all the values of nodes at + * level x is maximal. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number} + */ +var maxLevelSum = function(root) { + const sums = [-Infinity]; + + traverse(root, 1); + + return sums.indexOf(Math.max(...sums)); + + function traverse(node, depth) { + if (!node) return; + if (sums[depth] === undefined) { + sums.push(node.val); + } else { + sums[depth] += node.val; + } + traverse(node.left, depth + 1); + traverse(node.right, depth + 1); + } +}; diff --git a/README.md b/README.md index 76e03d51..853526d4 100644 --- a/README.md +++ b/README.md @@ -348,6 +348,7 @@ 1103|[Distribute Candies to People](./1103-distribute-candies-to-people.js)|Easy| 1108|[Defanging an IP Address](./1108-defanging-an-ip-address.js)|Easy| 1122|[Relative Sort Array](./1122-relative-sort-array.js)|Easy| +1161|[Maximum Level Sum of a Binary Tree](./1161-maximum-level-sum-of-a-binary-tree.js)|Medium| 1189|[Maximum Number of Balloons](./1189-maximum-number-of-balloons.js)|Easy| 1200|[Minimum Absolute Difference](./1200-minimum-absolute-difference.js)|Easy| 1206|[Design Skiplist](./1206-design-skiplist.js)|Hard| From 1c754a6798e88abb75cba669ab4f7fa8e316cd8c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 30 Jan 2025 17:47:25 -0600 Subject: [PATCH 552/919] Add solution #2493 --- ...nodes-into-the-maximum-number-of-groups.js | 61 +++++++++++++++++++ README.md | 1 + 2 files changed, 62 insertions(+) create mode 100644 2493-divide-nodes-into-the-maximum-number-of-groups.js diff --git a/2493-divide-nodes-into-the-maximum-number-of-groups.js b/2493-divide-nodes-into-the-maximum-number-of-groups.js new file mode 100644 index 00000000..cb490cf1 --- /dev/null +++ b/2493-divide-nodes-into-the-maximum-number-of-groups.js @@ -0,0 +1,61 @@ +/** + * 2493. Divide Nodes Into the Maximum Number of Groups + * https://leetcode.com/problems/divide-nodes-into-the-maximum-number-of-groups/ + * Difficulty: Hard + * + * You are given a positive integer n representing the number of nodes in an undirected graph. + * The nodes are labeled from 1 to n. + * + * You are also given a 2D integer array edges, where edges[i] = [ai, bi] indicates that there + * is a bidirectional edge between nodes ai and bi. Notice that the given graph may be disconnected. + * + * Divide the nodes of the graph into m groups (1-indexed) such that: + * - Each node in the graph belongs to exactly one group. + * - For every pair of nodes in the graph that are connected by an edge [ai, bi], if ai belongs to + * the group with index x, and bi belongs to the group with index y, then |y - x| = 1. + * + * Return the maximum number of groups (i.e., maximum m) into which you can divide the nodes. + * Return -1 if it is impossible to group the nodes with the given conditions. + */ + +/** + * @param {number} n + * @param {number[][]} edges + * @return {number} + */ +var magnificentSets = function(n, edges) { + const graph = new Array(n).fill().map(() => []); + for (const [i, j] of edges) { + graph[i - 1].push(j - 1); + graph[j - 1].push(i - 1); + } + + const result = new Array(n).fill(0); + for (let i = 0; i < n; i++) { + const groups = new Array(n).fill(0); + const queue = [i]; + let max = 1; + let root = i; + + groups[i] = 1; + + while (queue.length) { + const key = queue.shift(); + root = Math.min(root, key); + + for (const node of graph[key]) { + if (groups[node] === 0) { + groups[node] = groups[key] + 1; + max = Math.max(max, groups[node]); + queue.push(node); + } else if (Math.abs(groups[node] - groups[key]) !== 1) { + return -1; + } + } + } + + result[root] = Math.max(result[root], max); + } + + return result.reduce((a, b) => a + b); +}; diff --git a/README.md b/README.md index 853526d4..1ec7dda1 100644 --- a/README.md +++ b/README.md @@ -481,6 +481,7 @@ 2469|[Convert the Temperature](./2469-convert-the-temperature.js)|Easy| 2482|[Difference Between Ones and Zeros in Row and Column](./2482-difference-between-ones-and-zeros-in-row-and-column.js)|Medium| 2490|[Circular Sentence](./2490-circular-sentence.js)|Easy| +2493|[Divide Nodes Into the Maximum Number of Groups](./2493-divide-nodes-into-the-maximum-number-of-groups.js)|Hard| 2529|[Maximum Count of Positive Integer and Negative Integer](./2529-maximum-count-of-positive-integer-and-negative-integer.js)|Easy| 2535|[Difference Between Element Sum and Digit Sum of an Array](./2535-difference-between-element-sum-and-digit-sum-of-an-array.js)|Easy| 2618|[Check if Object Instance of Class](./2618-check-if-object-instance-of-class.js)|Medium| From 469177abb9a723df5fbde8a9dd5f9652cd4f1982 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 30 Jan 2025 17:48:11 -0600 Subject: [PATCH 553/919] Add solution #124 --- 0124-binary-tree-maximum-path-sum.js | 41 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 42 insertions(+) create mode 100644 0124-binary-tree-maximum-path-sum.js diff --git a/0124-binary-tree-maximum-path-sum.js b/0124-binary-tree-maximum-path-sum.js new file mode 100644 index 00000000..da161e3f --- /dev/null +++ b/0124-binary-tree-maximum-path-sum.js @@ -0,0 +1,41 @@ +/** + * 124. Binary Tree Maximum Path Sum + * https://leetcode.com/problems/binary-tree-maximum-path-sum/ + * Difficulty: Hard + * + * A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the + * sequence has an edge connecting them. A node can only appear in the sequence at most + * once. Note that the path does not need to pass through the root. + * + * The path sum of a path is the sum of the node's values in the path. + * + * Given the root of a binary tree, return the maximum path sum of any non-empty path. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number} + */ +var maxPathSum = function(root) { + let result = -Infinity; + + function traverse(node) { + if (!node) return 0; + const leftValue = Math.max(traverse(node.left), 0); + const rightValue = Math.max(traverse(node.right), 0); + result = Math.max(result, node.val + leftValue + rightValue); + return node.val + Math.max(leftValue, rightValue); + } + + traverse(root); + + return result; +}; diff --git a/README.md b/README.md index 1ec7dda1..b1a13dd8 100644 --- a/README.md +++ b/README.md @@ -127,6 +127,7 @@ 119|[Pascal's Triangle II](./0119-pascals-triangle-ii.js)|Easy| 120|[Triangle](./0120-triangle.js)|Medium| 121|[Best Time to Buy and Sell Stock](./0121-best-time-to-buy-and-sell-stock.js)|Easy| +124|[Binary Tree Maximum Path Sum](./0124-binary-tree-maximum-path-sum.js)|Hard| 125|[Valid Palindrome](./0125-valid-palindrome.js)|Easy| 128|[Longest Consecutive Sequence](./0128-longest-consecutive-sequence.js)|Medium| 131|[Palindrome Partitioning](./0131-palindrome-partitioning.js)|Medium| From 7e2df844094433a7bebfbdc39e1b0acd8694ecbf Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 30 Jan 2025 17:49:08 -0600 Subject: [PATCH 554/919] Add solution #155 --- 0155-min-stack.js | 50 +++++++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 51 insertions(+) create mode 100644 0155-min-stack.js diff --git a/0155-min-stack.js b/0155-min-stack.js new file mode 100644 index 00000000..ea010b42 --- /dev/null +++ b/0155-min-stack.js @@ -0,0 +1,50 @@ +/** + * 155. Min Stack + * https://leetcode.com/problems/min-stack/ + * Difficulty: Medium + * + * Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. + * + * Implement the MinStack class: + * - MinStack() initializes the stack object. + * - void push(int val) pushes the element val onto the stack. + * - void pop() removes the element on the top of the stack. + * - int top() gets the top element of the stack. + * - int getMin() retrieves the minimum element in the stack. + * + * You must implement a solution with O(1) time complexity for each function. + */ + + +var MinStack = function() { + this.stack = []; +}; + +/** + * @param {number} val + * @return {void} + */ +MinStack.prototype.push = function(val) { + this.stack.push({ val, min: this.stack.length ? Math.min(val, this.getMin()) : val }); +}; + +/** + * @return {void} + */ +MinStack.prototype.pop = function() { + this.stack.pop(); +}; + +/** + * @return {number} + */ +MinStack.prototype.top = function() { + return this.stack[this.stack.length - 1].val; +}; + +/** + * @return {number} + */ +MinStack.prototype.getMin = function() { + return this.stack.length ? this.stack[this.stack.length - 1].min : 0; +}; diff --git a/README.md b/README.md index b1a13dd8..588727d7 100644 --- a/README.md +++ b/README.md @@ -149,6 +149,7 @@ 149|[Max Points on a Line](./0149-max-points-on-a-line.js)|Hard| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| +155|[Min Stack](./0155-min-stack.js)|Medium| 160|[Intersection of Two Linked Lists](./0160-intersection-of-two-linked-lists.js)|Medium| 162|[Find Peak Element](./0162-find-peak-element.js)|Medium| 164|[Maximum Gap](./0164-maximum-gap.js)|Medium| From 830b5cbf7f4e99c5d5d50f4b14410a53553f8a42 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 30 Jan 2025 17:49:57 -0600 Subject: [PATCH 555/919] Add solution #122 --- 0122-best-time-to-buy-and-sell-stock-ii.js | 24 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 0122-best-time-to-buy-and-sell-stock-ii.js diff --git a/0122-best-time-to-buy-and-sell-stock-ii.js b/0122-best-time-to-buy-and-sell-stock-ii.js new file mode 100644 index 00000000..5f963d71 --- /dev/null +++ b/0122-best-time-to-buy-and-sell-stock-ii.js @@ -0,0 +1,24 @@ +/** + * 122. Best Time to Buy and Sell Stock II + * https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/ + * Difficulty: Medium + * + * You are given an integer array prices where prices[i] is the price of a given + * stock on the ith day. + * + * On each day, you may decide to buy and/or sell the stock. You can only hold at + * most one share of the stock at any time. However, you can buy it then immediately + * sell it on the same day. + * + * Find and return the maximum profit you can achieve. + */ + +/** + * @param {number[]} prices + * @return {number} + */ +var maxProfit = function(prices) { + return prices.reduce((result, price, i) => { + return prices[i - 1] < price ? result + (price - prices[i - 1]) : result; + }, 0); +}; diff --git a/README.md b/README.md index 588727d7..3f480b10 100644 --- a/README.md +++ b/README.md @@ -127,6 +127,7 @@ 119|[Pascal's Triangle II](./0119-pascals-triangle-ii.js)|Easy| 120|[Triangle](./0120-triangle.js)|Medium| 121|[Best Time to Buy and Sell Stock](./0121-best-time-to-buy-and-sell-stock.js)|Easy| +122|[Best Time to Buy and Sell Stock II](./0122-best-time-to-buy-and-sell-stock-ii.js)|Medium| 124|[Binary Tree Maximum Path Sum](./0124-binary-tree-maximum-path-sum.js)|Hard| 125|[Valid Palindrome](./0125-valid-palindrome.js)|Easy| 128|[Longest Consecutive Sequence](./0128-longest-consecutive-sequence.js)|Medium| From b3fd60ca0678fb22db47763cdd1c1685ce8a3ad2 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 30 Jan 2025 17:50:41 -0600 Subject: [PATCH 556/919] Add solution #123 --- 0123-best-time-to-buy-and-sell-stock-iii.js | 30 +++++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 0123-best-time-to-buy-and-sell-stock-iii.js diff --git a/0123-best-time-to-buy-and-sell-stock-iii.js b/0123-best-time-to-buy-and-sell-stock-iii.js new file mode 100644 index 00000000..66f5973a --- /dev/null +++ b/0123-best-time-to-buy-and-sell-stock-iii.js @@ -0,0 +1,30 @@ +/** + * 123. Best Time to Buy and Sell Stock III + * https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/ + * Difficulty: Hard + * + * You are given an array prices where prices[i] is the price of a given stock on the ith day. + * + * Find the maximum profit you can achieve. You may complete at most two transactions. + * + * Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the + * stock before you buy again). + */ + +/** + * @param {number[]} prices + * @return {number} + */ +var maxProfit = function(prices) { + const costs = [prices[0]]; + const profits = new Array(prices.length).fill(0); + + for (let i = 0; i < 2; i++) { + for (let j = 1; j < prices.length; j++) { + costs[j] = Math.min(costs[j - 1], prices[j] - profits[j]); + profits[j] = Math.max(profits[j - 1], prices[j] - costs[j]); + } + } + + return profits[profits.length - 1]; +}; diff --git a/README.md b/README.md index 3f480b10..a7a27c2f 100644 --- a/README.md +++ b/README.md @@ -128,6 +128,7 @@ 120|[Triangle](./0120-triangle.js)|Medium| 121|[Best Time to Buy and Sell Stock](./0121-best-time-to-buy-and-sell-stock.js)|Easy| 122|[Best Time to Buy and Sell Stock II](./0122-best-time-to-buy-and-sell-stock-ii.js)|Medium| +123|[Best Time to Buy and Sell Stock III](./0123-best-time-to-buy-and-sell-stock-iii.js)|Hard| 124|[Binary Tree Maximum Path Sum](./0124-binary-tree-maximum-path-sum.js)|Hard| 125|[Valid Palindrome](./0125-valid-palindrome.js)|Easy| 128|[Longest Consecutive Sequence](./0128-longest-consecutive-sequence.js)|Medium| From 450ae83d006753786e52f680888ba410e0ef8a49 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 31 Jan 2025 17:25:12 -0600 Subject: [PATCH 557/919] Add solution #127 --- 0127-word-ladder.js | 52 +++++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 53 insertions(+) create mode 100644 0127-word-ladder.js diff --git a/0127-word-ladder.js b/0127-word-ladder.js new file mode 100644 index 00000000..2edf0e0d --- /dev/null +++ b/0127-word-ladder.js @@ -0,0 +1,52 @@ +/** + * 127. Word Ladder + * https://leetcode.com/problems/word-ladder/ + * Difficulty: Hard + * + * A transformation sequence from word beginWord to word endWord using a dictionary + * wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that: + * - Every adjacent pair of words differs by a single letter. + * - Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to + * be in wordList. + * - sk == endWord + * Given two words, beginWord and endWord, and a dictionary wordList, return the + * number of words in the shortest transformation sequence from beginWord to + * endWord, or 0 if no such sequence exists. + */ + +/** + * @param {string} beginWord + * @param {string} endWord + * @param {string[]} wordList + * @return {number} + */ +var ladderLength = function(beginWord, endWord, wordList) { + const set = new Set(wordList); + let queue = [beginWord]; + let count = 1; + + while (queue.length) { + const group = []; + + for (const word of queue) { + if (word === endWord) { + return count; + } + + for (let i = 0; i < word.length; i++) { + for (let j = 0; j < 26; j++) { + const str = word.slice(0, i) + String.fromCharCode(j + 97) + word.slice(i + 1); + if (set.has(str)) { + group.push(str); + set.delete(str); + } + } + } + } + + queue = group; + count++; + } + + return 0; +}; diff --git a/README.md b/README.md index a7a27c2f..a93c937b 100644 --- a/README.md +++ b/README.md @@ -131,6 +131,7 @@ 123|[Best Time to Buy and Sell Stock III](./0123-best-time-to-buy-and-sell-stock-iii.js)|Hard| 124|[Binary Tree Maximum Path Sum](./0124-binary-tree-maximum-path-sum.js)|Hard| 125|[Valid Palindrome](./0125-valid-palindrome.js)|Easy| +127|[Word Ladder](./0127-word-ladder.js)|Hard| 128|[Longest Consecutive Sequence](./0128-longest-consecutive-sequence.js)|Medium| 131|[Palindrome Partitioning](./0131-palindrome-partitioning.js)|Medium| 133|[Clone Graph](./0133-clone-graph.js)|Medium| From aa99a464ec60e1b7bdd0f4f9af6cf1979c8f65d5 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 31 Jan 2025 17:25:57 -0600 Subject: [PATCH 558/919] Add solution #129 --- 0129-sum-root-to-leaf-numbers.js | 43 ++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 44 insertions(+) create mode 100644 0129-sum-root-to-leaf-numbers.js diff --git a/0129-sum-root-to-leaf-numbers.js b/0129-sum-root-to-leaf-numbers.js new file mode 100644 index 00000000..48a1f1f3 --- /dev/null +++ b/0129-sum-root-to-leaf-numbers.js @@ -0,0 +1,43 @@ +/** + * 129. Sum Root to Leaf Numbers + * https://leetcode.com/problems/sum-root-to-leaf-numbers/ + * Difficulty: Medium + * + * You are given the root of a binary tree containing digits from 0 to 9 only. + * + * Each root-to-leaf path in the tree represents a number. + * + * - For example, the root-to-leaf path 1 -> 2 -> 3 represents the number 123. + * + * Return the total sum of all root-to-leaf numbers. Test cases are generated + * so that the answer will fit in a 32-bit integer. + * + * A leaf node is a node with no children. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number} + */ +var sumNumbers = function(root) { + function traverse(node, value) { + if (!node) { + return null; + } + value += node.val; + if (!node.left && !node.right) { + return Number(value); + } + return traverse(node.left, value) + traverse(node.right, value); + } + + return traverse(root, ''); +}; diff --git a/README.md b/README.md index a93c937b..8e4d820a 100644 --- a/README.md +++ b/README.md @@ -133,6 +133,7 @@ 125|[Valid Palindrome](./0125-valid-palindrome.js)|Easy| 127|[Word Ladder](./0127-word-ladder.js)|Hard| 128|[Longest Consecutive Sequence](./0128-longest-consecutive-sequence.js)|Medium| +129|[Sum Root to Leaf Numbers](./0129-sum-root-to-leaf-numbers.js)|Medium| 131|[Palindrome Partitioning](./0131-palindrome-partitioning.js)|Medium| 133|[Clone Graph](./0133-clone-graph.js)|Medium| 134|[Gas Station](./0134-gas-station.js)|Medium| From 0ea4568b5296960c84bac990ad31e7de27485d96 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 31 Jan 2025 17:26:56 -0600 Subject: [PATCH 559/919] Add solution #147 --- 0147-insertion-sort-list.js | 51 +++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 52 insertions(+) create mode 100644 0147-insertion-sort-list.js diff --git a/0147-insertion-sort-list.js b/0147-insertion-sort-list.js new file mode 100644 index 00000000..cac58c54 --- /dev/null +++ b/0147-insertion-sort-list.js @@ -0,0 +1,51 @@ +/** + * 147. Insertion Sort List + * https://leetcode.com/problems/insertion-sort-list/ + * Difficulty: Medium + * + * Given the head of a singly linked list, sort the list using insertion sort, and + * return the sorted list's head. + * + * The steps of the insertion sort algorithm: + * - Insertion sort iterates, consuming one input element each repetition and growing + * a sorted output list. + * - At each iteration, insertion sort removes one element from the input data, finds + * the location it belongs within the sorted list and inserts it there. + * - It repeats until no input elements remain. + * + * The following is a graphical example of the insertion sort algorithm. The partially + * sorted list (black) initially contains only the first element in the list. One + * element (red) is removed from the input data and inserted in-place into the sorted + * list with each iteration. + */ + +/** + * 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 insertionSortList = function(head) { + const result = new ListNode(0); + + while (head) { + const tail = head; + let current = result; + head = head.next; + + while (current) { + if (!current.next || tail.val <= current.next.val) { + [current.next, tail.next] = [tail, current.next]; + break; + } + current = current.next; + } + } + + return result.next; +}; diff --git a/README.md b/README.md index 8e4d820a..df5addae 100644 --- a/README.md +++ b/README.md @@ -149,6 +149,7 @@ 144|[Binary Tree Preorder Traversal](./0144-binary-tree-preorder-traversal.js)|Easy| 145|[Binary Tree Postorder Traversal](./0145-binary-tree-postorder-traversal.js)|Easy| 146|[LRU Cache](./0146-lru-cache.js)|Medium| +147|[Insertion Sort List](./0147-insertion-sort-list.js)|Medium| 148|[Sort List](./0148-sort-list.js)|Medium| 149|[Max Points on a Line](./0149-max-points-on-a-line.js)|Hard| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| From b55d0c4e1e26335f1d092f158fa3057a06b21e1f Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 31 Jan 2025 17:27:35 -0600 Subject: [PATCH 560/919] Add solution #171 --- 0171-excel-sheet-column-number.js | 18 ++++++++++++++++++ README.md | 1 + 2 files changed, 19 insertions(+) create mode 100644 0171-excel-sheet-column-number.js diff --git a/0171-excel-sheet-column-number.js b/0171-excel-sheet-column-number.js new file mode 100644 index 00000000..8cbe390e --- /dev/null +++ b/0171-excel-sheet-column-number.js @@ -0,0 +1,18 @@ +/** + * 171. Excel Sheet Column Number + * https://leetcode.com/problems/excel-sheet-column-number/ + * Difficulty: Easy + * + * Given a string columnTitle that represents the column title as appears in + * an Excel sheet, return its corresponding column number. + */ + +/** + * @param {string} columnTitle + * @return {number} + */ +var titleToNumber = function(columnTitle) { + return columnTitle.split('').reduce((result, c, i) => { + return result + (c.charCodeAt() - 64) * Math.pow(26, columnTitle.length - (i + 1)); + }, 0); +}; diff --git a/README.md b/README.md index df5addae..6e871437 100644 --- a/README.md +++ b/README.md @@ -163,6 +163,7 @@ 167|[Two Sum II - Input Array Is Sorted](./0167-two-sum-ii-input-array-is-sorted.js)|Easy| 168|[Excel Sheet Column Title](./0168-excel-sheet-column-title.js)|Easy| 169|[Majority Element](./0169-majority-element.js)|Easy| +171|[Excel Sheet Column Number](./0171-excel-sheet-column-number.js)|Easy| 179|[Largest Number](./0179-largest-number.js)|Medium| 187|[Repeated DNA Sequences](./0187-repeated-dna-sequences.js)|Medium| 189|[Rotate Array](./0189-rotate-array.js)|Medium| From accd6137fff5c6b13ee32c6b86d87b9e033d15c3 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 31 Jan 2025 17:29:26 -0600 Subject: [PATCH 561/919] Add solution #827 --- 0827-making-a-large-island.js | 65 +++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 66 insertions(+) create mode 100644 0827-making-a-large-island.js diff --git a/0827-making-a-large-island.js b/0827-making-a-large-island.js new file mode 100644 index 00000000..7feaf7d0 --- /dev/null +++ b/0827-making-a-large-island.js @@ -0,0 +1,65 @@ +/** + * 827. Making A Large Island + * https://leetcode.com/problems/making-a-large-island/ + * Difficulty: Hard + * + * 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. + */ + +/** + * @param {number[][]} grid + * @return {number} + */ +var largestIsland = function(grid) { + function traverse(tile, grid, i, j) { + if (i < 0 || j < 0 || i >= grid.length || j >= grid[0].length + || grid[i][j] === 0 || grid[i][j] === tile) { + return 0; + } + grid[i][j] = tile; + return 1 + ( + traverse(tile, grid, i + 1, j) + + traverse(tile, grid, i - 1, j) + + traverse(tile, grid, i, j + 1) + + traverse(tile, grid, i, j - 1) + ); + }; + + const map = new Map(); + let tile = 2; + let result = -1; + + for (let i = 0; i < grid.length; i++) { + for (let j = 0; j < grid.length; j++) { + if (grid[i][j] === 1) { + const value = traverse(tile, grid, i, j); + map.set(tile, value); + tile += 1; + result = Math.max(result, value); + } + } + } + + map.set(0, 0); + + for (let i = 0; i < grid.length; i++) { + for (let j = 0; j < grid.length; j++) { + if (!grid[i][j]) { + const seen = new Set(); + let sum = 0; + if (i > 0) seen.add(grid[i - 1][j]); + if (j > 0) seen.add(grid[i][j - 1]); + if (i < grid.length - 1) seen.add(grid[i + 1][j]); + if (j < grid.length - 1) seen.add(grid[i][j + 1]); + seen.forEach(val => sum += map.get(val)); + result = Math.max(result, sum + 1); + } + } + } + + return result; +}; diff --git a/README.md b/README.md index 6e871437..be6d5f62 100644 --- a/README.md +++ b/README.md @@ -311,6 +311,7 @@ 819|[Most Common Word](./0819-most-common-word.js)|Easy| 821|[Shortest Distance to a Character](./0821-shortest-distance-to-a-character.js)|Easy| 824|[Goat Latin](./0824-goat-latin.js)|Easy| +827|[Making A Large Island](./0827-making-a-large-island.js)|Hard| 831|[Masking Personal Information](./0831-masking-personal-information.js)|Medium| 841|[Keys and Rooms](./0841-keys-and-rooms.js)|Medium| 844|[Backspace String Compare](./0844-backspace-string-compare.js)|Easy| From 3046fdb9686dfb8441d58a6a9598aeac5de8a772 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 1 Feb 2025 17:56:46 -0600 Subject: [PATCH 562/919] Add solution #173 --- 0173-binary-search-tree-iterator.js | 58 +++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 59 insertions(+) create mode 100644 0173-binary-search-tree-iterator.js diff --git a/0173-binary-search-tree-iterator.js b/0173-binary-search-tree-iterator.js new file mode 100644 index 00000000..44968700 --- /dev/null +++ b/0173-binary-search-tree-iterator.js @@ -0,0 +1,58 @@ +/** + * 173. Binary Search Tree Iterator + * https://leetcode.com/problems/binary-search-tree-iterator/ + * Difficulty: Medium + * + * Implement the BSTIterator class that represents an iterator over the in-order traversal + * of a binary search tree (BST): + * - BSTIterator(TreeNode root) Initializes an object of the BSTIterator class. The root of + * the BST is given as part of the constructor. The pointer should be initialized to a + * non-existent number smaller than any element in the BST. + * - boolean hasNext() Returns true if there exists a number in the traversal to the right + * of the pointer, otherwise returns false. + * - int next() Moves the pointer to the right, then returns the number at the pointer. + * + * Notice that by initializing the pointer to a non-existent smallest number, the first call + * to next() will return the smallest element in the BST. + * + * You may assume that next() calls will always be valid. That is, there will be at least a + * next number in the in-order traversal when next() is called. + */ + +/** + * 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 + */ +var BSTIterator = function(root) { + this.stack = []; + this.root = root; +}; + +/** + * @return {number} + */ +BSTIterator.prototype.next = function() { + while (this.root) { + this.stack.push(this.root); + this.root = this.root.left; + } + this.root = this.stack.pop(); + + const result = this.root.val; + this.root = this.root.right; + return result; +}; + +/** + * @return {boolean} + */ +BSTIterator.prototype.hasNext = function() { + return this.root || this.stack.length; +}; diff --git a/README.md b/README.md index be6d5f62..e8f09b90 100644 --- a/README.md +++ b/README.md @@ -164,6 +164,7 @@ 168|[Excel Sheet Column Title](./0168-excel-sheet-column-title.js)|Easy| 169|[Majority Element](./0169-majority-element.js)|Easy| 171|[Excel Sheet Column Number](./0171-excel-sheet-column-number.js)|Easy| +173|[Binary Search Tree Iterator](./0173-binary-search-tree-iterator.js)|Medium| 179|[Largest Number](./0179-largest-number.js)|Medium| 187|[Repeated DNA Sequences](./0187-repeated-dna-sequences.js)|Medium| 189|[Rotate Array](./0189-rotate-array.js)|Medium| From 62eeb3aa6bba16548805d097c8a35bb185d8a19f Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 1 Feb 2025 17:57:33 -0600 Subject: [PATCH 563/919] Add solution #1319 --- ...of-operations-to-make-network-connected.js | 50 +++++++++++++++++++ README.md | 1 + 2 files changed, 51 insertions(+) create mode 100644 1319-number-of-operations-to-make-network-connected.js diff --git a/1319-number-of-operations-to-make-network-connected.js b/1319-number-of-operations-to-make-network-connected.js new file mode 100644 index 00000000..9dc6fb16 --- /dev/null +++ b/1319-number-of-operations-to-make-network-connected.js @@ -0,0 +1,50 @@ +/** + * 1319. Number of Operations to Make Network Connected + * https://leetcode.com/problems/number-of-operations-to-make-network-connected/ + * Difficulty: Medium + * + * There are n computers numbered from 0 to n - 1 connected by ethernet cables connections forming + * a network where connections[i] = [ai, bi] represents a connection between computers ai and bi. + * Any computer can reach any other computer directly or indirectly through the network. + * + * You are given an initial computer network connections. You can extract certain cables between + * two directly connected computers, and place them between any pair of disconnected computers to + * make them directly connected. + * + * Return the minimum number of times you need to do this in order to make all the computers + * connected. If it is not possible, return -1. + */ + +/** + * @param {number} n + * @param {number[][]} connections + * @return {number} + */ +var makeConnected = function(n, connections) { + const parent = Array(n).fill(-1); + let isNotConnected = n - 1; + let count = 0; + + connections.forEach(([node, connection]) => { + if (search(node) !== search(connection)) { + const p1 = search(node); + const p2 = search(connection); + if (p1 !== p2) { + parent[p2] = p1; + } + isNotConnected--; + } else { + count++; + } + }); + + return isNotConnected <= count ? isNotConnected : -1; + + function search(node) { + if (parent[node] === -1) { + return node; + } + parent[node] = search(parent[node]); + return parent[node]; + } +}; diff --git a/README.md b/README.md index e8f09b90..282d78cb 100644 --- a/README.md +++ b/README.md @@ -382,6 +382,7 @@ 1313|[Decompress Run-Length Encoded List](./1313-decompress-run-length-encoded-list.js)|Easy| 1317|[Convert Integer to the Sum of Two No-Zero Integers](./1317-convert-integer-to-the-sum-of-two-no-zero-integers.js)|Easy| 1318|[Minimum Flips to Make a OR b Equal to c](./1318-minimum-flips-to-make-a-or-b-equal-to-c.js)|Medium| +1319|[Number of Operations to Make Network Connected](./1319-number-of-operations-to-make-network-connected.js)|Medium| 1323|[Maximum 69 Number](./1323-maximum-69-number.js)|Easy| 1324|[Print Words Vertically](./1324-print-words-vertically.js)|Medium| 1331|[Rank Transform of an Array](./1331-rank-transform-of-an-array.js)|Easy| From 289e10825c47350c9abfb3e8d07d72fcac551110 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 1 Feb 2025 18:00:26 -0600 Subject: [PATCH 564/919] Add solution #3151 --- 3151-special-array-i.js | 24 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 3151-special-array-i.js diff --git a/3151-special-array-i.js b/3151-special-array-i.js new file mode 100644 index 00000000..75caaa6d --- /dev/null +++ b/3151-special-array-i.js @@ -0,0 +1,24 @@ +/** + * 3151. Special Array I + * https://leetcode.com/problems/special-array-i/ + * Difficulty: Easy + * + * An array is considered special if every pair of its adjacent elements contains + * two numbers with different parity. + * + * You are given an array of integers nums. Return true if nums is a special array, + * otherwise, return false. + */ + +/** + * @param {number[]} nums + * @return {boolean} + */ +var isArraySpecial = function(nums) { + for (let i = 0; i < nums.length - 1; i++) { + if ((nums[i] + nums[i + 1]) % 2 === 0) { + return false; + } + } + return true; +}; diff --git a/README.md b/README.md index 282d78cb..3b498e7b 100644 --- a/README.md +++ b/README.md @@ -538,6 +538,7 @@ 2948|[Make Lexicographically Smallest Array by Swapping Elements](./2948-make-lexicographically-smallest-array-by-swapping-elements.js)|Medium| 3042|[Count Prefix and Suffix Pairs I](./3042-count-prefix-and-suffix-pairs-i.js)|Easy| 3110|[Score of a String](./3110-score-of-a-string.js)|Easy| +3151|[Special Array I](./3151-special-array-i.js)|Easy| 3223|[Minimum Length of String After Operations](./3223-minimum-length-of-string-after-operations.js)|Medium| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| 3396|[Minimum Number of Operations to Make Elements in Array Distinct](./3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy| From e86a3802c1c3b0d71f6474fc514fa4f9ba0fe2c5 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 1 Feb 2025 18:00:54 -0600 Subject: [PATCH 565/919] Add solution #172 --- 0172-factorial-trailing-zeroes.js | 17 +++++++++++++++++ README.md | 1 + 2 files changed, 18 insertions(+) create mode 100644 0172-factorial-trailing-zeroes.js diff --git a/0172-factorial-trailing-zeroes.js b/0172-factorial-trailing-zeroes.js new file mode 100644 index 00000000..d1616073 --- /dev/null +++ b/0172-factorial-trailing-zeroes.js @@ -0,0 +1,17 @@ +/** + * 172. Factorial Trailing Zeroes + * https://leetcode.com/problems/factorial-trailing-zeroes/ + * Difficulty: Medium + * + * Given an integer n, return the number of trailing zeroes in n!. + * + * Note that n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1. + */ + +/** + * @param {number} n + * @return {number} + */ +var trailingZeroes = function(n) { + return n < 5 ? 0 : Math.floor(n / 5) + trailingZeroes(n / 5); +}; diff --git a/README.md b/README.md index 3b498e7b..e10321e1 100644 --- a/README.md +++ b/README.md @@ -164,6 +164,7 @@ 168|[Excel Sheet Column Title](./0168-excel-sheet-column-title.js)|Easy| 169|[Majority Element](./0169-majority-element.js)|Easy| 171|[Excel Sheet Column Number](./0171-excel-sheet-column-number.js)|Easy| +172|[Factorial Trailing Zeroes](./0172-factorial-trailing-zeroes.js)|Medium| 173|[Binary Search Tree Iterator](./0173-binary-search-tree-iterator.js)|Medium| 179|[Largest Number](./0179-largest-number.js)|Medium| 187|[Repeated DNA Sequences](./0187-repeated-dna-sequences.js)|Medium| From 348bda871b928231942b18d9989c933fdd4b1f50 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 1 Feb 2025 18:06:00 -0600 Subject: [PATCH 566/919] Add solution #201 --- 0201-bitwise-and-of-numbers-range.js | 23 +++++++++++++++++++++++ README.md | 1 + 2 files changed, 24 insertions(+) create mode 100644 0201-bitwise-and-of-numbers-range.js diff --git a/0201-bitwise-and-of-numbers-range.js b/0201-bitwise-and-of-numbers-range.js new file mode 100644 index 00000000..c879aaaa --- /dev/null +++ b/0201-bitwise-and-of-numbers-range.js @@ -0,0 +1,23 @@ +/** + * 201. Bitwise AND of Numbers Range + * https://leetcode.com/problems/bitwise-and-of-numbers-range/ + * Difficulty: Medium + * + * Given two integers left and right that represent the range [left, right], return the + * bitwise AND of all numbers in this range, inclusive. + */ + +/** + * @param {number} left + * @param {number} right + * @return {number} + */ +var rangeBitwiseAnd = function(left, right) { + let count = 0; + while (left !== right) { + left >>= 1; + right >>= 1; + count++; + } + return left << count; +}; diff --git a/README.md b/README.md index e10321e1..2a632089 100644 --- a/README.md +++ b/README.md @@ -174,6 +174,7 @@ 198|[House Robber](./0198-house-robber.js)|Medium| 199|[Binary Tree Right Side View](./0199-binary-tree-right-side-view.js)|Medium| 200|[Number of Islands](./0200-number-of-islands.js)|Medium| +201|[Bitwise AND of Numbers Range](./0201-bitwise-and-of-numbers-range.js)|Medium| 202|[Happy Number](./0202-happy-number.js)|Easy| 203|[Remove Linked List Elements](./0203-remove-linked-list-elements.js)|Easy| 204|[Count Primes](./0204-count-primes.js)|Medium| From 4bdacee572f79ed49dfa4b175fc919de5606b3b7 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 2 Feb 2025 15:59:34 -0600 Subject: [PATCH 567/919] Add solution #153 --- 0153-find-minimum-in-rotated-sorted-array.js | 39 ++++++++++++++++++++ README.md | 1 + 2 files changed, 40 insertions(+) create mode 100644 0153-find-minimum-in-rotated-sorted-array.js diff --git a/0153-find-minimum-in-rotated-sorted-array.js b/0153-find-minimum-in-rotated-sorted-array.js new file mode 100644 index 00000000..4146f626 --- /dev/null +++ b/0153-find-minimum-in-rotated-sorted-array.js @@ -0,0 +1,39 @@ +/** + * 153. Find Minimum in Rotated Sorted Array + * https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/ + * Difficulty: Medium + * + * Suppose an array of length n sorted in ascending order is rotated between 1 and n times. + * For example, the array nums = [0,1,2,4,5,6,7] might become: + * - [4,5,6,7,0,1,2] if it was rotated 4 times. + * - [0,1,2,4,5,6,7] if it was rotated 7 times. + * + * Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array + * [a[n-1], a[0], a[1], a[2], ..., a[n-2]]. + * + * Given the sorted rotated array nums of unique elements, return the minimum element of this + * array. + * + * You must write an algorithm that runs in O(log n) time. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var findMin = function(nums) { + let left = 0; + let right = nums.length - 1; + + while (left < right) { + const mid = Math.floor((left + right) / 2); + + if (nums[mid] <= nums[right]) { + right = mid; + } else { + left = mid + 1; + } + } + + return nums[left]; +}; diff --git a/README.md b/README.md index 2a632089..4f082809 100644 --- a/README.md +++ b/README.md @@ -154,6 +154,7 @@ 149|[Max Points on a Line](./0149-max-points-on-a-line.js)|Hard| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| +153|[Find Minimum in Rotated Sorted Array](./0153-find-minimum-in-rotated-sorted-array.js)|Medium| 155|[Min Stack](./0155-min-stack.js)|Medium| 160|[Intersection of Two Linked Lists](./0160-intersection-of-two-linked-lists.js)|Medium| 162|[Find Peak Element](./0162-find-peak-element.js)|Medium| From 283f6d86c63d55c88af2c68b6021e83b83570f81 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 2 Feb 2025 16:01:13 -0600 Subject: [PATCH 568/919] Add solution #154 --- ...find-minimum-in-rotated-sorted-array-ii.js | 31 +++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 0154-find-minimum-in-rotated-sorted-array-ii.js diff --git a/0154-find-minimum-in-rotated-sorted-array-ii.js b/0154-find-minimum-in-rotated-sorted-array-ii.js new file mode 100644 index 00000000..b665f5df --- /dev/null +++ b/0154-find-minimum-in-rotated-sorted-array-ii.js @@ -0,0 +1,31 @@ +/** + * 154. Find Minimum in Rotated Sorted Array II + * https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/ + * Difficulty: Hard + * + * Suppose an array of length n sorted in ascending order is rotated between 1 and n times. + * For example, the array nums = [0,1,4,4,5,6,7] might become: + * - [4,5,6,7,0,1,4] if it was rotated 4 times. + * - [0,1,4,4,5,6,7] if it was rotated 7 times. + * + * Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array + * [a[n-1], a[0], a[1], a[2], ..., a[n-2]]. + * + * Given the sorted rotated array nums that may contain duplicates, return the minimum element + * of this array. + * + * You must decrease the overall operation steps as much as possible. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var findMin = function(nums) { + for (let i = 0; i < nums.length - 1; i++) { + if (nums[i] > nums[i + 1]) { + return nums[i + 1]; + } + } + return nums[0]; +}; diff --git a/README.md b/README.md index 4f082809..fe482ad7 100644 --- a/README.md +++ b/README.md @@ -155,6 +155,7 @@ 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| 153|[Find Minimum in Rotated Sorted Array](./0153-find-minimum-in-rotated-sorted-array.js)|Medium| +154|[Find Minimum in Rotated Sorted Array II](./0154-find-minimum-in-rotated-sorted-array-ii.js)|Hard| 155|[Min Stack](./0155-min-stack.js)|Medium| 160|[Intersection of Two Linked Lists](./0160-intersection-of-two-linked-lists.js)|Medium| 162|[Find Peak Element](./0162-find-peak-element.js)|Medium| From 357b71e7d0cae6c87137fcd9d7c45b7221f3b640 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 2 Feb 2025 16:02:15 -0600 Subject: [PATCH 569/919] Add solution #130 --- 0130-surrounded-regions.js | 53 ++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 54 insertions(+) create mode 100644 0130-surrounded-regions.js diff --git a/0130-surrounded-regions.js b/0130-surrounded-regions.js new file mode 100644 index 00000000..6b11bbee --- /dev/null +++ b/0130-surrounded-regions.js @@ -0,0 +1,53 @@ +/** + * 130. Surrounded Regions + * https://leetcode.com/problems/surrounded-regions/ + * Difficulty: Medium + * + * You are given an m x n matrix board containing letters 'X' and 'O', capture regions + * that are surrounded: + * - Connect: A cell is connected to adjacent cells horizontally or vertically. + * - Region: To form a region connect every 'O' cell. + * - Surround: The region is surrounded with 'X' cells if you can connect the region with + * 'X' cells and none of the region cells are on the edge of the board. + * + * To capture a surrounded region, replace all 'O's with 'X's in-place within the original + * board. You do not need to return anything. + */ + +/** + * @param {character[][]} board + * @return {void} Do not return anything, modify board in-place instead. + */ +var solve = function(board) { + for (let i = 0; i < board.length; i++) { + for (let j = 0; j < board[0].length; j++) { + if (board[i][j] === 'O' + && (!i || !j || i === board.length - 1 || j === board[0].length - 1)) { + dfs(i, j); + } + } + } + + for (let i = 0; i < board.length; i++) { + for (let j = 0; j < board[0].length; j++) { + if (board[i][j] === '-') { + board[i][j] = 'O'; + } else { + board[i][j] = 'X'; + } + } + } + + function dfs(i, j) { + if (i < 0 || i >= board.length || j < 0 || j >= board[i].length + || board[i][j] === '-' || board[i][j] === 'X') { + return; + } + + board[i][j] = '-'; + dfs(i - 1, j); + dfs(i + 1, j); + dfs(i, j - 1); + dfs(i, j + 1); + } +}; diff --git a/README.md b/README.md index fe482ad7..9a55f0ca 100644 --- a/README.md +++ b/README.md @@ -134,6 +134,7 @@ 127|[Word Ladder](./0127-word-ladder.js)|Hard| 128|[Longest Consecutive Sequence](./0128-longest-consecutive-sequence.js)|Medium| 129|[Sum Root to Leaf Numbers](./0129-sum-root-to-leaf-numbers.js)|Medium| +130|[Surrounded Regions](./0130-surrounded-regions.js)|Medium| 131|[Palindrome Partitioning](./0131-palindrome-partitioning.js)|Medium| 133|[Clone Graph](./0133-clone-graph.js)|Medium| 134|[Gas Station](./0134-gas-station.js)|Medium| From 638db298c4a343880d474ec7df9ebc27f223786e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 2 Feb 2025 16:03:13 -0600 Subject: [PATCH 570/919] Add solution #211 --- ...ign-add-and-search-words-data-structure.js | 60 +++++++++++++++++++ README.md | 1 + 2 files changed, 61 insertions(+) create mode 100644 0211-design-add-and-search-words-data-structure.js diff --git a/0211-design-add-and-search-words-data-structure.js b/0211-design-add-and-search-words-data-structure.js new file mode 100644 index 00000000..ee615fe3 --- /dev/null +++ b/0211-design-add-and-search-words-data-structure.js @@ -0,0 +1,60 @@ +/** + * 211. Design Add and Search Words Data Structure + * https://leetcode.com/problems/design-add-and-search-words-data-structure/ + * Difficulty: Medium + * + * Design a data structure that supports adding new words and finding if a string matches + * any previously added string. + * + * Implement the WordDictionary class: + * - WordDictionary() Initializes the object. + * - void addWord(word) Adds word to the data structure, it can be matched later. + * - bool search(word) Returns true if there is any string in the data structure that + * matches word or false otherwise. word may contain dots '.' where dots can be + * matched with any letter. + */ + + +var WordDictionary = function() { + this.root = {}; +}; + +/** + * @param {string} word + * @return {void} + */ +WordDictionary.prototype.addWord = function(word) { + let node = this.root; + + for (const character of word) { + node[character] = node[character] || {}; + node = node[character]; + } + + node.isTail = true; +}; + +/** + * @param {string} word + * @return {boolean} + */ +WordDictionary.prototype.search = function(word) { + return dfs(this.root, 0); + + function dfs(node, i) { + if (word.length === i) { + return node.isTail; + } + if (word[i] === '.') { + for (const key in node) { + if (dfs(node[key], i + 1)) { + return true; + } + } + } else if (node[word[i]] && dfs(node[word[i]], i + 1)) { + return true; + } + + return false; + } +}; diff --git a/README.md b/README.md index 9a55f0ca..0ac35c30 100644 --- a/README.md +++ b/README.md @@ -184,6 +184,7 @@ 205|[Isomorphic Strings](./0205-isomorphic-strings.js)|Easy| 206|[Reverse Linked List](./0206-reverse-linked-list.js)|Easy| 207|[Course Schedule](./0207-course-schedule.js)|Medium| +211|[Design Add and Search Words Data Structure](./0211-design-add-and-search-words-data-structure.js)|Medium| 213|[House Robber II](./0213-house-robber-ii.js)|Medium| 214|[Shortest Palindrome](./0214-shortest-palindrome.js)|Hard| 215|[Kth Largest Element in an Array](./0215-kth-largest-element-in-an-array.js)|Medium| From 522dc3b20509657f85616ae4bcec72a298b155c9 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 2 Feb 2025 16:03:52 -0600 Subject: [PATCH 571/919] Add solution #1752 --- 1752-check-if-array-is-sorted-and-rotated.js | 33 ++++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 1752-check-if-array-is-sorted-and-rotated.js diff --git a/1752-check-if-array-is-sorted-and-rotated.js b/1752-check-if-array-is-sorted-and-rotated.js new file mode 100644 index 00000000..3878c338 --- /dev/null +++ b/1752-check-if-array-is-sorted-and-rotated.js @@ -0,0 +1,33 @@ +/** + * 1752. Check if Array Is Sorted and Rotated + * https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/ + * Difficulty: Easy + * + * Given an array nums, return true if the array was originally sorted in non-decreasing + * order, then rotated some number of positions (including zero). Otherwise, return false. + * + * There may be duplicates in the original array. + * + * Note: An array A rotated by x positions results in an array B of the same length such + * that A[i] == B[(i+x) % A.length], where % is the modulo operation. + */ + +/** + * @param {number[]} nums + * @return {boolean} + */ +var check = function(nums) { + let count = 0; + + for (let i = 0; i < nums.length - 1; i++) { + if (nums[i] > nums[i + 1]) { + count++; + } + } + + if (nums[nums.length - 1] > nums[0]) { + count++; + } + + return count < 2 ? true : false; +}; diff --git a/README.md b/README.md index 0ac35c30..d0c0a473 100644 --- a/README.md +++ b/README.md @@ -451,6 +451,7 @@ 1716|[Calculate Money in Leetcode Bank](./1716-calculate-money-in-leetcode-bank.js)|Easy| 1732|[Find the Highest Altitude](./1732-find-the-highest-altitude.js)|Easy| 1748|[Sum of Unique Elements](./1748-sum-of-unique-elements.js)|Easy| +1752|[Check if Array Is Sorted and Rotated](./1752-check-if-array-is-sorted-and-rotated.js)|Easy| 1764|[Form Array by Concatenating Subarrays of Another Array](./1764-form-array-by-concatenating-subarrays-of-another-array.js)|Medium| 1765|[Map of Highest Peak](./1765-map-of-highest-peak.js)|Medium| 1768|[Merge Strings Alternately](./1768-merge-strings-alternately.js)|Easy| From 59db37cc710fca636ef1efc83b5827ca039cf517 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 3 Feb 2025 16:53:25 -0600 Subject: [PATCH 572/919] Add solution #3105 --- ...reasing-or-strictly-decreasing-subarray.js | 22 +++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 3105-longest-strictly-increasing-or-strictly-decreasing-subarray.js diff --git a/3105-longest-strictly-increasing-or-strictly-decreasing-subarray.js b/3105-longest-strictly-increasing-or-strictly-decreasing-subarray.js new file mode 100644 index 00000000..fd707819 --- /dev/null +++ b/3105-longest-strictly-increasing-or-strictly-decreasing-subarray.js @@ -0,0 +1,22 @@ +/** + * 3105. Longest Strictly Increasing or Strictly Decreasing Subarray + * https://leetcode.com/problems/longest-strictly-increasing-or-strictly-decreasing-subarray/ + * Difficulty: Easy + * + * You are given an array of integers nums. Return the length of the longest subarray of nums + * which is either strictly increasing or strictly decreasing. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var longestMonotonicSubarray = function(nums) { + let result = nums.length > 0 ? 1 : 0; + for (let i = 1, down = 1, up = 1; i < nums.length; i++) { + nums[i - 1] > nums[i] ? down++ : down = 1; + nums[i - 1] < nums[i] ? up++ : up = 1; + result = Math.max(result, down, up); + } + return result; +}; diff --git a/README.md b/README.md index d0c0a473..ec62b9ae 100644 --- a/README.md +++ b/README.md @@ -544,6 +544,7 @@ 2727|[Is Object Empty](./2727-is-object-empty.js)|Easy| 2948|[Make Lexicographically Smallest Array by Swapping Elements](./2948-make-lexicographically-smallest-array-by-swapping-elements.js)|Medium| 3042|[Count Prefix and Suffix Pairs I](./3042-count-prefix-and-suffix-pairs-i.js)|Easy| +3105|[Longest Strictly Increasing or Strictly Decreasing Subarray](./3105-longest-strictly-increasing-or-strictly-decreasing-subarray.js)|Easy| 3110|[Score of a String](./3110-score-of-a-string.js)|Easy| 3151|[Special Array I](./3151-special-array-i.js)|Easy| 3223|[Minimum Length of String After Operations](./3223-minimum-length-of-string-after-operations.js)|Medium| From 8f44163dab7097470ae3e6707b7f79e1d6c12413 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 3 Feb 2025 16:54:13 -0600 Subject: [PATCH 573/919] Add solution #696 --- 0696-count-binary-substrings.js | 33 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 0696-count-binary-substrings.js diff --git a/0696-count-binary-substrings.js b/0696-count-binary-substrings.js new file mode 100644 index 00000000..f7607f56 --- /dev/null +++ b/0696-count-binary-substrings.js @@ -0,0 +1,33 @@ +/** + * 696. Count Binary Substrings + * https://leetcode.com/problems/count-binary-substrings/ + * Difficulty: Easy + * + * Given a binary string s, return the number of non-empty substrings that have the same + * number of 0's and 1's, and all the 0's and all the 1's in these substrings are grouped + * consecutively. + * + * Substrings that occur multiple times are counted the number of times they occur. + */ + +/** + * @param {string} s + * @return {number} + */ +var countBinarySubstrings = function(s) { + let result = 0; + + for (let i = 0, group = [], count = 1, prevCount = 0; i < s.length; i++) { + if (s[i] === s[i + 1]) { + count++; + } else { + if (prevCount) { + result += prevCount <= count ? prevCount : count; + } + prevCount = count; + count = 1; + } + } + + return result; +}; diff --git a/README.md b/README.md index ec62b9ae..2394ec65 100644 --- a/README.md +++ b/README.md @@ -290,6 +290,7 @@ 684|[Redundant Connection](./0684-redundant-connection.js)|Medium| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| 695|[Max Area of Island](./0695-max-area-of-island.js)|Medium| +696|[Count Binary Substrings](./0696-count-binary-substrings.js)|Easy| 697|[Degree of an Array](./0697-degree-of-an-array.js)|Easy| 700|[Search in a Binary Search Tree](./0700-search-in-a-binary-search-tree.js)|Easy| 701|[Insert into a Binary Search Tree](./0701-insert-into-a-binary-search-tree.js)|Medium| From 61d99788ed13f5bff82d4c3879dc77dd841bbd68 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 3 Feb 2025 16:55:18 -0600 Subject: [PATCH 574/919] Add solution #654 --- 0654-maximum-binary-tree.js | 38 +++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 39 insertions(+) create mode 100644 0654-maximum-binary-tree.js diff --git a/0654-maximum-binary-tree.js b/0654-maximum-binary-tree.js new file mode 100644 index 00000000..ad5bd35b --- /dev/null +++ b/0654-maximum-binary-tree.js @@ -0,0 +1,38 @@ +/** + * 654. Maximum Binary Tree + * https://leetcode.com/problems/maximum-binary-tree/ + * Difficulty: Medium + * + * You are given an integer array nums with no duplicates. A maximum binary tree can be built + * recursively from nums using the following algorithm: + * 1. Create a root node whose value is the maximum value in nums. + * 2. Recursively build the left subtree on the subarray prefix to the left of the maximum value. + * 3. Recursively build the right subtree on the subarray suffix to the right of the maximum value. + * + * Return the maximum binary tree built from nums. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {number[]} nums + * @return {TreeNode} + */ +var constructMaximumBinaryTree = function(nums) { + if (!nums.length) return null; + + const max = Math.max(...nums); + const index = nums.indexOf(max); + const head = new TreeNode(max); + + head.left = constructMaximumBinaryTree(nums.slice(0, index)); + head.right = constructMaximumBinaryTree(nums.slice(index + 1)); + + return head; +}; diff --git a/README.md b/README.md index 2394ec65..3c2ae3ff 100644 --- a/README.md +++ b/README.md @@ -286,6 +286,7 @@ 648|[Replace Words](./0648-replace-words.js)|Medium| 649|[Dota2 Senate](./0649-dota2-senate.js)|Medium| 653|[Two Sum IV - Input is a BST](./0653-two-sum-iv-input-is-a-bst.js)|Easy| +654|[Maximum Binary Tree](./0654-maximum-binary-tree.js)|Medium| 680|[Valid Palindrome II](./0680-valid-palindrome-ii.js)|Easy| 684|[Redundant Connection](./0684-redundant-connection.js)|Medium| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| From 49e422343a52959b0320bd8f1d0c2a6caef5711c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 3 Feb 2025 16:55:48 -0600 Subject: [PATCH 575/919] Add solution #693 --- 0693-binary-number-with-alternating-bits.js | 19 +++++++++++++++++++ README.md | 1 + 2 files changed, 20 insertions(+) create mode 100644 0693-binary-number-with-alternating-bits.js diff --git a/0693-binary-number-with-alternating-bits.js b/0693-binary-number-with-alternating-bits.js new file mode 100644 index 00000000..fad03f79 --- /dev/null +++ b/0693-binary-number-with-alternating-bits.js @@ -0,0 +1,19 @@ +/** + * 693. Binary Number with Alternating Bits + * https://leetcode.com/problems/binary-number-with-alternating-bits/ + * Difficulty: Easy + * + * Given a positive integer, check whether it has alternating bits: namely, if two adjacent + * bits will always have different values. + */ + +/** + * @param {number} n + * @return {boolean} + */ +var hasAlternatingBits = function(n) { + for (let i = 1, b = n.toString(2); i < b.length; i++) { + if (b[i - 1] === b[i]) return false; + } + return true; +}; diff --git a/README.md b/README.md index 3c2ae3ff..b5a6812c 100644 --- a/README.md +++ b/README.md @@ -290,6 +290,7 @@ 680|[Valid Palindrome II](./0680-valid-palindrome-ii.js)|Easy| 684|[Redundant Connection](./0684-redundant-connection.js)|Medium| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| +693|[Binary Number with Alternating Bits](./0693-binary-number-with-alternating-bits.js)|Easy| 695|[Max Area of Island](./0695-max-area-of-island.js)|Medium| 696|[Count Binary Substrings](./0696-count-binary-substrings.js)|Easy| 697|[Degree of an Array](./0697-degree-of-an-array.js)|Easy| From a664b142e842c12a3fa5ad549575cf3a3353bf9d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 3 Feb 2025 16:56:32 -0600 Subject: [PATCH 576/919] Add solution #720 --- 0720-longest-word-in-dictionary.js | 32 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 0720-longest-word-in-dictionary.js diff --git a/0720-longest-word-in-dictionary.js b/0720-longest-word-in-dictionary.js new file mode 100644 index 00000000..eb97c011 --- /dev/null +++ b/0720-longest-word-in-dictionary.js @@ -0,0 +1,32 @@ +/** + * 720. Longest Word in Dictionary + * https://leetcode.com/problems/longest-word-in-dictionary/ + * Difficulty: Medium + * + * Given an array of strings words representing an English Dictionary, return the longest word + * in words that can be built one character at a time by other words in words. + * + * If there is more than one possible answer, return the longest word with the smallest + * lexicographical order. If there is no answer, return the empty string. + * + * Note that the word should be built from left to right with each additional character being + * added to the end of a previous word. + */ + +/** + * @param {string[]} words + * @return {string} + */ +var longestWord = function(words) { + const set = new Set(); + let result = ''; + + words.sort().forEach(word => { + if (word.length === 1 || set.has(word.slice(0, -1))) { + set.add(word); + result = word.length > result.length ? word : result; + } + }); + + return result; +}; diff --git a/README.md b/README.md index b5a6812c..662e77e4 100644 --- a/README.md +++ b/README.md @@ -301,6 +301,7 @@ 705|[Design HashSet](./0705-design-hashset.js)|Easy| 706|[Design HashMap](./0706-design-hashmap.js)|Easy| 713|[Subarray Product Less Than K](./0713-subarray-product-less-than-k.js)|Medium| +720|[Longest Word in Dictionary](./0720-longest-word-in-dictionary.js)|Medium| 722|[Remove Comments](./0722-remove-comments.js)|Medium| 724|[Find Pivot Index](./0724-find-pivot-index.js)|Easy| 733|[Flood Fill](./0733-flood-fill.js)|Easy| From 909acc43107f472027ce5555a4e9e39701435727 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 4 Feb 2025 20:25:33 -0600 Subject: [PATCH 577/919] Add solution #132 --- 0132-palindrome-partitioning-ii.js | 31 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 0132-palindrome-partitioning-ii.js diff --git a/0132-palindrome-partitioning-ii.js b/0132-palindrome-partitioning-ii.js new file mode 100644 index 00000000..4bc00080 --- /dev/null +++ b/0132-palindrome-partitioning-ii.js @@ -0,0 +1,31 @@ +/** + * 132. Palindrome Partitioning II + * https://leetcode.com/problems/palindrome-partitioning-ii/ + * Difficulty: Hard + * + * Given a string s, partition s such that every substring of the partition is a palindrome. + * + * Return the minimum cuts needed for a palindrome partitioning of s. + */ + +/** + * @param {string} s + * @return {number} + */ +var minCut = function(s) { + const isPalindrome = new Array(s.length).fill().map(() => new Array(s.length).fill(false)); + const partitions = new Array(s.length).fill(0); + + for (let i = 0; i < s.length; i++) { + let offset = i; + for (let j = 0; j <= i; j++) { + if (s[j] === s[i] && (i - j <= 1 || isPalindrome[j + 1][i - 1])) { + isPalindrome[j][i] = true; + offset = j === 0 ? 0 : Math.min(offset, partitions[j - 1] + 1); + } + } + partitions[i] = offset; + } + + return partitions[s.length - 1]; +}; diff --git a/README.md b/README.md index 662e77e4..d6812168 100644 --- a/README.md +++ b/README.md @@ -136,6 +136,7 @@ 129|[Sum Root to Leaf Numbers](./0129-sum-root-to-leaf-numbers.js)|Medium| 130|[Surrounded Regions](./0130-surrounded-regions.js)|Medium| 131|[Palindrome Partitioning](./0131-palindrome-partitioning.js)|Medium| +132|[Palindrome Partitioning II](./0132-palindrome-partitioning-ii.js)|Hard| 133|[Clone Graph](./0133-clone-graph.js)|Medium| 134|[Gas Station](./0134-gas-station.js)|Medium| 135|[Candy](./0135-candy.js)|Hard| From 7c68295a9f81a3dfdd6f4a6b724ef360107fda48 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 4 Feb 2025 20:26:34 -0600 Subject: [PATCH 578/919] Add solution #150 --- 0150-evaluate-reverse-polish-notation.js | 43 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 44 insertions(+) create mode 100644 0150-evaluate-reverse-polish-notation.js diff --git a/0150-evaluate-reverse-polish-notation.js b/0150-evaluate-reverse-polish-notation.js new file mode 100644 index 00000000..2d714446 --- /dev/null +++ b/0150-evaluate-reverse-polish-notation.js @@ -0,0 +1,43 @@ +/** + * 150. Evaluate Reverse Polish Notation + * https://leetcode.com/problems/evaluate-reverse-polish-notation/ + * Difficulty: Medium + * + * You are given an array of strings tokens that represents an arithmetic expression in a + * Reverse Polish Notation. + * + * Evaluate the expression. Return an integer that represents the value of the expression. + * + * Note that: + * - The valid operators are '+', '-', '*', and '/'. + * - Each operand may be an integer or another expression. + * - The division between two integers always truncates toward zero. + * - There will not be any division by zero. + * - The input represents a valid arithmetic expression in a reverse polish notation. + * - The answer and all the intermediate calculations can be represented in a 32-bit integer. + */ + +/** + * @param {string[]} tokens + * @return {number} + */ +var evalRPN = function(tokens) { + const stack = []; + const operators = { + '+': (a, b) => a + b, + '-': (a, b) => a - b, + '*': (a, b) => a * b, + '/': (a, b) => a / b >= 0 ? Math.floor(a / b) : Math.ceil(a / b), + }; + + tokens.forEach(token => { + if (operators[token]) { + const item = stack.pop(); + stack.push(operators[token](stack.pop(), item)); + } else { + stack.push(Number(token)); + } + }); + + return stack.pop(); +}; diff --git a/README.md b/README.md index d6812168..4a3b82ef 100644 --- a/README.md +++ b/README.md @@ -154,6 +154,7 @@ 147|[Insertion Sort List](./0147-insertion-sort-list.js)|Medium| 148|[Sort List](./0148-sort-list.js)|Medium| 149|[Max Points on a Line](./0149-max-points-on-a-line.js)|Hard| +150|[Evaluate Reverse Polish Notation](./0150-evaluate-reverse-polish-notation.js)|Medium| 151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium| 152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium| 153|[Find Minimum in Rotated Sorted Array](./0153-find-minimum-in-rotated-sorted-array.js)|Medium| From 41dfa23854b8aea4b68f70c28f181a543d8b299e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 4 Feb 2025 20:27:25 -0600 Subject: [PATCH 579/919] Add solution #1790 --- ...-one-string-swap-can-make-strings-equal.js | 25 +++++++++++++++++++ README.md | 1 + 2 files changed, 26 insertions(+) create mode 100644 1790-check-if-one-string-swap-can-make-strings-equal.js diff --git a/1790-check-if-one-string-swap-can-make-strings-equal.js b/1790-check-if-one-string-swap-can-make-strings-equal.js new file mode 100644 index 00000000..c6a48465 --- /dev/null +++ b/1790-check-if-one-string-swap-can-make-strings-equal.js @@ -0,0 +1,25 @@ +/** + * 1790. Check if One String Swap Can Make Strings Equal + * https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/ + * Difficulty: Easy + * + * You are given two strings s1 and s2 of equal length. A string swap is an operation where + * you choose two indices in a string (not necessarily different) and swap the characters + * at these indices. + * + * Return true if it is possible to make both strings equal by performing at most one string + * swap on exactly one of the strings. Otherwise, return false. + */ + +/** + * @param {string} s1 + * @param {string} s2 + * @return {boolean} + */ +var areAlmostEqual = function(s1, s2) { + const indices = []; + for (const i in s1) { + if (s1[i] !== s2[i] && indices.push(i) > 2) return false; + } + return s1[indices[0]] === s2[indices[1]] && s1[indices[1]] === s2[indices[0]]; +}; diff --git a/README.md b/README.md index 4a3b82ef..efb920ef 100644 --- a/README.md +++ b/README.md @@ -462,6 +462,7 @@ 1765|[Map of Highest Peak](./1765-map-of-highest-peak.js)|Medium| 1768|[Merge Strings Alternately](./1768-merge-strings-alternately.js)|Easy| 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| +1790|[Check if One String Swap Can Make Strings Equal](./1790-check-if-one-string-swap-can-make-strings-equal.js)|Easy| 1791|[Find Center of Star Graph](./1791-find-center-of-star-graph.js)|Easy| 1812|[Determine Color of a Chessboard Square](./1812-determine-color-of-a-chessboard-square.js)|Easy| 1817|[Finding the Users Active Minutes](./1817-finding-the-users-active-minutes.js)|Medium| From d66582da1b349ee03efa1bc4f8851a10e6b0fb66 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 4 Feb 2025 20:28:04 -0600 Subject: [PATCH 580/919] Add solution #1800 --- 1800-maximum-ascending-subarray-sum.js | 26 ++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 27 insertions(+) create mode 100644 1800-maximum-ascending-subarray-sum.js diff --git a/1800-maximum-ascending-subarray-sum.js b/1800-maximum-ascending-subarray-sum.js new file mode 100644 index 00000000..24667d2c --- /dev/null +++ b/1800-maximum-ascending-subarray-sum.js @@ -0,0 +1,26 @@ +/** + * 1800. Maximum Ascending Subarray Sum + * https://leetcode.com/problems/maximum-ascending-subarray-sum/ + * Difficulty: Easy + * + * Given an array of positive integers nums, return the maximum possible sum of an + * ascending subarray in nums. + * + * A subarray is defined as a contiguous sequence of numbers in an array. + * + * A subarray [numsl, numsl+1, ..., numsr-1, numsr] is ascending if for all i where + * l <= i < r, numsi < numsi+1. Note that a subarray of size 1 is ascending. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var maxAscendingSum = function(nums) { + let result = nums[0]; + for (let i = 1, max = nums[0]; i < nums.length; i++) { + max = nums[i] > nums[i - 1] ? max + nums[i] : nums[i]; + result = Math.max(result, max); + } + return result; +}; diff --git a/README.md b/README.md index efb920ef..54870aa8 100644 --- a/README.md +++ b/README.md @@ -464,6 +464,7 @@ 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| 1790|[Check if One String Swap Can Make Strings Equal](./1790-check-if-one-string-swap-can-make-strings-equal.js)|Easy| 1791|[Find Center of Star Graph](./1791-find-center-of-star-graph.js)|Easy| +1800|[Maximum Ascending Subarray Sum](./1800-maximum-ascending-subarray-sum.js)|Easy| 1812|[Determine Color of a Chessboard Square](./1812-determine-color-of-a-chessboard-square.js)|Easy| 1817|[Finding the Users Active Minutes](./1817-finding-the-users-active-minutes.js)|Medium| 1832|[Check if the Sentence Is Pangram](./1832-check-if-the-sentence-is-pangram.js)|Easy| From f96548c078d58e06b9807df619f908a465ab02d5 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 4 Feb 2025 20:32:33 -0600 Subject: [PATCH 581/919] Add solution #209 --- 0209-minimum-size-subarray-sum.js | 29 +++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 30 insertions(+) create mode 100644 0209-minimum-size-subarray-sum.js diff --git a/0209-minimum-size-subarray-sum.js b/0209-minimum-size-subarray-sum.js new file mode 100644 index 00000000..ee8208ed --- /dev/null +++ b/0209-minimum-size-subarray-sum.js @@ -0,0 +1,29 @@ +/** + * 209. Minimum Size Subarray Sum + * https://leetcode.com/problems/minimum-size-subarray-sum/ + * Difficulty: Medium + * + * Given an array of positive integers nums and a positive integer target, return the + * minimal length of a subarray whose sum is greater than or equal to target. If there + * is no such subarray, return 0 instead. + */ + +/** + * @param {number} target + * @param {number[]} nums + * @return {number} + */ +var minSubArrayLen = function(target, nums) { + let result = Infinity; + + for (let right = 0, sum = 0, left = 0; right < nums.length; right++) { + sum += nums[right]; + while (sum >= target) { + result = Math.min(result, right - left + 1); + sum -= nums[left]; + left++; + } + } + + return result === Infinity ? 0 : result; +}; diff --git a/README.md b/README.md index 54870aa8..68530c4d 100644 --- a/README.md +++ b/README.md @@ -186,6 +186,7 @@ 205|[Isomorphic Strings](./0205-isomorphic-strings.js)|Easy| 206|[Reverse Linked List](./0206-reverse-linked-list.js)|Easy| 207|[Course Schedule](./0207-course-schedule.js)|Medium| +209|[Minimum Size Subarray Sum](./0209-minimum-size-subarray-sum.js)|Medium| 211|[Design Add and Search Words Data Structure](./0211-design-add-and-search-words-data-structure.js)|Medium| 213|[House Robber II](./0213-house-robber-ii.js)|Medium| 214|[Shortest Palindrome](./0214-shortest-palindrome.js)|Hard| From 15d5b515ee6d357245e44ed2f626995efd1b3f4e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 5 Feb 2025 17:21:23 -0600 Subject: [PATCH 582/919] Add solution #322 --- 0322-coin-change.js | 33 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 0322-coin-change.js diff --git a/0322-coin-change.js b/0322-coin-change.js new file mode 100644 index 00000000..5d9a6212 --- /dev/null +++ b/0322-coin-change.js @@ -0,0 +1,33 @@ +/** + * 322. Coin Change + * https://leetcode.com/problems/coin-change/ + * Difficulty: Medium + * + * You are given an integer array coins representing coins of different denominations and an + * integer amount representing a total amount of money. + * + * Return the fewest number of coins that you need to make up that amount. If that amount of + * money cannot be made up by any combination of the coins, return -1. + * + * You may assume that you have an infinite number of each kind of coin. + */ + +/** + * @param {number[]} coins + * @param {number} amount + * @return {number} + */ +var coinChange = function(coins, amount) { + const counts = new Array(amount + 1).fill(amount + 1); + counts[0] = 0; + + for (let i = 1; i <= amount; i++) { + for (let j = 0; j < coins.length; j++) { + if (i - coins[j] >= 0) { + counts[i] = Math.min(counts[i], 1 + counts[i - coins[j]]); + } + } + } + + return counts[amount] !== amount + 1 ? counts[amount] : -1; +}; diff --git a/README.md b/README.md index 68530c4d..7702c82f 100644 --- a/README.md +++ b/README.md @@ -215,6 +215,7 @@ 290|[Word Pattern](./0290-word-pattern.js)|Easy| 295|[Find Median from Data Stream](./0295-find-median-from-data-stream.js)|Hard| 316|[Remove Duplicate Letters](./0316-remove-duplicate-letters.js)|Medium| +322|[Coin Change](./0322-coin-change.js)|Medium| 326|[Power of Three](./0326-power-of-three.js)|Easy| 328|[Odd Even Linked List](./0328-odd-even-linked-list.js)|Medium| 334|[Increasing Triplet Subsequence](./0334-increasing-triplet-subsequence.js)|Medium| From 2279c0f1036cc5df8ef3f755b3fc37a07600d585 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 5 Feb 2025 17:22:10 -0600 Subject: [PATCH 583/919] Add solution #260 --- 0260-single-number-iii.js | 19 +++++++++++++++++++ README.md | 1 + 2 files changed, 20 insertions(+) create mode 100644 0260-single-number-iii.js diff --git a/0260-single-number-iii.js b/0260-single-number-iii.js new file mode 100644 index 00000000..215ff4f9 --- /dev/null +++ b/0260-single-number-iii.js @@ -0,0 +1,19 @@ +/** + * 260. Single Number III + * https://leetcode.com/problems/single-number-iii/ + * Difficulty: Medium + * + * Given an integer array nums, in which exactly two elements appear only once and all + * the other elements appear exactly twice. Find the two elements that appear only once. + * You can return the answer in any order. + */ + +/** + * @param {number[]} nums + * @return {number[]} + */ +var singleNumber = function(nums) { + const set = new Set(); + nums.forEach(n => set.has(n) ? set.delete(n) : set.add(n)); + return Array.from(set); +}; diff --git a/README.md b/README.md index 7702c82f..cce2e9a4 100644 --- a/README.md +++ b/README.md @@ -205,6 +205,7 @@ 237|[Delete Node in a Linked List](./0237-delete-node-in-a-linked-list.js)|Easy| 238|[Product of Array Except Self](./0238-product-of-array-except-self.js)|Medium| 242|[Valid Anagram](./0242-valid-anagram.js)|Easy| +260|[Single Number III](./0260-single-number-iii.js)|Medium| 263|[Ugly Number](./0263-ugly-number.js)|Easy| 264|[Ugly Number II](./0264-ugly-number-ii.js)|Medium| 268|[Missing Number](./0268-missing-number.js)|Easy| From ca4c002a49a64b14680097c7e10c964c3650206f Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 5 Feb 2025 17:22:42 -0600 Subject: [PATCH 584/919] Add solution #258 --- 0258-add-digits.js | 16 ++++++++++++++++ README.md | 1 + 2 files changed, 17 insertions(+) create mode 100644 0258-add-digits.js diff --git a/0258-add-digits.js b/0258-add-digits.js new file mode 100644 index 00000000..29f1dde9 --- /dev/null +++ b/0258-add-digits.js @@ -0,0 +1,16 @@ +/** + * 258. Add Digits + * https://leetcode.com/problems/add-digits/ + * Difficulty: Easy + * + * Given an integer num, repeatedly add all its digits until + * the result has only one digit, and return it. + */ + +/** + * @param {number} num + * @return {number} + */ +var addDigits = function(num) { + return num < 10 ? num : num % 9 === 0 ? 9 : num % 9; +}; diff --git a/README.md b/README.md index cce2e9a4..4916e3fe 100644 --- a/README.md +++ b/README.md @@ -205,6 +205,7 @@ 237|[Delete Node in a Linked List](./0237-delete-node-in-a-linked-list.js)|Easy| 238|[Product of Array Except Self](./0238-product-of-array-except-self.js)|Medium| 242|[Valid Anagram](./0242-valid-anagram.js)|Easy| +258|[Add Digits](./0258-add-digits.js)|Easy| 260|[Single Number III](./0260-single-number-iii.js)|Medium| 263|[Ugly Number](./0263-ugly-number.js)|Easy| 264|[Ugly Number II](./0264-ugly-number-ii.js)|Medium| From 8f0d6683a4d4890c7529c26f8c938ddc8863b0ea Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 5 Feb 2025 17:23:30 -0600 Subject: [PATCH 585/919] Add solution #228 --- 0228-summary-ranges.js | 33 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 0228-summary-ranges.js diff --git a/0228-summary-ranges.js b/0228-summary-ranges.js new file mode 100644 index 00000000..db1453ac --- /dev/null +++ b/0228-summary-ranges.js @@ -0,0 +1,33 @@ +/** + * 228. Summary Ranges + * https://leetcode.com/problems/summary-ranges/ + * Difficulty: Easy + * + * You are given a sorted unique integer array nums. + * + * A range [a,b] is the set of all integers from a to b (inclusive). + * + * Return the smallest sorted list of ranges that cover all the numbers in the + * array exactly. That is, each element of nums is covered by exactly one of + * the ranges, and there is no integer x such that x is in one of the ranges + * but not in nums. + * + * Each range [a,b] in the list should be output as: + * - "a->b" if a != b + * - "a" if a == b + */ + +/** + * @param {number[]} nums + * @return {string[]} + */ +var summaryRanges = function(nums) { + const result = []; + for (let i = 0, n = nums[0]; i < nums.length; i++) { + if (nums[i] + 1 !== nums[i + 1]) { + result.push(nums[i] === n ? `${n}` : `${n}->${nums[i]}`); + n = nums[i + 1]; + } + } + return result; +}; diff --git a/README.md b/README.md index 4916e3fe..7322dca2 100644 --- a/README.md +++ b/README.md @@ -197,6 +197,7 @@ 220|[Contains Duplicate III](./0220-contains-duplicate-iii.js)|Hard| 225|[Implement Stack using Queues](./0225-implement-stack-using-queues.js)|Easy| 226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy| +228|[Summary Ranges](./0228-summary-ranges.js)|Easy| 229|[Majority Element II](./0229-majority-element-ii.js)|Medium| 231|[Power of Two](./0231-power-of-two.js)|Easy| 232|[Implement Queue using Stacks](./0232-implement-queue-using-stacks.js)|Easy| From 48f0a995e7457e6b72754791d08385ce5212e37e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 5 Feb 2025 17:23:56 -0600 Subject: [PATCH 586/919] Add solution #257 --- 0257-binary-tree-paths.js | 37 +++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 38 insertions(+) create mode 100644 0257-binary-tree-paths.js diff --git a/0257-binary-tree-paths.js b/0257-binary-tree-paths.js new file mode 100644 index 00000000..77bfd625 --- /dev/null +++ b/0257-binary-tree-paths.js @@ -0,0 +1,37 @@ +/** + * 257. Binary Tree Paths + * https://leetcode.com/problems/binary-tree-paths/ + * Difficulty: Easy + * + * Given the root of a binary tree, return all root-to-leaf paths in any order. + * + * A leaf is a node with no children. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {string[]} + */ +var binaryTreePaths = function(root) { + return tranverse(root); +}; + +function tranverse(node, path = [], result = []) { + if (!node) return; + path.push(node.val.toString()); + if (!node.left && !node.right) { + result.push(path.join('->')); + } else { + tranverse(node.left, path.slice(), result); + tranverse(node.right, path.slice(), result); + } + return result; +} diff --git a/README.md b/README.md index 7322dca2..3a01096d 100644 --- a/README.md +++ b/README.md @@ -206,6 +206,7 @@ 237|[Delete Node in a Linked List](./0237-delete-node-in-a-linked-list.js)|Easy| 238|[Product of Array Except Self](./0238-product-of-array-except-self.js)|Medium| 242|[Valid Anagram](./0242-valid-anagram.js)|Easy| +257|[Binary Tree Paths](./0257-binary-tree-paths.js)|Easy| 258|[Add Digits](./0258-add-digits.js)|Easy| 260|[Single Number III](./0260-single-number-iii.js)|Medium| 263|[Ugly Number](./0263-ugly-number.js)|Easy| From d2886553ec80d018a97a8d9d80d6486d707c423f Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 6 Feb 2025 17:21:44 -0600 Subject: [PATCH 587/919] Add solution #174 --- 0174-dungeon-game.js | 47 ++++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 48 insertions(+) create mode 100644 0174-dungeon-game.js diff --git a/0174-dungeon-game.js b/0174-dungeon-game.js new file mode 100644 index 00000000..f6154e01 --- /dev/null +++ b/0174-dungeon-game.js @@ -0,0 +1,47 @@ +/** + * 174. Dungeon Game + * https://leetcode.com/problems/dungeon-game/ + * Difficulty: Hard + * + * The demons had captured the princess and imprisoned her in the bottom-right corner of a dungeon. + * The dungeon consists of m x n rooms laid out in a 2D grid. Our valiant knight was initially + * positioned in the top-left room and must fight his way through dungeon to rescue the princess. + * + * The knight has an initial health point represented by a positive integer. If at any point his + * health point drops to 0 or below, he dies immediately. + * + * Some of the rooms are guarded by demons (represented by negative integers), so the knight loses + * health upon entering these rooms; other rooms are either empty (represented as 0) or contain + * magic orbs that increase the knight's health (represented by positive integers). + * + * To reach the princess as quickly as possible, the knight decides to move only rightward or + * downward in each step. + * + * Return the knight's minimum initial health so that he can rescue the princess. + * + * Note that any room can contain threats or power-ups, even the first room the knight enters and + * the bottom-right room where the princess is imprisoned. + */ + +/** + * @param {number[][]} dungeon + * @return {number} + */ +var calculateMinimumHP = function(dungeon) { + const dp = new Array(dungeon.length).fill(0).map(() => new Array(dungeon[0].length).fill(0)); + return traverse(dungeon, dungeon.length, dungeon[0].length, 0, 0, dp); +}; + +function traverse(dungeon, i, j, row, col, dp) { + if (row === i - 1 && col === j - 1) { + return Math.max(1, 1 - dungeon[row][col]); + } else if (row >= i || col >= j) { + return Infinity; + } else if (dp[row][col]) { + return dp[row][col]; + } + const right = traverse(dungeon, i, j, row, col + 1, dp); + const down = traverse(dungeon, i, j, row + 1, col, dp); + dp[row][col] = Math.max(1, Math.min(right, down) - dungeon[row][col]); + return dp[row][col]; +}; diff --git a/README.md b/README.md index 3a01096d..74d8267c 100644 --- a/README.md +++ b/README.md @@ -171,6 +171,7 @@ 171|[Excel Sheet Column Number](./0171-excel-sheet-column-number.js)|Easy| 172|[Factorial Trailing Zeroes](./0172-factorial-trailing-zeroes.js)|Medium| 173|[Binary Search Tree Iterator](./0173-binary-search-tree-iterator.js)|Medium| +174|[Dungeon Game](./0174-dungeon-game.js)|Hard| 179|[Largest Number](./0179-largest-number.js)|Medium| 187|[Repeated DNA Sequences](./0187-repeated-dna-sequences.js)|Medium| 189|[Rotate Array](./0189-rotate-array.js)|Medium| From d71d0bffd88c72e46544ebbe4ce95cdff5f82741 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 6 Feb 2025 17:22:29 -0600 Subject: [PATCH 588/919] Add solution #222 --- 0222-count-complete-tree-nodes.js | 29 +++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 30 insertions(+) create mode 100644 0222-count-complete-tree-nodes.js diff --git a/0222-count-complete-tree-nodes.js b/0222-count-complete-tree-nodes.js new file mode 100644 index 00000000..cfdb28f2 --- /dev/null +++ b/0222-count-complete-tree-nodes.js @@ -0,0 +1,29 @@ +/** + * 222. Count Complete Tree Nodes + * https://leetcode.com/problems/count-complete-tree-nodes/ + * Difficulty: Easy + * + * Given the root of a complete binary tree, return the number of the nodes in the tree. + * + * According to Wikipedia, every level, except possibly the last, is completely filled + * in a complete binary tree, and all nodes in the last level are as far left as possible. + * It can have between 1 and 2h nodes inclusive at the last level h. + * + * Design an algorithm that runs in less than O(n) time complexity. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number} + */ +var countNodes = function(root) { + return !root ? 0 : 1 + countNodes(root.left) + countNodes(root.right); +}; diff --git a/README.md b/README.md index 74d8267c..766514c4 100644 --- a/README.md +++ b/README.md @@ -196,6 +196,7 @@ 217|[Contains Duplicate](./0217-contains-duplicate.js)|Easy| 219|[Contains Duplicate II](./0219-contains-duplicate-ii.js)|Easy| 220|[Contains Duplicate III](./0220-contains-duplicate-iii.js)|Hard| +222|[Count Complete Tree Nodes](./0222-count-complete-tree-nodes.js)|Easy| 225|[Implement Stack using Queues](./0225-implement-stack-using-queues.js)|Easy| 226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy| 228|[Summary Ranges](./0228-summary-ranges.js)|Easy| From bfc35170a48cbcb194829bb4f6c9096340fa41ae Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 6 Feb 2025 17:23:14 -0600 Subject: [PATCH 589/919] Add solution #1726 --- 1726-tuple-with-same-product.js | 29 +++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 30 insertions(+) create mode 100644 1726-tuple-with-same-product.js diff --git a/1726-tuple-with-same-product.js b/1726-tuple-with-same-product.js new file mode 100644 index 00000000..ac3d1a77 --- /dev/null +++ b/1726-tuple-with-same-product.js @@ -0,0 +1,29 @@ +/** + * 1726. Tuple with Same Product + * https://leetcode.com/problems/tuple-with-same-product/ + * Difficulty: Medium + * + * Given an array nums of distinct positive integers, return the number of tuples (a, b, c, d) + * such that a * b = c * d where a, b, c, and d are elements of nums, and a != b != c != d. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var tupleSameProduct = function(nums) { + const map = new Map(); + let count = 0; + + for (let i = 0; i < nums.length; i++) { + for (let j = i + 1; j < nums.length; j++) { + map.set(nums[i] * nums[j], map.get(nums[i] * nums[j]) + 1 || 1); + } + } + + Array.from(map).forEach(([key, value]) => { + count += value > 1 ? value * (value - 1) / 2 : 0; + }); + + return count * 8; +}; diff --git a/README.md b/README.md index 766514c4..ba9eeffe 100644 --- a/README.md +++ b/README.md @@ -463,6 +463,7 @@ 1672|[Richest Customer Wealth](./1672-richest-customer-wealth.js)|Easy| 1679|[Max Number of K-Sum Pairs](./1679-max-number-of-k-sum-pairs.js)|Medium| 1716|[Calculate Money in Leetcode Bank](./1716-calculate-money-in-leetcode-bank.js)|Easy| +1726|[Tuple with Same Product](./1726-tuple-with-same-product.js)|Medium| 1732|[Find the Highest Altitude](./1732-find-the-highest-altitude.js)|Easy| 1748|[Sum of Unique Elements](./1748-sum-of-unique-elements.js)|Easy| 1752|[Check if Array Is Sorted and Rotated](./1752-check-if-array-is-sorted-and-rotated.js)|Easy| From 961a634a4d543e98742909b97890f5da98a8248b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 6 Feb 2025 17:24:16 -0600 Subject: [PATCH 590/919] Add solution #208 --- 0208-implement-trie-prefix-tree.js | 68 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 69 insertions(+) create mode 100644 0208-implement-trie-prefix-tree.js diff --git a/0208-implement-trie-prefix-tree.js b/0208-implement-trie-prefix-tree.js new file mode 100644 index 00000000..aea64c26 --- /dev/null +++ b/0208-implement-trie-prefix-tree.js @@ -0,0 +1,68 @@ +/** + * 208. Implement Trie (Prefix Tree) + * https://leetcode.com/problems/implement-trie-prefix-tree/ + * Difficulty: Medium + * + * A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store + * and retrieve keys in a dataset of strings. There are various applications of this data structure, + * such as autocomplete and spellchecker. + * + * Implement the Trie class: + * - Trie() Initializes the trie object. + * - void insert(String word) Inserts the string word into the trie. + * - boolean search(String word) Returns true if the string word is in the trie (i.e., was inserted + * before), and false otherwise. + * - boolean startsWith(String prefix) Returns true if there is a previously inserted string word + * that has the prefix prefix, and false otherwise. + */ + +var Trie = function() { + this.root = {}; +}; + +/** + * @param {string} word + * @return {void} + */ +Trie.prototype.insert = function(word) { + let node = this.root; + for (const char of word) { + if (!node[char]) { + node[char] = {}; + } + node = node[char]; + } + node.isWord = true; +}; + +/** + * @param {string} word + * @return {boolean} + */ +Trie.prototype.search = function(word) { + const node = this.find(word); + return node != null && node.isWord === true; +}; + +/** + * @param {string} prefix + * @return {boolean} + */ +Trie.prototype.startsWith = function(prefix) { + return this.find(prefix) !== null; +}; + +/** + * @param {string} word + * @return {boolean} + */ +Trie.prototype.find = function(word) { + let node = this.root; + for (const char of word) { + node = node[char]; + if (!node) { + return null; + } + } + return node; +}; diff --git a/README.md b/README.md index ba9eeffe..ad65613d 100644 --- a/README.md +++ b/README.md @@ -187,6 +187,7 @@ 205|[Isomorphic Strings](./0205-isomorphic-strings.js)|Easy| 206|[Reverse Linked List](./0206-reverse-linked-list.js)|Easy| 207|[Course Schedule](./0207-course-schedule.js)|Medium| +208|[Implement Trie (Prefix Tree)](./0208-implement-trie-prefix-tree.js)|Medium| 209|[Minimum Size Subarray Sum](./0209-minimum-size-subarray-sum.js)|Medium| 211|[Design Add and Search Words Data Structure](./0211-design-add-and-search-words-data-structure.js)|Medium| 213|[House Robber II](./0213-house-robber-ii.js)|Medium| From 432e36bfb5045cd890a3db96a5860b40207c9388 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 6 Feb 2025 17:24:52 -0600 Subject: [PATCH 591/919] Add solution #282 --- 0282-expression-add-operators.js | 42 ++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 43 insertions(+) create mode 100644 0282-expression-add-operators.js diff --git a/0282-expression-add-operators.js b/0282-expression-add-operators.js new file mode 100644 index 00000000..03e8b631 --- /dev/null +++ b/0282-expression-add-operators.js @@ -0,0 +1,42 @@ +/** + * 282. Expression Add Operators + * https://leetcode.com/problems/expression-add-operators/ + * Difficulty: Hard + * + * Given a string num that contains only digits and an integer target, return all possibilities + * to insert the binary operators '+', '-', and/or '*' between the digits of num so that the + * resultant expression evaluates to the target value. + * + * Note that operands in the returned expressions should not contain leading zeros. + */ + +/** + * @param {string} num + * @param {number} target + * @return {string[]} + */ +var addOperators = function(num, target) { + const result = []; + backtrack('', 0, 0, 0); + return result; + + function backtrack(expression, sum, prev, start) { + if (start === num.length && sum === target) { + result.push(expression); + return; + } + for (let i = start, str = ''; i < num.length; i++) { + str += num[i]; + const n = Number(str); + if (!start) { + backtrack(str, n, n, i + 1); + if (str === '0') return; + continue; + } + backtrack(expression + '*' + n, sum - prev + prev * n, prev * n, i + 1); + backtrack(expression + '+' + n, sum + n, n, i + 1); + backtrack(expression + '-' + n, sum - n, -n, i + 1); + if (str === '0') return; + } + } +}; diff --git a/README.md b/README.md index ad65613d..5db44c09 100644 --- a/README.md +++ b/README.md @@ -218,6 +218,7 @@ 273|[Integer to English Words](./0273-integer-to-english-words.js)|Hard| 274|[H-Index](./0274-h-index.js)|Medium| 278|[First Bad Version](./0278-first-bad-version.js)|Medium| +282|[Expression Add Operators](./0282-expression-add-operators.js)|Hard| 283|[Move Zeroes](./0283-move-zeroes.js)|Easy| 290|[Word Pattern](./0290-word-pattern.js)|Easy| 295|[Find Median from Data Stream](./0295-find-median-from-data-stream.js)|Hard| From 590f3da327c2f297154efc7f8cfd843de43a8d3a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 7 Feb 2025 00:27:51 -0600 Subject: [PATCH 592/919] Add solution #399 --- 0399-evaluate-division.js | 49 +++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 50 insertions(+) create mode 100644 0399-evaluate-division.js diff --git a/0399-evaluate-division.js b/0399-evaluate-division.js new file mode 100644 index 00000000..086c9609 --- /dev/null +++ b/0399-evaluate-division.js @@ -0,0 +1,49 @@ +/** + * 399. Evaluate Division + * https://leetcode.com/problems/evaluate-division/ + * Difficulty: Medium + * + * You are given an array of variable pairs equations and an array of real numbers values, + * where equations[i] = [Ai, Bi] and values[i] represent the equation Ai / Bi = values[i]. + * Each Ai or Bi is a string that represents a single variable. + * + * You are also given some queries, where queries[j] = [Cj, Dj] represents the jth query + * where you must find the answer for Cj / Dj = ?. + * + * Return the answers to all queries. If a single answer cannot be determined, return -1.0. + * + * Note: The input is always valid. You may assume that evaluating the queries will not + * result in division by zero and that there is no contradiction. + * + * Note: The variables that do not occur in the list of equations are undefined, so the + * answer cannot be determined for them. + */ + +/** + * @param {string[][]} equations + * @param {number[]} values + * @param {string[][]} queries + * @return {number[]} + */ +var calcEquation = function(equations, values, queries) { + const map = equations.reduce((result, [a, b], index) => { + result.set(a, [...(result.get(a) ?? []), [b, values[index]]]); + result.set(b, [...(result.get(b) ?? []), [a, 1 / values[index]]]); + return result; + }, new Map()); + + function traverse([a, b], seen = new Set(), current = 1) { + if (!map.has(a) || !map.has(b)) return -1; + if (a === b) return current; + seen.add(a); + + for (const [key, value] of map.get(a)) { + if (seen.has(key)) continue; + const result = traverse([key, b], seen, current * value); + if (result) return result; + } + return null; + } + + return queries.map(item => traverse(item) ?? -1); +}; diff --git a/README.md b/README.md index 5db44c09..ac19cb24 100644 --- a/README.md +++ b/README.md @@ -244,6 +244,7 @@ 392|[Is Subsequence](./0392-is-subsequence.js)|Easy| 394|[Decode String](./0394-decode-string.js)|Medium| 395|[Longest Substring with At Least K Repeating Characters](./0395-longest-substring-with-at-least-k-repeating-characters.js)|Medium| +399|[Evaluate Division](./0399-evaluate-division.js)|Medium| 405|[Convert a Number to Hexadecimal](./0405-convert-a-number-to-hexadecimal.js)|Easy| 407|[Trapping Rain Water II](./0407-trapping-rain-water-ii.js)|Hard| 412|[Fizz Buzz](./0412-fizz-buzz.js)|Easy| From 43fad560c8e2c1fc5223dfdcee5f88b4843f7c6a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 7 Feb 2025 00:28:44 -0600 Subject: [PATCH 593/919] Add solution #3160 --- ...mber-of-distinct-colors-among-the-balls.js | 40 +++++++++++++++++++ README.md | 1 + 2 files changed, 41 insertions(+) create mode 100644 3160-find-the-number-of-distinct-colors-among-the-balls.js diff --git a/3160-find-the-number-of-distinct-colors-among-the-balls.js b/3160-find-the-number-of-distinct-colors-among-the-balls.js new file mode 100644 index 00000000..7c339e85 --- /dev/null +++ b/3160-find-the-number-of-distinct-colors-among-the-balls.js @@ -0,0 +1,40 @@ +/** + * 3160. Find the Number of Distinct Colors Among the Balls + * https://leetcode.com/problems/find-the-number-of-distinct-colors-among-the-balls/ + * Difficulty: Medium + * + * You are given an integer limit and a 2D array queries of size n x 2. + * + * There are limit + 1 balls with distinct labels in the range [0, limit]. Initially, + * all balls are uncolored. For every query in queries that is of the form [x, y], + * you mark ball x with the color y. After each query, you need to find the number + * of distinct colors among the balls. + * + * Return an array result of length n, where result[i] denotes the number of distinct + * colors after ith query. + * + * Note that when answering a query, lack of a color will not be considered as a color. + */ + +/** + * @param {number} limit + * @param {number[][]} queries + * @return {number[]} + */ +var queryResults = function(limit, queries) { + const result = []; + + for (let i = 0, colors = new Map(), counts = new Map(); i < queries.length; i++) { + const [index, color] = queries[i]; + if (colors.has(index)) { + const prev = colors.get(index); + counts.set(prev, counts.get(prev) - 1); + if (!counts.get(prev)) counts.delete(prev); + } + colors.set(index, color); + counts.set(color, (counts.get(color) ?? 0) + 1); + result.push(counts.size); + } + + return result; +}; diff --git a/README.md b/README.md index ac19cb24..dec09a3c 100644 --- a/README.md +++ b/README.md @@ -567,6 +567,7 @@ 3105|[Longest Strictly Increasing or Strictly Decreasing Subarray](./3105-longest-strictly-increasing-or-strictly-decreasing-subarray.js)|Easy| 3110|[Score of a String](./3110-score-of-a-string.js)|Easy| 3151|[Special Array I](./3151-special-array-i.js)|Easy| +3160|[Find the Number of Distinct Colors Among the Balls](./3160-find-the-number-of-distinct-colors-among-the-balls.js)|Medium| 3223|[Minimum Length of String After Operations](./3223-minimum-length-of-string-after-operations.js)|Medium| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| 3396|[Minimum Number of Operations to Make Elements in Array Distinct](./3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy| From 957a5d16d7f89df660b352a80f4f1e838c1983b8 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 7 Feb 2025 00:29:18 -0600 Subject: [PATCH 594/919] Add solution #1137 --- 1137-n-th-tribonacci-number.js | 25 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 26 insertions(+) create mode 100644 1137-n-th-tribonacci-number.js diff --git a/1137-n-th-tribonacci-number.js b/1137-n-th-tribonacci-number.js new file mode 100644 index 00000000..5f3a7bb8 --- /dev/null +++ b/1137-n-th-tribonacci-number.js @@ -0,0 +1,25 @@ +/** + * 1137. N-th Tribonacci Number + * https://leetcode.com/problems/n-th-tribonacci-number/ + * Difficulty: Easy + * + * The Tribonacci sequence Tn is defined as follows: + * + * T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0. + * + * Given n, return the value of Tn. + */ + +/** + * @param {number} n + * @return {number} + */ +var tribonacci = function(n) { + const nums = [0, 1, 1]; + + for (let i = 3; i <= n; i++) { + nums.push(nums[i - 3] + nums[i - 2] + nums[i - 1]); + } + + return nums[n]; +}; diff --git a/README.md b/README.md index dec09a3c..9b6598b6 100644 --- a/README.md +++ b/README.md @@ -381,6 +381,7 @@ 1103|[Distribute Candies to People](./1103-distribute-candies-to-people.js)|Easy| 1108|[Defanging an IP Address](./1108-defanging-an-ip-address.js)|Easy| 1122|[Relative Sort Array](./1122-relative-sort-array.js)|Easy| +1137|[N-th Tribonacci Number](./1137-n-th-tribonacci-number.js)|Easy| 1161|[Maximum Level Sum of a Binary Tree](./1161-maximum-level-sum-of-a-binary-tree.js)|Medium| 1189|[Maximum Number of Balloons](./1189-maximum-number-of-balloons.js)|Easy| 1200|[Minimum Absolute Difference](./1200-minimum-absolute-difference.js)|Easy| From 2c942116f1fdef846eb7d4d06a972fd3d1248237 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 7 Feb 2025 00:29:48 -0600 Subject: [PATCH 595/919] Add solution #1448 --- 1448-count-good-nodes-in-binary-tree.js | 28 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 29 insertions(+) create mode 100644 1448-count-good-nodes-in-binary-tree.js diff --git a/1448-count-good-nodes-in-binary-tree.js b/1448-count-good-nodes-in-binary-tree.js new file mode 100644 index 00000000..35911a35 --- /dev/null +++ b/1448-count-good-nodes-in-binary-tree.js @@ -0,0 +1,28 @@ +/** + * 1448. Count Good Nodes in Binary Tree + * https://leetcode.com/problems/count-good-nodes-in-binary-tree/ + * Difficulty: Medium + * + * Given a binary tree root, a node X in the tree is named good if in the path from + * root to X there are no nodes with a value greater than X. + * + * Return the number of good nodes in the 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) + * } + */ +/** + * @param {TreeNode} root + * @return {number} + */ +var goodNodes = function(root, max = -Infinity) { + if (!root) return 0; + const n = root.val >= max ? 1 : 0; + return n + goodNodes(root.left, n ? root.val : max) + goodNodes(root.right, n ? root.val : max); +}; diff --git a/README.md b/README.md index 9b6598b6..b0fe77fd 100644 --- a/README.md +++ b/README.md @@ -432,6 +432,7 @@ 1443|[Minimum Time to Collect All Apples in a Tree](./1443-minimum-time-to-collect-all-apples-in-a-tree.js)|Medium| 1446|[Consecutive Characters](./1446-consecutive-characters.js)|Easy| 1447|[Simplified Fractions](./1447-simplified-fractions.js)|Medium| +1448|[Count Good Nodes in Binary Tree](./1448-count-good-nodes-in-binary-tree.js)|Medium| 1450|[Number of Students Doing Homework at a Given Time](./1450-number-of-students-doing-homework-at-a-given-time.js)|Easy| 1451|[Rearrange Words in a Sentence](./1451-rearrange-words-in-a-sentence.js)|Medium| 1455|[Check If a Word Occurs As a Prefix of Any Word in a Sentence](./1455-check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence.js)|Easy| From 5b9410f12a68ccda98d375bb6c9b23e452e3be28 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 7 Feb 2025 00:30:23 -0600 Subject: [PATCH 596/919] Add solution #437 --- 0437-path-sum-iii.js | 35 +++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 36 insertions(+) create mode 100644 0437-path-sum-iii.js diff --git a/0437-path-sum-iii.js b/0437-path-sum-iii.js new file mode 100644 index 00000000..054d8311 --- /dev/null +++ b/0437-path-sum-iii.js @@ -0,0 +1,35 @@ +/** + * 437. Path Sum III + * https://leetcode.com/problems/path-sum-iii/ + * Difficulty: Medium + * + * Given the root of a binary tree and an integer targetSum, return the number of paths where the + * sum of the values along the path equals targetSum. + * + * The path does not need to start or end at the root or a leaf, but it must go downwards + * (i.e., traveling only from parent nodes to child 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 + * @param {number} sum + * @return {number} + */ +var pathSum = function(root, sum) { + if (!root) return 0; + return (subPathSum(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum)); +}; + +function subPathSum(node, sum) { + if (!node) return 0; + const self = node.val === sum ? 1 : 0; + return self + subPathSum(node.left, sum - node.val) + subPathSum(node.right, sum - node.val); +} diff --git a/README.md b/README.md index b0fe77fd..6123a483 100644 --- a/README.md +++ b/README.md @@ -252,6 +252,7 @@ 415|[Add Strings](./0415-add-strings.js)|Easy| 419|[Battleships in a Board](./0419-battleships-in-a-board.js)|Medium| 435|[Non-overlapping Intervals](./0435-non-overlapping-intervals.js)|Medium| +437|[Path Sum III](./0437-path-sum-iii.js)|Medium| 442|[Find All Duplicates in an Array](./0442-find-all-duplicates-in-an-array.js)|Medium| 443|[String Compression](./0443-string-compression.js)|Medium| 448|[Find All Numbers Disappeared in an Array](./0448-find-all-numbers-disappeared-in-an-array.js)|Easy| From 37a79e975416132f9448724ace1bd9e718df0916 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 8 Feb 2025 14:53:46 -0600 Subject: [PATCH 597/919] Add solution #2336 --- 2336-smallest-number-in-infinite-set.js | 36 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 37 insertions(+) create mode 100644 2336-smallest-number-in-infinite-set.js diff --git a/2336-smallest-number-in-infinite-set.js b/2336-smallest-number-in-infinite-set.js new file mode 100644 index 00000000..75d6a337 --- /dev/null +++ b/2336-smallest-number-in-infinite-set.js @@ -0,0 +1,36 @@ +/** + * 2336. Smallest Number in Infinite Set + * https://leetcode.com/problems/smallest-number-in-infinite-set/ + * Difficulty: Medium + * + * You have a set which contains all positive integers [1, 2, 3, 4, 5, ...]. + * + * Implement the SmallestInfiniteSet class: + * - SmallestInfiniteSet() Initializes the SmallestInfiniteSet object to contain all + * positive integers. + * - int popSmallest() Removes and returns the smallest integer contained in the + * infinite set. + * - void addBack(int num) Adds a positive integer num back into the infinite set, + * if it is not already in the infinite set. + */ + +var SmallestInfiniteSet = function() { + this.set = new Array(1000).fill(1); +}; + +/** + * @return {number} + */ +SmallestInfiniteSet.prototype.popSmallest = function() { + const num = this.set.findIndex(n => n); + this.set[num] = 0; + return num + 1; +}; + +/** + * @param {number} num + * @return {void} + */ +SmallestInfiniteSet.prototype.addBack = function(num) { + this.set[num - 1] = 1; +}; diff --git a/README.md b/README.md index 6123a483..fef253f8 100644 --- a/README.md +++ b/README.md @@ -512,6 +512,7 @@ 2215|[Find the Difference of Two Arrays](./2215-find-the-difference-of-two-arrays.js)|Easy| 2235|[Add Two Integers](./2235-add-two-integers.js)|Easy| 2244|[Minimum Rounds to Complete All Tasks](./2244-minimum-rounds-to-complete-all-tasks.js)|Medium| +2336|[Smallest Number in Infinite Set](./2336-smallest-number-in-infinite-set.js)|Medium| 2352|[Equal Row and Column Pairs](./2352-equal-row-and-column-pairs.js)|Medium| 2390|[Removing Stars From a String](./2390-removing-stars-from-a-string.js)|Medium| 2396|[Strictly Palindromic Number](./2396-strictly-palindromic-number.js)|Medium| From dda42108bc2c619ba397b5436e0e3f86d8a40537 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 8 Feb 2025 14:55:37 -0600 Subject: [PATCH 598/919] Add solution #236 --- ...lowest-common-ancestor-of-a-binary-tree.js | 30 +++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 0236-lowest-common-ancestor-of-a-binary-tree.js diff --git a/0236-lowest-common-ancestor-of-a-binary-tree.js b/0236-lowest-common-ancestor-of-a-binary-tree.js new file mode 100644 index 00000000..54380a39 --- /dev/null +++ b/0236-lowest-common-ancestor-of-a-binary-tree.js @@ -0,0 +1,30 @@ +/** + * 236. Lowest Common Ancestor of a Binary Tree + * https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/ + * Difficulty: Medium + * + * Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. + * + * According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined + * between two nodes p and q as the lowest node in T that has both p and q as descendants + * (where we allow a node to be a descendant of itself).” + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ +/** + * @param {TreeNode} root + * @param {TreeNode} p + * @param {TreeNode} q + * @return {TreeNode} + */ +var lowestCommonAncestor = function(root, p, q) { + if (!root || root === p || root === q) return root; + const [l, r] = [lowestCommonAncestor(root.left, p, q), lowestCommonAncestor(root.right, p, q)]; + return l && r ? root : l ?? r; +}; diff --git a/README.md b/README.md index fef253f8..090f4eec 100644 --- a/README.md +++ b/README.md @@ -206,6 +206,7 @@ 232|[Implement Queue using Stacks](./0232-implement-queue-using-stacks.js)|Easy| 234|[Palindrome Linked List](./0234-palindrome-linked-list.js)|Easy| 235|[Lowest Common Ancestor of a Binary Search Tree](./0235-lowest-common-ancestor-of-a-binary-search-tree.js)|Easy| +236|[Lowest Common Ancestor of a Binary Tree](./0236-lowest-common-ancestor-of-a-binary-tree.js)|Medium| 237|[Delete Node in a Linked List](./0237-delete-node-in-a-linked-list.js)|Easy| 238|[Product of Array Except Self](./0238-product-of-array-except-self.js)|Medium| 242|[Valid Anagram](./0242-valid-anagram.js)|Easy| From 069d81edb914583f26640b4540d8fe16b17c4f00 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 8 Feb 2025 14:56:16 -0600 Subject: [PATCH 599/919] Add solution #434 --- 0434-number-of-segments-in-a-string.js | 17 +++++++++++++++++ README.md | 1 + 2 files changed, 18 insertions(+) create mode 100644 0434-number-of-segments-in-a-string.js diff --git a/0434-number-of-segments-in-a-string.js b/0434-number-of-segments-in-a-string.js new file mode 100644 index 00000000..931f1c75 --- /dev/null +++ b/0434-number-of-segments-in-a-string.js @@ -0,0 +1,17 @@ +/** + * 434. Number of Segments in a String + * https://leetcode.com/problems/number-of-segments-in-a-string/ + * Difficulty: Easy + * + * Given a string s, return the number of segments in the string. + * + * A segment is defined to be a contiguous sequence of non-space characters. + */ + +/** + * @param {string} s + * @return {number} + */ +var countSegments = function(s) { + return s.split(/\s+/).filter(s => s).length; +}; diff --git a/README.md b/README.md index 090f4eec..16727173 100644 --- a/README.md +++ b/README.md @@ -252,6 +252,7 @@ 414|[Third Maximum Number](./0414-third-maximum-number.js)|Easy| 415|[Add Strings](./0415-add-strings.js)|Easy| 419|[Battleships in a Board](./0419-battleships-in-a-board.js)|Medium| +434|[Number of Segments in a String](./0434-number-of-segments-in-a-string.js)|Easy| 435|[Non-overlapping Intervals](./0435-non-overlapping-intervals.js)|Medium| 437|[Path Sum III](./0437-path-sum-iii.js)|Medium| 442|[Find All Duplicates in an Array](./0442-find-all-duplicates-in-an-array.js)|Medium| From fc075d1801bf1a2f9f307dac4b0816dce7b9d83c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 8 Feb 2025 14:56:53 -0600 Subject: [PATCH 600/919] Add solution #404 --- 0404-sum-of-left-leaves.js | 28 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 29 insertions(+) create mode 100644 0404-sum-of-left-leaves.js diff --git a/0404-sum-of-left-leaves.js b/0404-sum-of-left-leaves.js new file mode 100644 index 00000000..718eb970 --- /dev/null +++ b/0404-sum-of-left-leaves.js @@ -0,0 +1,28 @@ +/** + * 404. Sum of Left Leaves + * https://leetcode.com/problems/sum-of-left-leaves/ + * Difficulty: Easy + * + * Given the root of a binary tree, return the sum of all left leaves. + * + * A leaf is a node with no children. A left leaf is a leaf that is the left child of another node. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @param {TreeNode} include + * @return {number} + */ +var sumOfLeftLeaves = function(root, include) { + if (!root) return 0; + if (!root.left && !root.right && include) return root.val; + return sumOfLeftLeaves(root.left, true) + sumOfLeftLeaves(root.right); +}; diff --git a/README.md b/README.md index 16727173..76ee39cd 100644 --- a/README.md +++ b/README.md @@ -246,6 +246,7 @@ 394|[Decode String](./0394-decode-string.js)|Medium| 395|[Longest Substring with At Least K Repeating Characters](./0395-longest-substring-with-at-least-k-repeating-characters.js)|Medium| 399|[Evaluate Division](./0399-evaluate-division.js)|Medium| +404|[Sum of Left Leaves](./0404-sum-of-left-leaves.js)|Easy| 405|[Convert a Number to Hexadecimal](./0405-convert-a-number-to-hexadecimal.js)|Easy| 407|[Trapping Rain Water II](./0407-trapping-rain-water-ii.js)|Hard| 412|[Fizz Buzz](./0412-fizz-buzz.js)|Easy| From ce236f256307479b757f2ee215b3c25a5411dca9 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 8 Feb 2025 14:57:58 -0600 Subject: [PATCH 601/919] Add solution #2349 --- 2349-design-a-number-container-system.js | 50 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 51 insertions(+) create mode 100644 2349-design-a-number-container-system.js diff --git a/2349-design-a-number-container-system.js b/2349-design-a-number-container-system.js new file mode 100644 index 00000000..51a9cf77 --- /dev/null +++ b/2349-design-a-number-container-system.js @@ -0,0 +1,50 @@ +/** + * 2349. Design a Number Container System + * https://leetcode.com/problems/design-a-number-container-system/ + * Difficulty: Medium + * + * Design a number container system that can do the following: + * - Insert or Replace a number at the given index in the system. + * - Return the smallest index for the given number in the system. + * + * Implement the NumberContainers class: + * - NumberContainers() Initializes the number container system. + * - void change(int index, int number) Fills the container at index with the number. + * If there is already a number at that index, replace it. + * - int find(int number) Returns the smallest index for the given number, or -1 if + * there is no index that is filled by number in the system. + */ + +var NumberContainers = function() { + this.indexMap = new Map(); + this.lookup = new Map(); +}; + +/** + * @param {number} index + * @param {number} number + * @return {void} + */ +NumberContainers.prototype.change = function(index, number) { + this.indexMap.set(index, number); + this.getQueue(number).enqueue(index); +}; + +/** + * @param {number} number + * @return {number} + */ +NumberContainers.prototype.find = function(number) { + const queue = this.getQueue(number); + while (queue.size() && this.indexMap.get(queue.front()) !== number) { + queue.dequeue(); + } + return queue.size() ? queue.front() : -1; +}; + +NumberContainers.prototype.getQueue = function(number) { + if (!this.lookup.has(number)) { + this.lookup.set(number, new PriorityQueue({ compare: (a, b) => a - b })); + } + return this.lookup.get(number); +}; diff --git a/README.md b/README.md index 76ee39cd..d768a9f5 100644 --- a/README.md +++ b/README.md @@ -516,6 +516,7 @@ 2235|[Add Two Integers](./2235-add-two-integers.js)|Easy| 2244|[Minimum Rounds to Complete All Tasks](./2244-minimum-rounds-to-complete-all-tasks.js)|Medium| 2336|[Smallest Number in Infinite Set](./2336-smallest-number-in-infinite-set.js)|Medium| +2349|[Design a Number Container System](./2349-design-a-number-container-system.js)|Medium| 2352|[Equal Row and Column Pairs](./2352-equal-row-and-column-pairs.js)|Medium| 2390|[Removing Stars From a String](./2390-removing-stars-from-a-string.js)|Medium| 2396|[Strictly Palindromic Number](./2396-strictly-palindromic-number.js)|Medium| From f5a653dcf57ee8953fcc26f91c5694551f6fc4a7 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 9 Feb 2025 17:48:24 -0600 Subject: [PATCH 602/919] Add solution #2364 --- 2364-count-number-of-bad-pairs.js | 26 ++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 27 insertions(+) create mode 100644 2364-count-number-of-bad-pairs.js diff --git a/2364-count-number-of-bad-pairs.js b/2364-count-number-of-bad-pairs.js new file mode 100644 index 00000000..8064aa0e --- /dev/null +++ b/2364-count-number-of-bad-pairs.js @@ -0,0 +1,26 @@ +/** + * 2364. Count Number of Bad Pairs + * https://leetcode.com/problems/count-number-of-bad-pairs/ + * Difficulty: Medium + * + * You are given a 0-indexed integer array nums. A pair of indices (i, j) is a bad pair + * if i < j and j - i != nums[j] - nums[i]. + * + * Return the total number of bad pairs in nums. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var countBadPairs = function(nums) { + const map = new Map(); + let result = nums.length * (nums.length - 1) / 2; + + nums.forEach((n, i) => { + result -= map.get(n - i) ?? 0; + map.set(n - i, (map.get(n - i) ?? 0) + 1); + }); + + return result; +}; diff --git a/README.md b/README.md index d768a9f5..2c939904 100644 --- a/README.md +++ b/README.md @@ -518,6 +518,7 @@ 2336|[Smallest Number in Infinite Set](./2336-smallest-number-in-infinite-set.js)|Medium| 2349|[Design a Number Container System](./2349-design-a-number-container-system.js)|Medium| 2352|[Equal Row and Column Pairs](./2352-equal-row-and-column-pairs.js)|Medium| +2364|[Count Number of Bad Pairs](./2364-count-number-of-bad-pairs.js)|Medium| 2390|[Removing Stars From a String](./2390-removing-stars-from-a-string.js)|Medium| 2396|[Strictly Palindromic Number](./2396-strictly-palindromic-number.js)|Medium| 2413|[Smallest Even Multiple](./2413-smallest-even-multiple.js)|Easy| From 029e8fdb5d2db22ff7738f99ead2d0174420a336 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 10 Feb 2025 16:22:12 -0600 Subject: [PATCH 603/919] Add solution #3174 --- 3174-clear-digits.js | 30 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 3174-clear-digits.js diff --git a/3174-clear-digits.js b/3174-clear-digits.js new file mode 100644 index 00000000..29e1c1b7 --- /dev/null +++ b/3174-clear-digits.js @@ -0,0 +1,30 @@ +/** + * 3174. Clear Digits + * https://leetcode.com/problems/clear-digits/ + * Difficulty: Easy + * + * You are given a string s. + * + * Your task is to remove all digits by doing this operation repeatedly: + * - Delete the first digit and the closest non-digit character to its left. + * + * Return the resulting string after removing all digits. + */ + +/** + * @param {string} s + * @return {string} + */ +var clearDigits = function(s) { + const stack = []; + + for (const character of s) { + if (!isNaN(character) && stack.length) { + stack.pop(); + } else { + stack.push(character); + } + } + + return stack.join(''); +}; diff --git a/README.md b/README.md index 2c939904..2488404c 100644 --- a/README.md +++ b/README.md @@ -577,6 +577,7 @@ 3110|[Score of a String](./3110-score-of-a-string.js)|Easy| 3151|[Special Array I](./3151-special-array-i.js)|Easy| 3160|[Find the Number of Distinct Colors Among the Balls](./3160-find-the-number-of-distinct-colors-among-the-balls.js)|Medium| +3174|[Clear Digits](./3174-clear-digits.js)|Easy| 3223|[Minimum Length of String After Operations](./3223-minimum-length-of-string-after-operations.js)|Medium| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| 3396|[Minimum Number of Operations to Make Elements in Array Distinct](./3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy| From 2e4136fe63319dc88db98f3a2099f880b33d164e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 10 Feb 2025 16:23:04 -0600 Subject: [PATCH 604/919] Add solution #352 --- 0352-data-stream-as-disjoint-intervals.js | 46 +++++++++++++++++++++++ README.md | 1 + 2 files changed, 47 insertions(+) create mode 100644 0352-data-stream-as-disjoint-intervals.js diff --git a/0352-data-stream-as-disjoint-intervals.js b/0352-data-stream-as-disjoint-intervals.js new file mode 100644 index 00000000..d6667dd0 --- /dev/null +++ b/0352-data-stream-as-disjoint-intervals.js @@ -0,0 +1,46 @@ +/** + * 352. Data Stream as Disjoint Intervals + * https://leetcode.com/problems/data-stream-as-disjoint-intervals/ + * Difficulty: Hard + * + * Given a data stream input of non-negative integers a1, a2, ..., an, summarize the + * numbers seen so far as a list of disjoint intervals. + * + * Implement the SummaryRanges class: + * - SummaryRanges() Initializes the object with an empty stream. + * - void addNum(int value) Adds the integer value to the stream. + * - int[][] getIntervals() Returns a summary of the integers in the stream currently as + * a list of disjoint intervals [starti, endi]. The answer should be sorted by starti. + */ + +var SummaryRanges = function() { + this.list = []; +}; + +/** + * @param {number} value + * @return {void} + */ +SummaryRanges.prototype.addNum = function(value) { + this.list[value] = true; +}; + +/** + * @return {number[][]} + */ +SummaryRanges.prototype.getIntervals = function() { + const result = []; + + for (let i = 0; i < this.list.length; i++) { + if (this.list[i]) { + let j = i; + while (this.list[j]) { + j++; + } + result.push([i, j - 1]); + i = j; + } + } + + return result; +}; diff --git a/README.md b/README.md index 2488404c..441fdbd1 100644 --- a/README.md +++ b/README.md @@ -235,6 +235,7 @@ 347|[Top K Frequent Elements](./0347-top-k-frequent-elements.js)|Medium| 349|[Intersection of Two Arrays](./0349-intersection-of-two-arrays.js)|Easy| 350|[Intersection of Two Arrays II](./0350-intersection-of-two-arrays-ii.js)|Easy| +352|[Data Stream as Disjoint Intervals](./0352-data-stream-as-disjoint-intervals.js)|Hard| 367|[Valid Perfect Square](./0367-valid-perfect-square.js)|Easy| 371|[Sum of Two Integers](./0371-sum-of-two-integers.js)|Medium| 372|[Super Pow](./0372-super-pow.js)|Medium| From 2085304bff909f33c1a8abd3beaff5101e698cbd Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 10 Feb 2025 16:28:09 -0600 Subject: [PATCH 605/919] Add solution #233 --- 0233-number-of-digit-one.js | 26 ++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 27 insertions(+) create mode 100644 0233-number-of-digit-one.js diff --git a/0233-number-of-digit-one.js b/0233-number-of-digit-one.js new file mode 100644 index 00000000..3c82a1d6 --- /dev/null +++ b/0233-number-of-digit-one.js @@ -0,0 +1,26 @@ +/** + * 233. Number of Digit One + * https://leetcode.com/problems/number-of-digit-one/ + * Difficulty: Hard + * + * Given an integer n, count the total number of digit 1 appearing in all non-negative + * integers less than or equal to n. + */ + +/** + * @param {number} n + * @return {number} + */ +var countDigitOne = function(n) { + if (n <= 0) { + return 0; + } else if (n < 10) { + return 1; + } + + const base = 10 ** (n.toString().length - 1); + const answer = parseInt(n / base); + + return countDigitOne(base - 1) * answer + + (answer === 1 ? (n - base + 1) : base) + countDigitOne(n % base); +}; diff --git a/README.md b/README.md index 441fdbd1..f982fa4e 100644 --- a/README.md +++ b/README.md @@ -204,6 +204,7 @@ 229|[Majority Element II](./0229-majority-element-ii.js)|Medium| 231|[Power of Two](./0231-power-of-two.js)|Easy| 232|[Implement Queue using Stacks](./0232-implement-queue-using-stacks.js)|Easy| +233|[Number of Digit One](./0233-number-of-digit-one.js)|Hard| 234|[Palindrome Linked List](./0234-palindrome-linked-list.js)|Easy| 235|[Lowest Common Ancestor of a Binary Search Tree](./0235-lowest-common-ancestor-of-a-binary-search-tree.js)|Easy| 236|[Lowest Common Ancestor of a Binary Tree](./0236-lowest-common-ancestor-of-a-binary-tree.js)|Medium| From 13f874c69c252a6b0fb595a5acba7b74d4035301 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 10 Feb 2025 16:32:31 -0600 Subject: [PATCH 606/919] Add solution #275 --- 0275-h-index-ii.js | 34 ++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 0275-h-index-ii.js diff --git a/0275-h-index-ii.js b/0275-h-index-ii.js new file mode 100644 index 00000000..0b515c77 --- /dev/null +++ b/0275-h-index-ii.js @@ -0,0 +1,34 @@ +/** + * 275. H-Index II + * https://leetcode.com/problems/h-index-ii/ + * Difficulty: Medium + * + * Given an array of integers citations where citations[i] is the number of citations a + * researcher received for their ith paper and citations is sorted in ascending order, + * return the researcher's h-index. + * + * According to the definition of h-index on Wikipedia: The h-index is defined as the + * maximum value of h such that the given researcher has published at least h papers + * that have each been cited at least h times. + * + * You must write an algorithm that runs in logarithmic time. + */ + +/** + * @param {number[]} citations + * @return {number} + */ +var hIndex = function(citations) { + let start = 0; + + for (let end = citations.length - 1; start <= end;) { + const middle = Math.floor((start + end) / 2); + if (citations.length - middle - 1 < citations[middle]) { + end = middle - 1; + } else { + start = middle + 1; + } + } + + return citations.length - start; +}; diff --git a/README.md b/README.md index f982fa4e..29c60a8a 100644 --- a/README.md +++ b/README.md @@ -219,6 +219,7 @@ 268|[Missing Number](./0268-missing-number.js)|Easy| 273|[Integer to English Words](./0273-integer-to-english-words.js)|Hard| 274|[H-Index](./0274-h-index.js)|Medium| +275|[H-Index II](./0275-h-index-ii.js)|Medium| 278|[First Bad Version](./0278-first-bad-version.js)|Medium| 282|[Expression Add Operators](./0282-expression-add-operators.js)|Hard| 283|[Move Zeroes](./0283-move-zeroes.js)|Easy| From cc969f257d80616cfb67593e8e77dd16d1fda486 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 11 Feb 2025 17:50:10 -0600 Subject: [PATCH 607/919] Add solution #1910 --- 1910-remove-all-occurrences-of-a-substring.js | 25 +++++++++++++++++++ README.md | 1 + 2 files changed, 26 insertions(+) create mode 100644 1910-remove-all-occurrences-of-a-substring.js diff --git a/1910-remove-all-occurrences-of-a-substring.js b/1910-remove-all-occurrences-of-a-substring.js new file mode 100644 index 00000000..6f8a8f4e --- /dev/null +++ b/1910-remove-all-occurrences-of-a-substring.js @@ -0,0 +1,25 @@ +/** + * 1910. Remove All Occurrences of a Substring + * https://leetcode.com/problems/remove-all-occurrences-of-a-substring/ + * Difficulty: Medium + * + * Given two strings s and part, perform the following operation on s until all occurrences of + * the substring part are removed: + * - Find the leftmost occurrence of the substring part and remove it from s. + * + * Return s after removing all occurrences of part. + * + * A substring is a contiguous sequence of characters in a string. + */ + +/** + * @param {string} s + * @param {string} part + * @return {string} + */ +var removeOccurrences = function(s, part) { + while (s.includes(part)) { + s = s.replace(part, ''); + } + return s; +}; diff --git a/README.md b/README.md index 29c60a8a..21e7717d 100644 --- a/README.md +++ b/README.md @@ -492,6 +492,7 @@ 1833|[Maximum Ice Cream Bars](./1833-maximum-ice-cream-bars.js)|Medium| 1880|[Check if Word Equals Summation of Two Words](./1880-check-if-word-equals-summation-of-two-words.js)|Easy| 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| +1910|[Remove All Occurrences of a Substring](./1910-remove-all-occurrences-of-a-substring.js)|Medium| 1920|[Build Array from Permutation](./1920-build-array-from-permutation.js)|Easy| 1929|[Concatenation of Array](./1929-concatenation-of-array.js)|Easy| 1935|[Maximum Number of Words You Can Type](./1935-maximum-number-of-words-you-can-type.js)|Easy| From 4816671589926d198354c42734d97221371b1bbf Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 11 Feb 2025 17:51:28 -0600 Subject: [PATCH 608/919] Add solution #1372 --- 1372-longest-zigzag-path-in-a-binary-tree.js | 47 ++++++++++++++++++++ README.md | 1 + 2 files changed, 48 insertions(+) create mode 100644 1372-longest-zigzag-path-in-a-binary-tree.js diff --git a/1372-longest-zigzag-path-in-a-binary-tree.js b/1372-longest-zigzag-path-in-a-binary-tree.js new file mode 100644 index 00000000..57b9d818 --- /dev/null +++ b/1372-longest-zigzag-path-in-a-binary-tree.js @@ -0,0 +1,47 @@ +/** + * 1372. Longest ZigZag Path in a Binary Tree + * https://leetcode.com/problems/longest-zigzag-path-in-a-binary-tree/ + * Difficulty: Medium + * + * You are given the root of a binary tree. + * + * A ZigZag path for a binary tree is defined as follow: + * - Choose any node in the binary tree and a direction (right or left). + * - If the current direction is right, move to the right child of the current node; + * otherwise, move to the left child. + * - Change the direction from right to left or from left to right. + * - Repeat the second and third steps until you can't move in the tree. + * + * Zigzag length is defined as the number of nodes visited - 1. (A single node has a + * length of 0). + * + * Return the longest ZigZag path contained in that 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) + * } + */ +/** + * @param {TreeNode} root + * @return {number} + */ +var longestZigZag = function(root) { + let result = 0; + + dfs(root, true, 0); + dfs(root, false, 0); + + return result; + + function dfs(node, isLeft, total) { + if (!node) return; + result = Math.max(result, total); + dfs(node.left, true, isLeft ? 1 : total + 1); + dfs(node.right, false, isLeft ? total + 1 : 1); + } +}; diff --git a/README.md b/README.md index 21e7717d..eabb30d2 100644 --- a/README.md +++ b/README.md @@ -426,6 +426,7 @@ 1365|[How Many Numbers Are Smaller Than the Current Number](./1365-how-many-numbers-are-smaller-than-the-current-number.js)|Easy| 1366|[Rank Teams by Votes](./1366-rank-teams-by-votes.js)|Medium| 1368|[Minimum Cost to Make at Least One Valid Path in a Grid](./1368-minimum-cost-to-make-at-least-one-valid-path-in-a-grid.js)|Hard| +1372|[Longest ZigZag Path in a Binary Tree](./1372-longest-zigzag-path-in-a-binary-tree.js)|Medium| 1374|[Generate a String With Characters That Have Odd Counts](./1374-generate-a-string-with-characters-that-have-odd-counts.js)|Easy| 1380|[Lucky Numbers in a Matrix](./1380-lucky-numbers-in-a-matrix.js)|Easy| 1389|[Create Target Array in the Given Order](./1389-create-target-array-in-the-given-order.js)|Easy| From c03ea0729ebc639728ccebe962c289368e6c6321 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 11 Feb 2025 17:52:28 -0600 Subject: [PATCH 609/919] Add solution #450 --- 0450-delete-node-in-a-bst.js | 48 ++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 49 insertions(+) create mode 100644 0450-delete-node-in-a-bst.js diff --git a/0450-delete-node-in-a-bst.js b/0450-delete-node-in-a-bst.js new file mode 100644 index 00000000..5fe0c158 --- /dev/null +++ b/0450-delete-node-in-a-bst.js @@ -0,0 +1,48 @@ +/** + * 450. Delete Node in a BST + * https://leetcode.com/problems/delete-node-in-a-bst/ + * Difficulty: Medium + * + * Given a root node reference of a BST and a key, delete the node with the given key in + * the BST. Return the root node reference (possibly updated) of the BST. + * + * Basically, the deletion can be divided into two stages: + * 1. Search for a node to remove. + * 2. If the node is found, delete the node. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @param {number} key + * @return {TreeNode} + */ +var deleteNode = function(root, key) { + if (!root) return root; + if (root.val < key) { + root.right = deleteNode(root.right, key); + } else if (root.val > key) { + root.left = deleteNode(root.left, key); + } else { + if (root.left === null) { + return root.right; + } else if (root.right === null) { + return root.left; + } else { + let node = root.right; + while (node.left) { + node = node.left; + } + node.left = root.left; + return root.right; + } + } + return root; +}; diff --git a/README.md b/README.md index eabb30d2..f95c39f9 100644 --- a/README.md +++ b/README.md @@ -262,6 +262,7 @@ 442|[Find All Duplicates in an Array](./0442-find-all-duplicates-in-an-array.js)|Medium| 443|[String Compression](./0443-string-compression.js)|Medium| 448|[Find All Numbers Disappeared in an Array](./0448-find-all-numbers-disappeared-in-an-array.js)|Easy| +450|[Delete Node in a BST](./0450-delete-node-in-a-bst.js)|Medium| 451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| 452|[Minimum Number of Arrows to Burst Balloons](./0452-minimum-number-of-arrows-to-burst-balloons.js)|Medium| 456|[132 Pattern](./0456-132-pattern.js)|Medium| From faf7635d5c0522baf236200b4680354da9abe34a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 11 Feb 2025 17:53:12 -0600 Subject: [PATCH 610/919] Add solution #589 --- 0589-n-ary-tree-preorder-traversal.js | 26 ++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 27 insertions(+) create mode 100644 0589-n-ary-tree-preorder-traversal.js diff --git a/0589-n-ary-tree-preorder-traversal.js b/0589-n-ary-tree-preorder-traversal.js new file mode 100644 index 00000000..3e6e5259 --- /dev/null +++ b/0589-n-ary-tree-preorder-traversal.js @@ -0,0 +1,26 @@ +/** + * 589. N-ary Tree Preorder Traversal + * https://leetcode.com/problems/n-ary-tree-preorder-traversal/ + * Difficulty: Easy + * + * Given the root of an n-ary tree, return the preorder traversal of its nodes' values. + * + * Nary-Tree input serialization is represented in their level order traversal. Each group + * of children is separated by the null value (See examples) + */ + +/** + * // Definition for a _Node. + * function _Node(val, children) { + * this.val = val; + * this.children = children; + * }; + */ + +/** + * @param {_Node|null} root + * @return {number[]} + */ +var preorder = function(root) { + return !root ? [] : [root.val, ...root.children.flatMap(n => preorder(n))]; +}; diff --git a/README.md b/README.md index f95c39f9..210a0be1 100644 --- a/README.md +++ b/README.md @@ -295,6 +295,7 @@ 566|[Reshape the Matrix](./0566-reshape-the-matrix.js)|Easy| 567|[Permutation in String](./0567-permutation-in-string.js)|Medium| 575|[Distribute Candies](./0575-distribute-candies.js)|Easy| +589|[N-ary Tree Preorder Traversal](./0589-n-ary-tree-preorder-traversal.js)|Easy| 594|[Longest Harmonious Subsequence](./0594-longest-harmonious-subsequence.js)|Easy| 599|[Minimum Index Sum of Two Lists](./0599-minimum-index-sum-of-two-lists.js)|Easy| 605|[Can Place Flowers](./0605-can-place-flowers.js)|Easy| From 08e305f7e48d9e2aec43a325f97f6e62a7beb43b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 11 Feb 2025 17:53:58 -0600 Subject: [PATCH 611/919] Add solution #1268 --- 1268-search-suggestions-system.js | 30 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 1268-search-suggestions-system.js diff --git a/1268-search-suggestions-system.js b/1268-search-suggestions-system.js new file mode 100644 index 00000000..1ab450a9 --- /dev/null +++ b/1268-search-suggestions-system.js @@ -0,0 +1,30 @@ +/** + * 1268. Search Suggestions System + * https://leetcode.com/problems/search-suggestions-system/ + * Difficulty: Medium + * + * You are given an array of strings products and a string searchWord. + * + * Design a system that suggests at most three product names from products after each + * character of searchWord is typed. Suggested products should have common prefix with + * searchWord. If there are more than three products with a common prefix return the + * three lexicographically minimums products. + * + * Return a list of lists of the suggested products after each character of searchWord + * is typed. + */ + +/** + * @param {string[]} products + * @param {string} searchWord + * @return {string[][]} + */ +var suggestedProducts = function(products, searchWord) { + products.sort(); + const result = new Array(searchWord.length); + for (let i = 0; i < searchWord.length; i++) { + products = products.filter((word) => word[i] === searchWord[i]); + result[i] = products.slice(0, 3); + } + return result; +}; diff --git a/README.md b/README.md index 210a0be1..2503a28d 100644 --- a/README.md +++ b/README.md @@ -403,6 +403,7 @@ 1249|[Minimum Remove to Make Valid Parentheses](./1249-minimum-remove-to-make-valid-parentheses.js)|Medium| 1252|[Cells with Odd Values in a Matrix](./1252-cells-with-odd-values-in-a-matrix.js)|Easy| 1267|[Count Servers that Communicate](./1267-count-servers-that-communicate.js)|Medium| +1268|[Search Suggestions System](./1268-search-suggestions-system.js)|Medium| 1287|[Element Appearing More Than 25% In Sorted Array](./1287-element-appearing-more-than-25-in-sorted-array.js)|Easy| 1290|[Convert Binary Number in a Linked List to Integer](./1290-convert-binary-number-in-a-linked-list-to-integer.js)|Easy| 1291|[Sequential Digits](./1291-sequential-digits.js)|Medium| From 327d7dd2985055bb419d7d9827cf9006a9355d8e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 12 Feb 2025 17:42:09 -0600 Subject: [PATCH 612/919] Add solution #224 --- 0224-basic-calculator.js | 45 ++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 46 insertions(+) create mode 100644 0224-basic-calculator.js diff --git a/0224-basic-calculator.js b/0224-basic-calculator.js new file mode 100644 index 00000000..8bb532ac --- /dev/null +++ b/0224-basic-calculator.js @@ -0,0 +1,45 @@ +/** + * 224. Basic Calculator + * https://leetcode.com/problems/basic-calculator/ + * Difficulty: Hard + * + * Given a string s representing a valid expression, implement a basic calculator to + * evaluate it, and return the result of the evaluation. + * + * Note: You are not allowed to use any built-in function which evaluates strings as + * mathematical expressions, such as eval(). + */ + +/** + * @param {string} s + * @return {number} + */ +var calculate = function(s) { + const stack = []; + let result = 0; + + for (let i = 0, sign = 1; i < s.length; i += 1) { + if (s[i] >= '0' && s[i] <= '9') { + let value = 0; + while (s[i] >= '0' && s[i] <= '9') { + value = (value * 10) + (s[i] - '0'); + i += 1; + } + result += value * sign; + i -= 1; + } else if (s[i] === '+') { + sign = 1; + } else if (s[i] === '-') { + sign = -1; + } else if (s[i] === '(') { + stack.push(result, sign); + result = 0; + sign = 1; + } else if (s[i] === ')') { + result = stack.pop() * result; + result += stack.pop(); + } + } + + return result; +}; diff --git a/README.md b/README.md index 2503a28d..ce76b5a7 100644 --- a/README.md +++ b/README.md @@ -198,6 +198,7 @@ 219|[Contains Duplicate II](./0219-contains-duplicate-ii.js)|Easy| 220|[Contains Duplicate III](./0220-contains-duplicate-iii.js)|Hard| 222|[Count Complete Tree Nodes](./0222-count-complete-tree-nodes.js)|Easy| +224|[Basic Calculator](./0224-basic-calculator.js)|Hard| 225|[Implement Stack using Queues](./0225-implement-stack-using-queues.js)|Easy| 226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy| 228|[Summary Ranges](./0228-summary-ranges.js)|Easy| From ab80e13418a8ea1bf4bbf229b85306af20e31df0 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 12 Feb 2025 17:46:08 -0600 Subject: [PATCH 613/919] Add solution #2300 --- ...-successful-pairs-of-spells-and-potions.js | 44 +++++++++++++++++++ README.md | 1 + 2 files changed, 45 insertions(+) create mode 100644 2300-successful-pairs-of-spells-and-potions.js diff --git a/2300-successful-pairs-of-spells-and-potions.js b/2300-successful-pairs-of-spells-and-potions.js new file mode 100644 index 00000000..eb0fa04f --- /dev/null +++ b/2300-successful-pairs-of-spells-and-potions.js @@ -0,0 +1,44 @@ +/** + * 2300. Successful Pairs of Spells and Potions + * https://leetcode.com/problems/successful-pairs-of-spells-and-potions/ + * Difficulty: Medium + * + * You are given two positive integer arrays spells and potions, of length n and m respectively, + * where spells[i] represents the strength of the ith spell and potions[j] represents the strength + * of the jth potion. + * + * You are also given an integer success. A spell and potion pair is considered successful if the + * product of their strengths is at least success. + * + * Return an integer array pairs of length n where pairs[i] is the number of potions that will form + * a successful pair with the ith spell. + */ + +/** + * @param {number[]} spells + * @param {number[]} potions + * @param {number} success + * @return {number[]} + */ +var successfulPairs = function(spells, potions, success) { + const result = []; + potions.sort((a, b) => a - b); + + for (let i = 0; i < spells.length; i++) { + let left = 0; + let right = potions.length - 1; + + while (left <= right) { + const mid = Math.floor((left + right) / 2); + if (spells[i] * potions[mid] < success) { + left = mid + 1; + } else { + right = mid - 1; + } + } + + result[i] = potions.length - left; + } + + return result; +}; diff --git a/README.md b/README.md index ce76b5a7..69bc8ac4 100644 --- a/README.md +++ b/README.md @@ -524,6 +524,7 @@ 2215|[Find the Difference of Two Arrays](./2215-find-the-difference-of-two-arrays.js)|Easy| 2235|[Add Two Integers](./2235-add-two-integers.js)|Easy| 2244|[Minimum Rounds to Complete All Tasks](./2244-minimum-rounds-to-complete-all-tasks.js)|Medium| +2300|[Successful Pairs of Spells and Potions](./2300-successful-pairs-of-spells-and-potions.js)|Medium| 2336|[Smallest Number in Infinite Set](./2336-smallest-number-in-infinite-set.js)|Medium| 2349|[Design a Number Container System](./2349-design-a-number-container-system.js)|Medium| 2352|[Equal Row and Column Pairs](./2352-equal-row-and-column-pairs.js)|Medium| From b263166072abe1157ad7b33ead1e2fa5ca01d420 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 12 Feb 2025 17:47:21 -0600 Subject: [PATCH 614/919] Add solution #2542 --- 2542-maximum-subsequence-score.js | 44 +++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 45 insertions(+) create mode 100644 2542-maximum-subsequence-score.js diff --git a/2542-maximum-subsequence-score.js b/2542-maximum-subsequence-score.js new file mode 100644 index 00000000..83b1106e --- /dev/null +++ b/2542-maximum-subsequence-score.js @@ -0,0 +1,44 @@ +/** + * 2542. Maximum Subsequence Score + * https://leetcode.com/problems/maximum-subsequence-score/ + * Difficulty: Medium + * + * You are given two 0-indexed integer arrays nums1 and nums2 of equal length n and a positive + * integer k. You must choose a subsequence of indices from nums1 of length k. + * + * For chosen indices i0, i1, ..., ik - 1, your score is defined as: + * - The sum of the selected elements from nums1 multiplied with the minimum of the selected + * elements from nums2. + * - It can defined simply as: (nums1[i0] + nums1[i1] +...+ nums1[ik - 1]) * min(nums2[i0], + * nums2[i1], ... ,nums2[ik - 1]). + * + * Return the maximum possible score. + * + * A subsequence of indices of an array is a set that can be derived from the set {0, 1, ..., n-1} + * by deleting some or no elements. + */ + +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @param {number} k + * @return {number} + */ +var maxScore = function(nums1, nums2, k) { + const zipped = nums1.map((num1, i) => [num1, nums2[i]]).sort((a, b) => b[1] - a[1]); + const heap = new MinPriorityQueue(); + let result = 0; + let sum = 0; + + for (const [num, min] of zipped) { + heap.enqueue(num); + sum += num; + + if (heap.size() == k) { + result = Math.max(result, sum * min); + sum -= heap.dequeue().element; + } + } + + return result; +}; diff --git a/README.md b/README.md index 69bc8ac4..2fb3f676 100644 --- a/README.md +++ b/README.md @@ -541,6 +541,7 @@ 2493|[Divide Nodes Into the Maximum Number of Groups](./2493-divide-nodes-into-the-maximum-number-of-groups.js)|Hard| 2529|[Maximum Count of Positive Integer and Negative Integer](./2529-maximum-count-of-positive-integer-and-negative-integer.js)|Easy| 2535|[Difference Between Element Sum and Digit Sum of an Array](./2535-difference-between-element-sum-and-digit-sum-of-an-array.js)|Easy| +2542|[Maximum Subsequence Score](./2542-maximum-subsequence-score.js)|Medium| 2618|[Check if Object Instance of Class](./2618-check-if-object-instance-of-class.js)|Medium| 2619|[Array Prototype Last](./2619-array-prototype-last.js)|Easy| 2620|[Counter](./2620-counter.js)|Easy| From 852a9d8ab92ebe52f21cdf2c8538c2462eec596c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 12 Feb 2025 17:48:29 -0600 Subject: [PATCH 615/919] Add solution #717 --- 0717-1-bit-and-2-bit-characters.js | 20 ++++++++++++++++++++ README.md | 1 + 2 files changed, 21 insertions(+) create mode 100644 0717-1-bit-and-2-bit-characters.js diff --git a/0717-1-bit-and-2-bit-characters.js b/0717-1-bit-and-2-bit-characters.js new file mode 100644 index 00000000..77312827 --- /dev/null +++ b/0717-1-bit-and-2-bit-characters.js @@ -0,0 +1,20 @@ +/** + * 717. 1-bit and 2-bit Characters + * https://leetcode.com/problems/1-bit-and-2-bit-characters/ + * Difficulty: Easy + * + * We have two special characters: + * - The first character can be represented by one bit 0. + * - The second character can be represented by two bits (10 or 11). + * + * Given a binary array bits that ends with 0, return true if the last character + * must be a one-bit character. + */ + +/** + * @param {number[]} bits + * @return {boolean} + */ +var isOneBitCharacter = function(bits) { + return bits.slice(0, bits.length - 1).join('').replace(/11|10|0/g, '') !== '1'; +}; diff --git a/README.md b/README.md index 2fb3f676..680dffdd 100644 --- a/README.md +++ b/README.md @@ -324,6 +324,7 @@ 705|[Design HashSet](./0705-design-hashset.js)|Easy| 706|[Design HashMap](./0706-design-hashmap.js)|Easy| 713|[Subarray Product Less Than K](./0713-subarray-product-less-than-k.js)|Medium| +717|[1-bit and 2-bit Characters](./0717-1-bit-and-2-bit-characters.js)|Easy| 720|[Longest Word in Dictionary](./0720-longest-word-in-dictionary.js)|Medium| 722|[Remove Comments](./0722-remove-comments.js)|Medium| 724|[Find Pivot Index](./0724-find-pivot-index.js)|Easy| From ad0a74cf89b9e695804788e97466a140a4f25884 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 12 Feb 2025 17:49:23 -0600 Subject: [PATCH 616/919] Add solution #2342 --- ...-sum-of-a-pair-with-equal-sum-of-digits.js | 28 +++++++++++++++++++ README.md | 1 + 2 files changed, 29 insertions(+) create mode 100644 2342-max-sum-of-a-pair-with-equal-sum-of-digits.js diff --git a/2342-max-sum-of-a-pair-with-equal-sum-of-digits.js b/2342-max-sum-of-a-pair-with-equal-sum-of-digits.js new file mode 100644 index 00000000..3bc0ca1d --- /dev/null +++ b/2342-max-sum-of-a-pair-with-equal-sum-of-digits.js @@ -0,0 +1,28 @@ +/** + * 2342. Max Sum of a Pair With Equal Sum of Digits + * https://leetcode.com/problems/max-sum-of-a-pair-with-equal-sum-of-digits/ + * Difficulty: Medium + * + * You are given a 0-indexed array nums consisting of positive integers. You can choose two + * indices i and j, such that i != j, and the sum of digits of the number nums[i] is equal + * to that of nums[j]. + * + * Return the maximum value of nums[i] + nums[j] that you can obtain over all possible indices + * i and j that satisfy the conditions. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var maximumSum = function(nums) { + const map = new Map(); + + return nums.reduce((result, n) => { + const key = n.toString().split('').reduce((sum, n) => +n + sum, 0); + result = !map.has(key) ? result : Math.max(result, n + map.get(key)); + map.set(key, Math.max(map.get(key) ?? 0, n)); + + return result; + }, -1); +}; diff --git a/README.md b/README.md index 680dffdd..c9be732e 100644 --- a/README.md +++ b/README.md @@ -527,6 +527,7 @@ 2244|[Minimum Rounds to Complete All Tasks](./2244-minimum-rounds-to-complete-all-tasks.js)|Medium| 2300|[Successful Pairs of Spells and Potions](./2300-successful-pairs-of-spells-and-potions.js)|Medium| 2336|[Smallest Number in Infinite Set](./2336-smallest-number-in-infinite-set.js)|Medium| +2342|[Max Sum of a Pair With Equal Sum of Digits](./2342-max-sum-of-a-pair-with-equal-sum-of-digits.js)|Medium| 2349|[Design a Number Container System](./2349-design-a-number-container-system.js)|Medium| 2352|[Equal Row and Column Pairs](./2352-equal-row-and-column-pairs.js)|Medium| 2364|[Count Number of Bad Pairs](./2364-count-number-of-bad-pairs.js)|Medium| From e2c4574a54540b37cecebbdd6a2c50f8d47b701e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 13 Feb 2025 15:47:35 -0600 Subject: [PATCH 617/919] Add solution #875 --- 0875-koko-eating-bananas.js | 42 +++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 43 insertions(+) create mode 100644 0875-koko-eating-bananas.js diff --git a/0875-koko-eating-bananas.js b/0875-koko-eating-bananas.js new file mode 100644 index 00000000..68ee313c --- /dev/null +++ b/0875-koko-eating-bananas.js @@ -0,0 +1,42 @@ +/** + * 875. Koko Eating Bananas + * https://leetcode.com/problems/koko-eating-bananas/ + * Difficulty: Medium + * + * 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. + */ + +/** + * @param {number[]} piles + * @param {number} h + * @return {number} + */ +var minEatingSpeed = function(piles, h) { + const fn = speed => piles.reduce((sum, pile) => sum + Math.ceil(pile / speed), 0); + let min = 1; + let max = Math.max(...piles); + let result = max; + + while (min <= max) { + const middle = Math.floor((min + max) / 2); + + if (fn(middle) <= h) { + result = middle; + max = middle - 1; + } else { + min = middle + 1; + } + } + + return result; +}; diff --git a/README.md b/README.md index c9be732e..46852c57 100644 --- a/README.md +++ b/README.md @@ -354,6 +354,7 @@ 867|[Transpose Matrix](./0867-transpose-matrix.js)|Easy| 868|[Binary Gap](./0868-binary-gap.js)|Easy| 872|[Leaf-Similar Trees](./0872-leaf-similar-trees.js)|Easy| +875|[Koko Eating Bananas](./0875-koko-eating-bananas.js)|Medium| 876|[Middle of the Linked List](./0876-middle-of-the-linked-list.js)|Easy| 884|[Uncommon Words from Two Sentences](./0884-uncommon-words-from-two-sentences.js)|Easy| 890|[Find and Replace Pattern](./0890-find-and-replace-pattern.js)|Medium| From 3a677a2aa8a82cddd2b53f2ca59334a8b9dfcd54 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 13 Feb 2025 15:48:25 -0600 Subject: [PATCH 618/919] Add solution #790 --- 0790-domino-and-tromino-tiling.js | 28 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 29 insertions(+) create mode 100644 0790-domino-and-tromino-tiling.js diff --git a/0790-domino-and-tromino-tiling.js b/0790-domino-and-tromino-tiling.js new file mode 100644 index 00000000..b03ff226 --- /dev/null +++ b/0790-domino-and-tromino-tiling.js @@ -0,0 +1,28 @@ +/** + * 790. Domino and Tromino Tiling + * https://leetcode.com/problems/domino-and-tromino-tiling/ + * Difficulty: Medium + * + * 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. + */ + +/** + * @param {number} n + * @return {number} + */ +var numTilings = function(n) { + const MOD_VALUE = Math.pow(10, 9) + 7; + const dp = { 1: 1, 2: 2, 3: 5 }; + for (let i = 4; i <= n; i++) { + dp[i] = (2 * dp[i - 1] + dp[i - 3]) % MOD_VALUE; + } + return dp[n]; +}; diff --git a/README.md b/README.md index 46852c57..4f5fb751 100644 --- a/README.md +++ b/README.md @@ -339,6 +339,7 @@ 748|[Shortest Completing Word](./0748-shortest-completing-word.js)|Easy| 762|[Prime Number of Set Bits in Binary Representation](./0762-prime-number-of-set-bits-in-binary-representation.js)|Easy| 784|[Letter Case Permutation](./0784-letter-case-permutation.js)|Medium| +790|[Domino and Tromino Tiling](./0790-domino-and-tromino-tiling.js)|Medium| 791|[Custom Sort String](./0791-custom-sort-string.js)|Medium| 796|[Rotate String](./0796-rotate-string.js)|Easy| 802|[Find Eventual Safe States](./0802-find-eventual-safe-states.js)|Medium| From b813ac7d2130fcc3de7e591f7bebb9e12890dc03 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 13 Feb 2025 15:49:10 -0600 Subject: [PATCH 619/919] Add solution #3066 --- ...operations-to-exceed-threshold-value-ii.js | 35 +++++++++++++++++++ README.md | 1 + 2 files changed, 36 insertions(+) create mode 100644 3066-minimum-operations-to-exceed-threshold-value-ii.js diff --git a/3066-minimum-operations-to-exceed-threshold-value-ii.js b/3066-minimum-operations-to-exceed-threshold-value-ii.js new file mode 100644 index 00000000..cf3b9b68 --- /dev/null +++ b/3066-minimum-operations-to-exceed-threshold-value-ii.js @@ -0,0 +1,35 @@ +/** + * 3066. Minimum Operations to Exceed Threshold Value II + * https://leetcode.com/problems/minimum-operations-to-exceed-threshold-value-ii/ + * Difficulty: Medium + * + * You are given a 0-indexed integer array nums, and an integer k. + * + * You are allowed to perform some operations on nums, where in a single operation, you can: + * - Select the two smallest integers x and y from nums. + * - Remove x and y from nums. + * - Insert (min(x, y) * 2 + max(x, y)) at any position in the array. + * + * Note that you can only apply the described operation if nums contains at least two elements. + * + * Return the minimum number of operations needed so that all elements of the array are greater + * than or equal to k. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var minOperations = function(nums, k) { + const queue = new MinPriorityQueue(); + let operations = 0; + + nums.forEach(n => queue.enqueue(n)); + while (queue.size() >= 2 && queue.front().element < k) { + queue.enqueue(queue.dequeue().element * 2 + queue.dequeue().element); + operations++; + } + + return operations; +}; diff --git a/README.md b/README.md index 4f5fb751..c27c3af1 100644 --- a/README.md +++ b/README.md @@ -588,6 +588,7 @@ 2727|[Is Object Empty](./2727-is-object-empty.js)|Easy| 2948|[Make Lexicographically Smallest Array by Swapping Elements](./2948-make-lexicographically-smallest-array-by-swapping-elements.js)|Medium| 3042|[Count Prefix and Suffix Pairs I](./3042-count-prefix-and-suffix-pairs-i.js)|Easy| +3066|[Minimum Operations to Exceed Threshold Value II](./3066-minimum-operations-to-exceed-threshold-value-ii.js)|Medium| 3105|[Longest Strictly Increasing or Strictly Decreasing Subarray](./3105-longest-strictly-increasing-or-strictly-decreasing-subarray.js)|Easy| 3110|[Score of a String](./3110-score-of-a-string.js)|Easy| 3151|[Special Array I](./3151-special-array-i.js)|Easy| From 7ba557ee833f4bc05a59cc7ef578f6e8e5ebb4bd Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 13 Feb 2025 15:50:51 -0600 Subject: [PATCH 620/919] Add solution #2462 --- 2462-total-cost-to-hire-k-workers.js | 62 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 63 insertions(+) create mode 100644 2462-total-cost-to-hire-k-workers.js diff --git a/2462-total-cost-to-hire-k-workers.js b/2462-total-cost-to-hire-k-workers.js new file mode 100644 index 00000000..9f05f48b --- /dev/null +++ b/2462-total-cost-to-hire-k-workers.js @@ -0,0 +1,62 @@ +/** + * 2462. Total Cost to Hire K Workers + * https://leetcode.com/problems/total-cost-to-hire-k-workers/ + * Difficulty: Medium + * + * You are given a 0-indexed integer array costs where costs[i] is the cost of hiring + * the ith worker. + * + * You are also given two integers k and candidates. We want to hire exactly k workers + * according to the following rules: + * - You will run k sessions and hire exactly one worker in each session. + * - In each hiring session, choose the worker with the lowest cost from either the first + * candidates workers or the last candidates workers. Break the tie by the smallest index. + * - For example, if costs = [3,2,7,7,1,2] and candidates = 2, then in the first hiring + * session, we will choose the 4th worker because they have the lowest cost [3,2,7,7,1,2]. + * - In the second hiring session, we will choose 1st worker because they have the same + * lowest cost as 4th worker but they have the smallest index [3,2,7,7,2]. Please note + * that the indexing may be changed in the process. + * - If there are fewer than candidates workers remaining, choose the worker with the lowest + * cost among them. Break the tie by the smallest index. + * - A worker can only be chosen once. + * + * Return the total cost to hire exactly k workers. + */ + +/** + * @param {number[]} costs + * @param {number} k + * @param {number} candidates + * @return {number} + */ +var totalCost = function(costs, k, candidates) { + const queue = new PriorityQueue({ compare: (a, b) => { + return a[0] === b[0] ? a[1] - b[1] : a[0] - b[0]; + }}); + + costs.forEach((cost, index) => { + if (index < candidates || index >= costs.length - candidates) { + queue.enqueue([cost, index]); + } + }); + + let result = 0; + for (let i = 0, count = candidates, diff = costs.length - candidates - 1; i < k; i++) { + const worker = queue.dequeue(); + result += worker[0]; + + if (count <= diff) { + let status = null; + if (worker[1] < count) { + status = [costs[count], count]; + count++; + } else { + status = [costs[diff], diff]; + diff--; + } + queue.enqueue(status); + } + } + + return result; +}; diff --git a/README.md b/README.md index c27c3af1..10a549ab 100644 --- a/README.md +++ b/README.md @@ -539,6 +539,7 @@ 2425|[Bitwise XOR of All Pairings](./2425-bitwise-xor-of-all-pairings.js)|Medium| 2427|[Number of Common Factors](./2427-number-of-common-factors.js)|Easy| 2429|[Minimize XOR](./2429-minimize-xor.js)|Medium| +2462|[Total Cost to Hire K Workers](./2462-total-cost-to-hire-k-workers.js)|Medium| 2469|[Convert the Temperature](./2469-convert-the-temperature.js)|Easy| 2482|[Difference Between Ones and Zeros in Row and Column](./2482-difference-between-ones-and-zeros-in-row-and-column.js)|Medium| 2490|[Circular Sentence](./2490-circular-sentence.js)|Easy| From 8e1af35e67de13fe7060095218c3399b3ab43295 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 13 Feb 2025 15:51:45 -0600 Subject: [PATCH 621/919] Add solution #303 --- 0303-range-sum-query-immutable.js | 31 +++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 0303-range-sum-query-immutable.js diff --git a/0303-range-sum-query-immutable.js b/0303-range-sum-query-immutable.js new file mode 100644 index 00000000..08992907 --- /dev/null +++ b/0303-range-sum-query-immutable.js @@ -0,0 +1,31 @@ +/** + * 303. Range Sum Query - Immutable + * https://leetcode.com/problems/range-sum-query-immutable/ + * Difficulty: Easy + * + * Given an integer array nums, handle multiple queries of the following type: + * - Calculate the sum of the elements of nums between indices left and right inclusive + * where left <= right. + * + * Implement the NumArray class: + * - NumArray(int[] nums) Initializes the object with the integer array nums. + * - int sumRange(int left, int right) Returns the sum of the elements of nums between + * indices left and right inclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right]). + + */ + +/** + * @param {number[]} nums + */ +var NumArray = function(nums) { + this.nums = nums; +}; + +/** + * @param {number} left + * @param {number} right + * @return {number} + */ +NumArray.prototype.sumRange = function(left, right) { + return this.nums.slice(left, right + 1).reduce((sum, n) => sum + n, 0); +}; diff --git a/README.md b/README.md index 10a549ab..931440ab 100644 --- a/README.md +++ b/README.md @@ -226,6 +226,7 @@ 283|[Move Zeroes](./0283-move-zeroes.js)|Easy| 290|[Word Pattern](./0290-word-pattern.js)|Easy| 295|[Find Median from Data Stream](./0295-find-median-from-data-stream.js)|Hard| +303|[Range Sum Query - Immutable](./0303-range-sum-query-immutable.js)|Easy| 316|[Remove Duplicate Letters](./0316-remove-duplicate-letters.js)|Medium| 322|[Coin Change](./0322-coin-change.js)|Medium| 326|[Power of Three](./0326-power-of-three.js)|Easy| From 093916ce8d77b0af1d0e8fbb227657636f698060 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 14 Feb 2025 15:35:30 -0600 Subject: [PATCH 622/919] Add solution #292 --- 0292-nim-game.js | 22 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 0292-nim-game.js diff --git a/0292-nim-game.js b/0292-nim-game.js new file mode 100644 index 00000000..47e81093 --- /dev/null +++ b/0292-nim-game.js @@ -0,0 +1,22 @@ +/** + * 292. Nim Game + * https://leetcode.com/problems/nim-game/ + * Difficulty: Easy + * + * You are playing the following Nim Game with your friend: + * - Initially, there is a heap of stones on the table. + * - You and your friend will alternate taking turns, and you go first. + * - On each turn, the person whose turn it is will remove 1 to 3 stones from the heap. + * - The one who removes the last stone is the winner. + * + * Given n, the number of stones in the heap, return true if you can win the game assuming + * both you and your friend play optimally, otherwise return false. + */ + +/** + * @param {number} n + * @return {boolean} + */ +var canWinNim = function(n) { + return n % 4 !== 0; +}; diff --git a/README.md b/README.md index 931440ab..0e83fdaf 100644 --- a/README.md +++ b/README.md @@ -225,6 +225,7 @@ 282|[Expression Add Operators](./0282-expression-add-operators.js)|Hard| 283|[Move Zeroes](./0283-move-zeroes.js)|Easy| 290|[Word Pattern](./0290-word-pattern.js)|Easy| +292|[Nim Game](./0292-nim-game.js)|Easy| 295|[Find Median from Data Stream](./0295-find-median-from-data-stream.js)|Hard| 303|[Range Sum Query - Immutable](./0303-range-sum-query-immutable.js)|Easy| 316|[Remove Duplicate Letters](./0316-remove-duplicate-letters.js)|Medium| From 763adfe33fecc78a3801999ba623291b5505a6d4 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 14 Feb 2025 15:36:32 -0600 Subject: [PATCH 623/919] Add solution #1926 --- 1926-nearest-exit-from-entrance-in-maze.js | 45 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 46 insertions(+) create mode 100644 1926-nearest-exit-from-entrance-in-maze.js diff --git a/1926-nearest-exit-from-entrance-in-maze.js b/1926-nearest-exit-from-entrance-in-maze.js new file mode 100644 index 00000000..a9b89243 --- /dev/null +++ b/1926-nearest-exit-from-entrance-in-maze.js @@ -0,0 +1,45 @@ +/** + * 1926. Nearest Exit from Entrance in Maze + * https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/ + * Difficulty: Medium + * + * You are given an m x n matrix maze (0-indexed) with empty cells (represented as '.') and + * walls (represented as '+'). You are also given the entrance of the maze, where entrance + * = [entrancerow, entrancecol] denotes the row and column of the cell you are initially + * standing at. + * + * In one step, you can move one cell up, down, left, or right. You cannot step into a cell + * with a wall, and you cannot step outside the maze. Your goal is to find the nearest exit + * from the entrance. An exit is defined as an empty cell that is at the border of the maze. + * The entrance does not count as an exit. + * + * Return the number of steps in the shortest path from the entrance to the nearest exit, + * or -1 if no such path exists. + */ + +/** + * @param {character[][]} maze + * @param {number[]} entrance + * @return {number} + */ +var nearestExit = function(maze, entrance) { + const queue = [[entrance, 0]]; + + while (queue.length) { + const [cell, steps] = queue.shift(); + const [i, j] = cell; + if (i === maze.length || i === -1 || j === maze[0].length || j === -1 || maze[i][j] !== '.') { + continue; + } + if ((i === maze.length - 1 || i === 0 || j === maze[0].length - 1 || j === 0) && steps !== 0) { + return steps; + } + maze[i][j] = '*'; + queue.push([[i, j + 1], steps + 1]); + queue.push([[i, j - 1], steps + 1]); + queue.push([[i + 1, j], steps + 1]); + queue.push([[i - 1, j], steps + 1]); + } + + return -1; +}; diff --git a/README.md b/README.md index 0e83fdaf..7da5e268 100644 --- a/README.md +++ b/README.md @@ -504,6 +504,7 @@ 1886|[Determine Whether Matrix Can Be Obtained By Rotation](./1886-determine-whether-matrix-can-be-obtained-by-rotation.js)|Easy| 1910|[Remove All Occurrences of a Substring](./1910-remove-all-occurrences-of-a-substring.js)|Medium| 1920|[Build Array from Permutation](./1920-build-array-from-permutation.js)|Easy| +1926|[Nearest Exit from Entrance in Maze](./1926-nearest-exit-from-entrance-in-maze.js)|Medium| 1929|[Concatenation of Array](./1929-concatenation-of-array.js)|Easy| 1935|[Maximum Number of Words You Can Type](./1935-maximum-number-of-words-you-can-type.js)|Easy| 1985|[Find the Kth Largest Integer in the Array](./1985-find-the-kth-largest-integer-in-the-array.js)|Medium| From 749e4977c96b6c3755373e73b3c5a4cdcf4f4a7c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 14 Feb 2025 15:37:23 -0600 Subject: [PATCH 624/919] Add solution #1352 --- 1352-product-of-the-last-k-numbers.js | 36 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 37 insertions(+) create mode 100644 1352-product-of-the-last-k-numbers.js diff --git a/1352-product-of-the-last-k-numbers.js b/1352-product-of-the-last-k-numbers.js new file mode 100644 index 00000000..c7596e38 --- /dev/null +++ b/1352-product-of-the-last-k-numbers.js @@ -0,0 +1,36 @@ +/** + * 1352. Product of the Last K Numbers + * https://leetcode.com/problems/product-of-the-last-k-numbers/ + * Difficulty: Medium + * + * Design an algorithm that accepts a stream of integers and retrieves the product of the + * last k integers of the stream. + * + * Implement the ProductOfNumbers class: + * - ProductOfNumbers() Initializes the object with an empty stream. + * - void add(int num) Appends the integer num to the stream. + * - int getProduct(int k) Returns the product of the last k numbers in the current list. + * You can assume that always the current list has at least k numbers. + * - The test cases are generated so that, at any time, the product of any contiguous sequence + * of numbers will fit into a single 32-bit integer without overflowing. + */ + +var ProductOfNumbers = function() { + this.nums = []; +}; + +/** + * @param {number} num + * @return {void} + */ +ProductOfNumbers.prototype.add = function(num) { + this.nums.push(num); +}; + +/** + * @param {number} k + * @return {number} + */ +ProductOfNumbers.prototype.getProduct = function(k) { + return this.nums.slice(-k).reduce((product, n) => product * n, 1); +}; diff --git a/README.md b/README.md index 7da5e268..b4d3327e 100644 --- a/README.md +++ b/README.md @@ -430,6 +430,7 @@ 1333|[Filter Restaurants by Vegan-Friendly, Price and Distance](./1333-filter-restaurants-by-vegan-friendly-price-and-distance.js)|Medium| 1342|[Number of Steps to Reduce a Number to Zero](./1342-number-of-steps-to-reduce-a-number-to-zero.js)|Easy| 1351|[Count Negative Numbers in a Sorted Matrix](./1351-count-negative-numbers-in-a-sorted-matrix.js)|Easy| +1352|[Product of the Last K Numbers](./1352-product-of-the-last-k-numbers.js)|Medium| 1356|[Sort Integers by The Number of 1 Bits](./1356-sort-integers-by-the-number-of-1-bits.js)|Easy| 1360|[Number of Days Between Two Dates](./1360-number-of-days-between-two-dates.js)|Easy| 1365|[How Many Numbers Are Smaller Than the Current Number](./1365-how-many-numbers-are-smaller-than-the-current-number.js)|Easy| From 359a267f41d71e6b76dcf2c07dd67acd0914152f Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 14 Feb 2025 15:38:22 -0600 Subject: [PATCH 625/919] Add solution #1143 --- 1143-longest-common-subsequence.js | 37 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 38 insertions(+) create mode 100644 1143-longest-common-subsequence.js diff --git a/1143-longest-common-subsequence.js b/1143-longest-common-subsequence.js new file mode 100644 index 00000000..afe14e3c --- /dev/null +++ b/1143-longest-common-subsequence.js @@ -0,0 +1,37 @@ +/** + * 1143. Longest Common Subsequence + * https://leetcode.com/problems/longest-common-subsequence/ + * Difficulty: Medium + * + * Given two strings text1 and text2, return the length of their longest common subsequence. + * If there is no common subsequence, return 0. + * + * A subsequence of a string is a new string generated from the original string with some + * characters (can be none) deleted without changing the relative order of the remaining + * characters. + * + * - For example, "ace" is a subsequence of "abcde". + * + * A common subsequence of two strings is a subsequence that is common to both strings. + */ + +/** + * @param {string} text1 + * @param {string} text2 + * @return {number} + */ +var longestCommonSubsequence = function(text1, text2) { + const dp = new Array(text1.length + 1).fill(0).map(() => new Array(text2.length + 1).fill(0)); + + for (let i = 1; i <= text1.length; i++) { + for (let j = 1; j <= text2.length; j++) { + if (text1.charAt(i - 1) === text2.charAt(j - 1)) { + dp[i][j] = dp[i - 1][j - 1] + 1; + } else { + dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); + } + } + } + + return dp[text1.length][text2.length]; +}; diff --git a/README.md b/README.md index b4d3327e..409f477b 100644 --- a/README.md +++ b/README.md @@ -397,6 +397,7 @@ 1108|[Defanging an IP Address](./1108-defanging-an-ip-address.js)|Easy| 1122|[Relative Sort Array](./1122-relative-sort-array.js)|Easy| 1137|[N-th Tribonacci Number](./1137-n-th-tribonacci-number.js)|Easy| +1143|[Longest Common Subsequence](./1143-longest-common-subsequence.js)|Medium| 1161|[Maximum Level Sum of a Binary Tree](./1161-maximum-level-sum-of-a-binary-tree.js)|Medium| 1189|[Maximum Number of Balloons](./1189-maximum-number-of-balloons.js)|Easy| 1200|[Minimum Absolute Difference](./1200-minimum-absolute-difference.js)|Easy| From fe5f1a76d10b91e4684504016a48a85dd1f91e5f Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 14 Feb 2025 15:39:16 -0600 Subject: [PATCH 626/919] Add solution #714 --- ...buy-and-sell-stock-with-transaction-fee.js | 25 +++++++++++++++++++ README.md | 1 + 2 files changed, 26 insertions(+) create mode 100644 0714-best-time-to-buy-and-sell-stock-with-transaction-fee.js diff --git a/0714-best-time-to-buy-and-sell-stock-with-transaction-fee.js b/0714-best-time-to-buy-and-sell-stock-with-transaction-fee.js new file mode 100644 index 00000000..07a1c9e8 --- /dev/null +++ b/0714-best-time-to-buy-and-sell-stock-with-transaction-fee.js @@ -0,0 +1,25 @@ +/** + * 714. Best Time to Buy and Sell Stock with Transaction Fee + * https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/ + * Difficulty: Medium + * + * You are given an array prices where prices[i] is the price of a given stock on the ith day, + * and an integer fee representing a transaction fee. + * + * Find the maximum profit you can achieve. You may complete as many transactions as you like, + * but you need to pay the transaction fee for each transaction. + */ + +/** + * @param {number[]} prices + * @param {number} fee + * @return {number} + */ +var maxProfit = function(prices, fee) { + let result = 0; + for (let i = 1, sell = -prices[0]; i < prices.length; i++) { + result = Math.max(result, sell + prices[i] - fee); + sell = Math.max(sell, result - prices[i]); + } + return result; +}; diff --git a/README.md b/README.md index 409f477b..aebacabd 100644 --- a/README.md +++ b/README.md @@ -326,6 +326,7 @@ 705|[Design HashSet](./0705-design-hashset.js)|Easy| 706|[Design HashMap](./0706-design-hashmap.js)|Easy| 713|[Subarray Product Less Than K](./0713-subarray-product-less-than-k.js)|Medium| +714|[Best Time to Buy and Sell Stock with Transaction Fee](./0714-best-time-to-buy-and-sell-stock-with-transaction-fee.js)|Medium| 717|[1-bit and 2-bit Characters](./0717-1-bit-and-2-bit-characters.js)|Easy| 720|[Longest Word in Dictionary](./0720-longest-word-in-dictionary.js)|Medium| 722|[Remove Comments](./0722-remove-comments.js)|Medium| From 4caec2f0524ec6b7f080dc27d8fc7069a7ed71a8 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 15 Feb 2025 14:17:27 -0600 Subject: [PATCH 627/919] Add solution #2698 --- ...ind-the-punishment-number-of-an-integer.js | 45 +++++++++++++++++++ README.md | 1 + 2 files changed, 46 insertions(+) create mode 100644 2698-find-the-punishment-number-of-an-integer.js diff --git a/2698-find-the-punishment-number-of-an-integer.js b/2698-find-the-punishment-number-of-an-integer.js new file mode 100644 index 00000000..98719925 --- /dev/null +++ b/2698-find-the-punishment-number-of-an-integer.js @@ -0,0 +1,45 @@ +/** + * 2698. Find the Punishment Number of an Integer + * https://leetcode.com/problems/find-the-punishment-number-of-an-integer/ + * Difficulty: Medium + * + * Given a positive integer n, return the punishment number of n. + * + * The punishment number of n is defined as the sum of the squares of all integers i such that: + * - 1 <= i <= n + * - The decimal representation of i * i can be partitioned into contiguous substrings such that + * the sum of the integer values of these substrings equals i. + */ + +/** + * @param {number} n + * @return {number} + */ +var punishmentNumber = function(n) { + function canPartition(num, target, start) { + if (!target && start === num.length) { + return true; + } else if (start >= num.length) { + return false; + } + for (let i = start, sum = 0; i < num.length; i++) { + sum = sum * 10 + +num[i]; + if (sum > target) { + break; + } else if (canPartition(num, target - sum, i + 1)) { + return true; + } + } + + return false; + } + + let result = 0; + for (let i = 1; i <= n; i++) { + if (canPartition((i * i).toString(), i, 0)) { + result += i * i; + } + } + + return result; +}; diff --git a/README.md b/README.md index aebacabd..7cd8e29f 100644 --- a/README.md +++ b/README.md @@ -582,6 +582,7 @@ 2693|[Call Function with Custom Context](./2693-call-function-with-custom-context.js)|Medium| 2694|[Event Emitter](./2694-event-emitter.js)|Medium| 2695|[Array Wrapper](./2695-array-wrapper.js)|Easy| +2698|[Find the Punishment Number of an Integer](./2698-find-the-punishment-number-of-an-integer.js)|Medium| 2703|[Return Length of Arguments Passed](./2703-return-length-of-arguments-passed.js)|Easy| 2704|[To Be Or Not To Be](./2704-to-be-or-not-to-be.js)|Easy| 2705|[Compact Object](./2705-compact-object.js)|Medium| From 044c69b6da92e11d7af18ba5fe850af15d8d4231 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 15 Feb 2025 14:18:05 -0600 Subject: [PATCH 628/919] Add solution #279 --- 0279-perfect-squares.js | 27 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 28 insertions(+) create mode 100644 0279-perfect-squares.js diff --git a/0279-perfect-squares.js b/0279-perfect-squares.js new file mode 100644 index 00000000..b9cd5dbd --- /dev/null +++ b/0279-perfect-squares.js @@ -0,0 +1,27 @@ +/** + * 279. Perfect Squares + * https://leetcode.com/problems/perfect-squares/ + * Difficulty: Medium + * + * Given an integer n, return the least number of perfect square numbers that sum to n. + * + * A perfect square is an integer that is the square of an integer; in other words, it is + * the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares + * while 3 and 11 are not. + */ + +/** + * @param {number} n + * @return {number} + */ +var numSquares = function(n) { + const dp = new Array(n + 1).fill(0).map((_, i) => !i ? 0 : Infinity); + + for (let i = 1; i <= n; i++) { + for (let j = 1; j * j <= i; j++) { + dp[i] = Math.min(dp[i], dp[i - j * j] + 1); + } + } + + return dp[n]; +}; diff --git a/README.md b/README.md index 7cd8e29f..7abe169e 100644 --- a/README.md +++ b/README.md @@ -222,6 +222,7 @@ 274|[H-Index](./0274-h-index.js)|Medium| 275|[H-Index II](./0275-h-index-ii.js)|Medium| 278|[First Bad Version](./0278-first-bad-version.js)|Medium| +279|[Perfect Squares](./0279-perfect-squares.js)|Medium| 282|[Expression Add Operators](./0282-expression-add-operators.js)|Hard| 283|[Move Zeroes](./0283-move-zeroes.js)|Easy| 290|[Word Pattern](./0290-word-pattern.js)|Easy| From e0cc81dd1b903a57428553f65ff051bd2f7cec18 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 15 Feb 2025 14:19:24 -0600 Subject: [PATCH 629/919] Add solution #289 --- 0289-game-of-life.js | 59 ++++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 60 insertions(+) create mode 100644 0289-game-of-life.js diff --git a/0289-game-of-life.js b/0289-game-of-life.js new file mode 100644 index 00000000..80160800 --- /dev/null +++ b/0289-game-of-life.js @@ -0,0 +1,59 @@ +/** + * 289. Game of Life + * https://leetcode.com/problems/game-of-life/ + * Difficulty: Medium + * + * According to Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular + * automaton devised by the British mathematician John Horton Conway in 1970." + * + * The board is made up of an m x n grid of cells, where each cell has an initial state: live + * (represented by a 1) or dead (represented by a 0). Each cell interacts with its eight neighbors + * (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia + * article): + * 1. Any live cell with fewer than two live neighbors dies as if caused by under-population. + * 2. Any live cell with two or three live neighbors lives on to the next generation. + * 3. Any live cell with more than three live neighbors dies, as if by over-population. + * 4. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction. + * + * The next state of the board is determined by applying the above rules simultaneously to every + * cell in the current state of the m x n grid board. In this process, births and deaths occur + * simultaneously. + * + * Given the current state of the board, update the board to reflect its next state. + * + * Note that you do not need to return anything. + */ + +/** + * @param {number[][]} board + * @return {void} Do not return anything, modify board in-place instead. + */ +var gameOfLife = function(board) { + const directions = [[1, -1], [1, 0], [1, 1], [0, -1], [0, 1], [-1, -1], [-1, 0], [-1, 1]]; + const r = board.length; + const c = board[0].length; + + for (let i = 0; i < r; i++) { + for (let j = 0; j < c; j++) { + let lives = 0; + for (const d of directions) { + if (d[0] + i < 0 || d[0] + i >= r || d[1] + j < 0 || d[1] + j >= c) { + continue; + } else if (board[d[0] + i][d[1] + j] === 1 || board[d[0] + i][d[1] + j] === 2) { + lives++; + } + } + if (board[i][j] === 0 && lives === 3) { + board[i][j] = 3; + } else if (board[i][j] === 1 && (lives < 2 || lives > 3)) { + board[i][j] = 2; + } + } + } + + for (let i = 0; i < r; i++) { + for (let j = 0; j < c; j++) { + board[i][j] %= 2; + } + } +}; diff --git a/README.md b/README.md index 7abe169e..44238514 100644 --- a/README.md +++ b/README.md @@ -225,6 +225,7 @@ 279|[Perfect Squares](./0279-perfect-squares.js)|Medium| 282|[Expression Add Operators](./0282-expression-add-operators.js)|Hard| 283|[Move Zeroes](./0283-move-zeroes.js)|Easy| +289|[Game of Life](./0289-game-of-life.js)|Medium| 290|[Word Pattern](./0290-word-pattern.js)|Easy| 292|[Nim Game](./0292-nim-game.js)|Easy| 295|[Find Median from Data Stream](./0295-find-median-from-data-stream.js)|Hard| From 2611d2e7488c35f3b1a7c62c5d30a2fd47e37392 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 15 Feb 2025 14:20:13 -0600 Subject: [PATCH 630/919] Add solution #306 --- 0306-additive-number.js | 45 +++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 46 insertions(+) create mode 100644 0306-additive-number.js diff --git a/0306-additive-number.js b/0306-additive-number.js new file mode 100644 index 00000000..e6255997 --- /dev/null +++ b/0306-additive-number.js @@ -0,0 +1,45 @@ +/** + * 306. Additive Number + * https://leetcode.com/problems/additive-number/ + * Difficulty: Medium + * + * An additive number is a string whose digits can form an additive sequence. + * + * A valid additive sequence should contain at least three numbers. Except for the first two + * numbers, each subsequent number in the sequence must be the sum of the preceding two. + * + * Given a string containing only digits, return true if it is an additive number or false + * otherwise. + * + * Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03 or + * 1, 02, 3 is invalid. + */ + +/** + * @param {string} num + * @param {Array} group + * @param {number} startIndex + * @return {boolean} + */ +var isAdditiveNumber = function(num, group = [], startIndex = 0) { + if (startIndex === num.length && group.length >= 3) { + return true; + } + + for (let i = startIndex; i < num.length; i++) { + if (num[startIndex] === '0' && i !== startIndex) { + break; + } + const n = +num.slice(startIndex, i + 1); + if (group[group.length - 1] + group[group.length - 2] !== n && group.length >= 2) { + continue; + } + group.push(n); + if (isAdditiveNumber(num, group, i + 1)) { + return true; + } + group.pop(); + } + + return false; +}; diff --git a/README.md b/README.md index 44238514..f046ce91 100644 --- a/README.md +++ b/README.md @@ -230,6 +230,7 @@ 292|[Nim Game](./0292-nim-game.js)|Easy| 295|[Find Median from Data Stream](./0295-find-median-from-data-stream.js)|Hard| 303|[Range Sum Query - Immutable](./0303-range-sum-query-immutable.js)|Easy| +306|[Additive Number](./0306-additive-number.js)|Medium| 316|[Remove Duplicate Letters](./0316-remove-duplicate-letters.js)|Medium| 322|[Coin Change](./0322-coin-change.js)|Medium| 326|[Power of Three](./0326-power-of-three.js)|Easy| From af29ae09e6bd0b0c7acafa6232e61c8f3c115da4 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 15 Feb 2025 14:21:03 -0600 Subject: [PATCH 631/919] Add solution #318 --- 0318-maximum-product-of-word-lengths.js | 30 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 0318-maximum-product-of-word-lengths.js diff --git a/0318-maximum-product-of-word-lengths.js b/0318-maximum-product-of-word-lengths.js new file mode 100644 index 00000000..cf95d542 --- /dev/null +++ b/0318-maximum-product-of-word-lengths.js @@ -0,0 +1,30 @@ +/** + * 318. Maximum Product of Word Lengths + * https://leetcode.com/problems/maximum-product-of-word-lengths/ + * Difficulty: Medium + * + * Given a string array words, return the maximum value of length(word[i]) * length(word[j]) + * where the two words do not share common letters. If no such two words exist, return 0. + */ + +/** + * @param {string[]} words + * @return {number} + */ +var maxProduct = function(words) { + const letters = words.map(word => Array.from(new Set(word))); + let result = 0; + + for (let i = 0; i < words.length - 1; i++) { + for (let j = i + 1; j < words.length; j++) { + if (!letters[i].some(item => letters[j].includes(item))) { + const product = words[i].length * words[j].length; + if (product > result) { + result = product; + } + } + } + } + + return result; +}; diff --git a/README.md b/README.md index f046ce91..821d6782 100644 --- a/README.md +++ b/README.md @@ -232,6 +232,7 @@ 303|[Range Sum Query - Immutable](./0303-range-sum-query-immutable.js)|Easy| 306|[Additive Number](./0306-additive-number.js)|Medium| 316|[Remove Duplicate Letters](./0316-remove-duplicate-letters.js)|Medium| +318|[Maximum Product of Word Lengths](./0318-maximum-product-of-word-lengths.js)|Medium| 322|[Coin Change](./0322-coin-change.js)|Medium| 326|[Power of Three](./0326-power-of-three.js)|Easy| 328|[Odd Even Linked List](./0328-odd-even-linked-list.js)|Medium| From 6b84f2f4fdc49025bbe6c57f2beda1fb6a67333d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 16 Feb 2025 00:45:24 -0600 Subject: [PATCH 632/919] Add solution #1207 --- 1207-unique-number-of-occurrences.js | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/1207-unique-number-of-occurrences.js b/1207-unique-number-of-occurrences.js index 35b8cacf..91b7b2f7 100644 --- a/1207-unique-number-of-occurrences.js +++ b/1207-unique-number-of-occurrences.js @@ -3,19 +3,17 @@ * https://leetcode.com/problems/unique-number-of-occurrences/ * Difficulty: Easy * - * Given an array of integers arr, write a - * function that returns true if and only - * if the number of occurrences of each - * value in the array is unique. + * Given an array of integers arr, return true if the number of occurrences of each + * value in the array is unique or false otherwise. */ /** - * @param {number[]} numbers + * @param {number[]} arr * @return {boolean} */ -var uniqueOccurrences = function(numbers) { +var uniqueOccurrences = function(arr) { const map = new Map(); - numbers.forEach(n => map.set(n, map.has(n) ? map.get(n) + 1 : 1)); + arr.forEach(n => map.set(n, map.has(n) ? map.get(n) + 1 : 1)); const occurrences = Array.from(map.values()); - return new Set(occurrences).size === occurrences.length + return new Set(occurrences).size === occurrences.length; }; From 975788505ef5d2d9d706156b76f16a5d2095d919 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 16 Feb 2025 17:24:12 -0600 Subject: [PATCH 633/919] Add solution #1718 --- ...exicographically-largest-valid-sequence.js | 64 +++++++++++++++++++ README.md | 1 + 2 files changed, 65 insertions(+) create mode 100644 1718-construct-the-lexicographically-largest-valid-sequence.js diff --git a/1718-construct-the-lexicographically-largest-valid-sequence.js b/1718-construct-the-lexicographically-largest-valid-sequence.js new file mode 100644 index 00000000..41f59cb7 --- /dev/null +++ b/1718-construct-the-lexicographically-largest-valid-sequence.js @@ -0,0 +1,64 @@ +/** + * 1718. Construct the Lexicographically Largest Valid Sequence + * https://leetcode.com/problems/construct-the-lexicographically-largest-valid-sequence/ + * Difficulty: Medium + * + * Given an integer n, find a sequence that satisfies all of the following: + * - The integer 1 occurs once in the sequence. + * - Each integer between 2 and n occurs twice in the sequence. + * - For every integer i between 2 and n, the distance between the two occurrences of i is + * exactly i. + * + * The distance between two numbers on the sequence, a[i] and a[j], is the absolute difference + * of their indices, |j - i|. + * + * Return the lexicographically largest sequence. It is guaranteed that under the given + * constraints, there is always a solution. + * + * A sequence a is lexicographically larger than a sequence b (of the same length) if in the first + * position where a and b differ, sequence a has a number greater than the corresponding number in + * b. For example, [0,1,9,0] is lexicographically larger than [0,1,5,6] because the first position + * they differ is at the third number, and 9 is greater than 5. + */ + +/** + * @param {number} n + * @return {number[]} + */ +var constructDistancedSequence = function(n) { + const result = new Array(2 * n - 1).fill(0); + const group = new Array(n + 1).fill(false); + + backtrack(0); + + function backtrack(index) { + if (index === 2 * n - 1) { + return true; + } else if (result[index] !== 0) { + return backtrack(index + 1); + } + for (let num = n; num >= 1; num--) { + if (group[num]) { + continue; + } + group[num] = true; + result[index] = num; + if (num === 1 || (index + num < 2 * n - 1 && result[index + num] === 0)) { + if (num > 1) { + result[index + num] = num; + } + if (backtrack(index + 1)) { + return true; + } + if (num > 1) { + result[index + num] = 0; + } + } + result[index] = 0; + group[num] = false; + } + return false; + } + + return result; +}; diff --git a/README.md b/README.md index 821d6782..113ffcca 100644 --- a/README.md +++ b/README.md @@ -492,6 +492,7 @@ 1672|[Richest Customer Wealth](./1672-richest-customer-wealth.js)|Easy| 1679|[Max Number of K-Sum Pairs](./1679-max-number-of-k-sum-pairs.js)|Medium| 1716|[Calculate Money in Leetcode Bank](./1716-calculate-money-in-leetcode-bank.js)|Easy| +1718|[Construct the Lexicographically Largest Valid Sequence](./1718-construct-the-lexicographically-largest-valid-sequence.js)|Medium| 1726|[Tuple with Same Product](./1726-tuple-with-same-product.js)|Medium| 1732|[Find the Highest Altitude](./1732-find-the-highest-altitude.js)|Easy| 1748|[Sum of Unique Elements](./1748-sum-of-unique-elements.js)|Easy| From 6497ca684664cf89db40840dc25f690fb9e621bb Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 16 Feb 2025 17:25:23 -0600 Subject: [PATCH 634/919] Add solution #441 --- 0441-arranging-coins.js | 22 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 0441-arranging-coins.js diff --git a/0441-arranging-coins.js b/0441-arranging-coins.js new file mode 100644 index 00000000..77b385bb --- /dev/null +++ b/0441-arranging-coins.js @@ -0,0 +1,22 @@ +/** + * 441. Arranging Coins + * https://leetcode.com/problems/arranging-coins/ + * Difficulty: Easy + * + * You have n coins and you want to build a staircase with these coins. The staircase consists + * of k rows where the ith row has exactly i coins. The last row of the staircase may be incomplete. + * + * Given the integer n, return the number of complete rows of the staircase you will build. + */ + +/** + * @param {number} n + * @return {number} + */ +var arrangeCoins = function(n) { + let count = 0; + for (; count <= n; count++) { + n -= count; + } + return count - 1; +}; diff --git a/README.md b/README.md index 113ffcca..9a4e9136 100644 --- a/README.md +++ b/README.md @@ -266,6 +266,7 @@ 434|[Number of Segments in a String](./0434-number-of-segments-in-a-string.js)|Easy| 435|[Non-overlapping Intervals](./0435-non-overlapping-intervals.js)|Medium| 437|[Path Sum III](./0437-path-sum-iii.js)|Medium| +441|[Arranging Coins](./0441-arranging-coins.js)|Easy| 442|[Find All Duplicates in an Array](./0442-find-all-duplicates-in-an-array.js)|Medium| 443|[String Compression](./0443-string-compression.js)|Medium| 448|[Find All Numbers Disappeared in an Array](./0448-find-all-numbers-disappeared-in-an-array.js)|Easy| From da67bafac586a50819bfc165a6bb2ebdfa69fc9e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 16 Feb 2025 17:26:35 -0600 Subject: [PATCH 635/919] Add solution #486 --- 0486-predict-the-winner.js | 35 +++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 36 insertions(+) create mode 100644 0486-predict-the-winner.js diff --git a/0486-predict-the-winner.js b/0486-predict-the-winner.js new file mode 100644 index 00000000..825abf3a --- /dev/null +++ b/0486-predict-the-winner.js @@ -0,0 +1,35 @@ +/** + * 486. Predict the Winner + * https://leetcode.com/problems/predict-the-winner/ + * Difficulty: Medium + * + * You are given an integer array nums. Two players are playing a game with this array: + * player 1 and player 2. + * + * Player 1 and player 2 take turns, with player 1 starting first. Both players start + * the game with a score of 0. At each turn, the player takes one of the numbers from + * either end of the array (i.e., nums[0] or nums[nums.length - 1]) which reduces the + * size of the array by 1. The player adds the chosen number to their score. The game + * ends when there are no more elements in the array. + * + * Return true if Player 1 can win the game. If the scores of both players are equal, + * then player 1 is still the winner, and you should also return true. You may assume + * that both players are playing optimally. + */ + +/** + * @param {number[]} nums + * @return {boolean} + */ +var predictTheWinner = function(nums) { + const diff = new Array(nums.length).fill(0); + + for (let i = nums.length - 1; i >= 0; i--) { + diff[i] = nums[i]; + for (let j = i + 1; j < nums.length; j++) { + diff[j] = Math.max(nums[i] - diff[j], nums[j] - diff[j - 1]); + } + } + + return diff[nums.length - 1] >= 0; +}; diff --git a/README.md b/README.md index 9a4e9136..40a4805e 100644 --- a/README.md +++ b/README.md @@ -280,6 +280,7 @@ 476|[Number Complement](./0476-number-complement.js)|Easy| 482|[License Key Formatting](./0482-license-key-formatting.js)|Easy| 485|[Max Consecutive Ones](./0485-max-consecutive-ones.js)|Easy| +486|[Predict the Winner](./0486-predict-the-winner.js)|Medium| 491|[Non-decreasing Subsequences](./0491-non-decreasing-subsequences.js)|Medium| 492|[Construct the Rectangle](./0492-construct-the-rectangle.js)|Easy| 496|[Next Greater Element I](./0496-next-greater-element-i.js)|Easy| From 222c4c55bb7764274488e7698b1b91ad5f2dd9ef Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 16 Feb 2025 17:27:35 -0600 Subject: [PATCH 636/919] Add solution #472 --- 0472-concatenated-words.js | 35 +++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 36 insertions(+) create mode 100644 0472-concatenated-words.js diff --git a/0472-concatenated-words.js b/0472-concatenated-words.js new file mode 100644 index 00000000..d2ecd834 --- /dev/null +++ b/0472-concatenated-words.js @@ -0,0 +1,35 @@ +/** + * 472. Concatenated Words + * https://leetcode.com/problems/concatenated-words/ + * Difficulty: Hard + * + * Given an array of strings words (without duplicates), return all the concatenated words + * in the given list of words. + * + * A concatenated word is defined as a string that is comprised entirely of at least two + * shorter words (not necessarily distinct) in the given array. + */ + +/** + * @param {string[]} words + * @return {string[]} + */ +var findAllConcatenatedWordsInADict = function(words) { + const set = new Set(words); + const map = new Map(); + + function isValid(word) { + if (map.has(word)) return map.get(word); + for (let i = 1; i < word.length; i++) { + const suffix = word.slice(i); + if (set.has(word.slice(0, i)) && (set.has(suffix) || isValid(suffix))) { + map.set(word, true); + return true; + } + } + map.set(word, false); + return false; + } + + return words.filter(word => word.length > 0 && isValid(word)); +}; diff --git a/README.md b/README.md index 40a4805e..d90fe446 100644 --- a/README.md +++ b/README.md @@ -277,6 +277,7 @@ 459|[Repeated Substring Pattern](./0459-repeated-substring-pattern.js)|Easy| 461|[Hamming Distance](./0461-hamming-distance.js)|Easy| 463|[Island Perimeter](./0463-island-perimeter.js)|Medium| +472|[Concatenated Words](./0472-concatenated-words.js)|Hard| 476|[Number Complement](./0476-number-complement.js)|Easy| 482|[License Key Formatting](./0482-license-key-formatting.js)|Easy| 485|[Max Consecutive Ones](./0485-max-consecutive-ones.js)|Easy| From 173889bb7467881cef95d2c77ecddd14bb1b521e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 16 Feb 2025 17:28:50 -0600 Subject: [PATCH 637/919] Add solution #380 --- 0380-insert-delete-getrandom-o1.js | 52 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 53 insertions(+) create mode 100644 0380-insert-delete-getrandom-o1.js diff --git a/0380-insert-delete-getrandom-o1.js b/0380-insert-delete-getrandom-o1.js new file mode 100644 index 00000000..b48b8773 --- /dev/null +++ b/0380-insert-delete-getrandom-o1.js @@ -0,0 +1,52 @@ +/** + * 380. Insert Delete GetRandom O(1) + * https://leetcode.com/problems/insert-delete-getrandom-o1/ + * Difficulty: Medium + * + * Implement the RandomizedSet class: + * - RandomizedSet() Initializes the RandomizedSet object. + * - bool insert(int val) Inserts an item val into the set if not present. Returns true if the + * item was not present, false otherwise. + * - bool remove(int val) Removes an item val from the set if present. Returns true if the item + * was present, false otherwise. + * - int getRandom() Returns a random element from the current set of elements (it's guaranteed + * that at least one element exists when this method is called). Each element must have the + * same probability of being returned. + * + * You must implement the functions of the class such that each function works in average O(1) + * time complexity. + */ + + +var RandomizedSet = function() { + this.set = new Set(); +}; + +/** + * @param {number} val + * @return {boolean} + */ +RandomizedSet.prototype.insert = function(val) { + const hasValue = this.set.has(val); + this.set.add(val); + return !hasValue; +}; + +/** + * @param {number} val + * @return {boolean} + */ +RandomizedSet.prototype.remove = function(val) { + const hasValue = this.set.has(val); + this.set.delete(val); + return hasValue; +}; + +/** + * @return {number} + */ +RandomizedSet.prototype.getRandom = function() { + const item = Array.from(this.set); + const randomIndex = Math.floor(Math.random() * item.length); + return item[randomIndex]; +}; diff --git a/README.md b/README.md index d90fe446..69b65c6a 100644 --- a/README.md +++ b/README.md @@ -249,6 +249,7 @@ 371|[Sum of Two Integers](./0371-sum-of-two-integers.js)|Medium| 372|[Super Pow](./0372-super-pow.js)|Medium| 374|[Guess Number Higher or Lower](./0374-guess-number-higher-or-lower.js)|Medium| +380|[Insert Delete GetRandom O(1)](./0380-insert-delete-getrandom-o1.js)|Medium| 383|[Ransom Note](./0383-ransom-note.js)|Easy| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| 389|[Find the Difference](./0389-find-the-difference.js)|Easy| From 20961d877991b3fa2029d014bb314ba73d7f8392 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 17 Feb 2025 17:23:00 -0600 Subject: [PATCH 638/919] Add solution #297 --- 0297-serialize-and-deserialize-binary-tree.js | 42 +++++++++++++++++++ README.md | 1 + 2 files changed, 43 insertions(+) create mode 100644 0297-serialize-and-deserialize-binary-tree.js diff --git a/0297-serialize-and-deserialize-binary-tree.js b/0297-serialize-and-deserialize-binary-tree.js new file mode 100644 index 00000000..09bee069 --- /dev/null +++ b/0297-serialize-and-deserialize-binary-tree.js @@ -0,0 +1,42 @@ +/** + * 297. Serialize and Deserialize Binary Tree + * https://leetcode.com/problems/serialize-and-deserialize-binary-tree/ + * Difficulty: Hard + * + * Serialization is the process of converting a data structure or object into a sequence of bits so + * that it can be stored in a file or memory buffer, or transmitted across a network connection link + * to be reconstructed later in the same or another computer environment. + * + * Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how + * your serialization/deserialization algorithm should work. You just need to ensure that a binary + * tree can be serialized to a string and this string can be deserialized to the original tree + * structure. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ + +/** + * Encodes a tree to a single string. + * + * @param {TreeNode} root + * @return {string} + */ +var serialize = function(root) { + return JSON.stringify(root); +}; + +/** + * Decodes your encoded data to tree. + * + * @param {string} data + * @return {TreeNode} + */ +var deserialize = function(data) { + return JSON.parse(data); +}; diff --git a/README.md b/README.md index 69b65c6a..97076afb 100644 --- a/README.md +++ b/README.md @@ -229,6 +229,7 @@ 290|[Word Pattern](./0290-word-pattern.js)|Easy| 292|[Nim Game](./0292-nim-game.js)|Easy| 295|[Find Median from Data Stream](./0295-find-median-from-data-stream.js)|Hard| +297|[Serialize and Deserialize Binary Tree](./0297-serialize-and-deserialize-binary-tree.js)|Hard| 303|[Range Sum Query - Immutable](./0303-range-sum-query-immutable.js)|Easy| 306|[Additive Number](./0306-additive-number.js)|Medium| 316|[Remove Duplicate Letters](./0316-remove-duplicate-letters.js)|Medium| From c02b1d9de0cb28b012f6475d7eaa8afca32a3070 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 17 Feb 2025 17:23:34 -0600 Subject: [PATCH 639/919] Add solution #1079 --- 1079-letter-tile-possibilities.js | 32 +++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 1079-letter-tile-possibilities.js diff --git a/1079-letter-tile-possibilities.js b/1079-letter-tile-possibilities.js new file mode 100644 index 00000000..ca716ded --- /dev/null +++ b/1079-letter-tile-possibilities.js @@ -0,0 +1,32 @@ +/** + * 1079. Letter Tile Possibilities + * https://leetcode.com/problems/letter-tile-possibilities/ + * Difficulty: Medium + * + * You have n tiles, where each tile has one letter tiles[i] printed on it. + * + * Return the number of possible non-empty sequences of letters you can make using the letters + * printed on those tiles. + */ + +/** + * @param {string} tiles + * @return {number} + */ +var numTilePossibilities = function(tiles) { + const map = {}; + tiles.split('').forEach(t => map[t] = (map[t] ?? 0) + 1); + return backtrack(); + + function backtrack() { + let count = 0; + for (const key of Object.keys(map)) { + if (!map[key]) continue; + count += 1; + map[key] -= 1; + count += backtrack(); + map[key] += 1; + } + return count; + } +}; diff --git a/README.md b/README.md index 97076afb..33111948 100644 --- a/README.md +++ b/README.md @@ -402,6 +402,7 @@ 1047|[Remove All Adjacent Duplicates In String](./1047-remove-all-adjacent-duplicates-in-string.js)|Easy| 1051|[Height Checker](./1051-height-checker.js)|Easy| 1071|[Greatest Common Divisor of Strings](./1071-greatest-common-divisor-of-strings.js)|Easy| +1079|[Letter Tile Possibilities](./1079-letter-tile-possibilities.js)|Medium| 1081|[Smallest Subsequence of Distinct Characters](./1081-smallest-subsequence-of-distinct-characters.js)|Medium| 1103|[Distribute Candies to People](./1103-distribute-candies-to-people.js)|Easy| 1108|[Defanging an IP Address](./1108-defanging-an-ip-address.js)|Easy| From 8818a5b40660553a50b3cf0bfe1956ef43678541 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 17 Feb 2025 17:24:04 -0600 Subject: [PATCH 640/919] Add solution #230 --- 0230-kth-smallest-element-in-a-bst.js | 34 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 0230-kth-smallest-element-in-a-bst.js diff --git a/0230-kth-smallest-element-in-a-bst.js b/0230-kth-smallest-element-in-a-bst.js new file mode 100644 index 00000000..29e875cd --- /dev/null +++ b/0230-kth-smallest-element-in-a-bst.js @@ -0,0 +1,34 @@ +/** + * 230. Kth Smallest Element in a BST + * https://leetcode.com/problems/kth-smallest-element-in-a-bst/ + * Difficulty: Medium + * + * Given the root of a binary search tree, and an integer k, return the kth smallest value + * (1-indexed) of all the values of the nodes in the tree. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @param {number} k + * @return {number} + */ +var kthSmallest = function(root, k) { + const result = []; + dfs(root); + return result[k - 1]; + + function dfs(node) { + if (!node || result.length > k) return null; + dfs(node.left); + result.push(node.val); + dfs(node.right); + } +}; diff --git a/README.md b/README.md index 33111948..1b2364c3 100644 --- a/README.md +++ b/README.md @@ -203,6 +203,7 @@ 226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy| 228|[Summary Ranges](./0228-summary-ranges.js)|Easy| 229|[Majority Element II](./0229-majority-element-ii.js)|Medium| +230|[Kth Smallest Element in a BST](./0230-kth-smallest-element-in-a-bst.js)|Medium| 231|[Power of Two](./0231-power-of-two.js)|Easy| 232|[Implement Queue using Stacks](./0232-implement-queue-using-stacks.js)|Easy| 233|[Number of Digit One](./0233-number-of-digit-one.js)|Hard| From 105867b2282e66855d480d57d142ec28571e58e6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 17 Feb 2025 17:24:40 -0600 Subject: [PATCH 641/919] Add solution #287 --- 0287-find-the-duplicate-number.js | 33 +++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 0287-find-the-duplicate-number.js diff --git a/0287-find-the-duplicate-number.js b/0287-find-the-duplicate-number.js new file mode 100644 index 00000000..9fccafd4 --- /dev/null +++ b/0287-find-the-duplicate-number.js @@ -0,0 +1,33 @@ +/** + * 287. Find the Duplicate Number + * https://leetcode.com/problems/find-the-duplicate-number/ + * Difficulty: Medium + * + * Given an array of integers nums containing n + 1 integers where each integer is in the + * range [1, n] inclusive. + * + * There is only one repeated number in nums, return this repeated number. + * + * You must solve the problem without modifying the array nums and using only constant extra space. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var findDuplicate = function(nums) { + let slow = nums[0]; + let fast = nums[nums[0]]; + + while (slow !== fast) { + slow = nums[slow]; + fast = nums[nums[fast]]; + } + slow = 0; + while (slow !== fast) { + slow = nums[slow]; + fast = nums[fast]; + } + + return slow; +}; diff --git a/README.md b/README.md index 1b2364c3..f5b263d8 100644 --- a/README.md +++ b/README.md @@ -226,6 +226,7 @@ 279|[Perfect Squares](./0279-perfect-squares.js)|Medium| 282|[Expression Add Operators](./0282-expression-add-operators.js)|Hard| 283|[Move Zeroes](./0283-move-zeroes.js)|Easy| +287|[Find the Duplicate Number](./0287-find-the-duplicate-number.js)|Medium| 289|[Game of Life](./0289-game-of-life.js)|Medium| 290|[Word Pattern](./0290-word-pattern.js)|Easy| 292|[Nim Game](./0292-nim-game.js)|Easy| From 1c4b1040861223c18ab17d60f8ae87d382bddf69 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 17 Feb 2025 17:25:59 -0600 Subject: [PATCH 642/919] Add solution #284 --- 0284-peeking-iterator.js | 49 ++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 50 insertions(+) create mode 100644 0284-peeking-iterator.js diff --git a/0284-peeking-iterator.js b/0284-peeking-iterator.js new file mode 100644 index 00000000..0fa52ba9 --- /dev/null +++ b/0284-peeking-iterator.js @@ -0,0 +1,49 @@ +/** + * 284. Peeking Iterator + * https://leetcode.com/problems/peeking-iterator/ + * Difficulty: Medium + * + * Design an iterator that supports the peek operation on an existing iterator in addition to + * the hasNext and the next operations. + * + * Implement the PeekingIterator class: + * - PeekingIterator(Iterator nums) Initializes the object with the given integer iterator + * iterator. + * - int next() Returns the next element in the array and moves the pointer to the next element. + * - boolean hasNext() Returns true if there are still elements in the array. + * - int peek() Returns the next element in the array without moving the pointer. + * + * Note: Each language may have a different implementation of the constructor and Iterator, but + * they all support the int next() and boolean hasNext() functions. + */ + +/** + * @param {Iterator} iterator + */ +var PeekingIterator = function(iterator) { + this.iterator = iterator; + this.peekValue = iterator.next(); +}; + +/** + * @return {number} + */ +PeekingIterator.prototype.peek = function() { + return this.peekValue; +}; + +/** + * @return {number} + */ +PeekingIterator.prototype.next = function() { + const next = this.peekValue; + this.peekValue = this.iterator.next(); + return next; +}; + +/** + * @return {boolean} + */ +PeekingIterator.prototype.hasNext = function() { + return this.peekValue > 0; +}; diff --git a/README.md b/README.md index f5b263d8..6d54aa6e 100644 --- a/README.md +++ b/README.md @@ -226,6 +226,7 @@ 279|[Perfect Squares](./0279-perfect-squares.js)|Medium| 282|[Expression Add Operators](./0282-expression-add-operators.js)|Hard| 283|[Move Zeroes](./0283-move-zeroes.js)|Easy| +284|[Peeking Iterator](./0284-peeking-iterator.js)|Medium| 287|[Find the Duplicate Number](./0287-find-the-duplicate-number.js)|Medium| 289|[Game of Life](./0289-game-of-life.js)|Medium| 290|[Word Pattern](./0290-word-pattern.js)|Easy| From 634991b6f846f70655cf398bf4747d2960ba2c13 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 18 Feb 2025 17:27:32 -0600 Subject: [PATCH 643/919] Add solution #2375 --- ...onstruct-smallest-number-from-di-string.js | 34 +++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 2375-construct-smallest-number-from-di-string.js diff --git a/2375-construct-smallest-number-from-di-string.js b/2375-construct-smallest-number-from-di-string.js new file mode 100644 index 00000000..2632156e --- /dev/null +++ b/2375-construct-smallest-number-from-di-string.js @@ -0,0 +1,34 @@ +/** + * 2375. Construct Smallest Number From DI String + * https://leetcode.com/problems/construct-smallest-number-from-di-string/ + * Difficulty: Medium + * + * You are given a 0-indexed string pattern of length n consisting of the characters + * 'I' meaning increasing and 'D' meaning decreasing. + * + * A 0-indexed string num of length n + 1 is created using the following conditions: + * - num consists of the digits '1' to '9', where each digit is used at most once. + * - If pattern[i] == 'I', then num[i] < num[i + 1]. + * - If pattern[i] == 'D', then num[i] > num[i + 1]. + * + * Return the lexicographically smallest possible string num that meets the conditions. + */ + +/** + * @param {string} pattern + * @return {string} + */ +var smallestNumber = function(pattern) { + let result = ''; + + for (let i = 0, stack = []; i <= pattern.length; i++) { + stack.push(i + 1); + if (i === pattern.length || pattern[i] === 'I') { + while (stack.length > 0) { + result += stack.pop(); + } + } + } + + return result; +}; diff --git a/README.md b/README.md index 6d54aa6e..74b655e5 100644 --- a/README.md +++ b/README.md @@ -553,6 +553,7 @@ 2349|[Design a Number Container System](./2349-design-a-number-container-system.js)|Medium| 2352|[Equal Row and Column Pairs](./2352-equal-row-and-column-pairs.js)|Medium| 2364|[Count Number of Bad Pairs](./2364-count-number-of-bad-pairs.js)|Medium| +2375|[Construct Smallest Number From DI String](./2375-construct-smallest-number-from-di-string.js)|Medium| 2390|[Removing Stars From a String](./2390-removing-stars-from-a-string.js)|Medium| 2396|[Strictly Palindromic Number](./2396-strictly-palindromic-number.js)|Medium| 2413|[Smallest Even Multiple](./2413-smallest-even-multiple.js)|Easy| From 06ad34d5a607347df3ab95f5c82f45cd92bd952e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 18 Feb 2025 17:28:38 -0600 Subject: [PATCH 644/919] Add solution #126 --- 0126-word-ladder-ii.js | 76 ++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 77 insertions(+) create mode 100644 0126-word-ladder-ii.js diff --git a/0126-word-ladder-ii.js b/0126-word-ladder-ii.js new file mode 100644 index 00000000..9e60306e --- /dev/null +++ b/0126-word-ladder-ii.js @@ -0,0 +1,76 @@ +/** + * 126. Word Ladder II + * https://leetcode.com/problems/word-ladder-ii/ + * Difficulty: Hard + * + * A transformation sequence from word beginWord to word endWord using a dictionary wordList + * is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that: + * - Every adjacent pair of words differs by a single letter. + * - Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList. + * - sk == endWord + * + * Given two words, beginWord and endWord, and a dictionary wordList, return all the shortest + * transformation sequences from beginWord to endWord, or an empty list if no such sequence + * exists. Each sequence should be returned as a list of the words [beginWord, s1, s2, ..., sk]. + */ + +/** + * @param {string} beginWord + * @param {string} endWord + * @param {string[]} wordList + * @return {string[][]} + */ +var findLadders = function(beginWord, endWord, wordList) { + const set = new Set(wordList); + const queue = [beginWord]; + const group = []; + let isEnd = false; + + while (queue.length && !isEnd) { + group.push([...queue]); + const limit = queue.length; + for (let i = 0; i < limit && !isEnd; i++) { + const from = queue.shift(); + for (const word of set) { + if (!isValid(from, word)) { + continue; + } else if (word === endWord) { + isEnd = true; + break; + } + queue.push(word); + set.delete(word); + } + } + } + + if (!isEnd) { + return []; + } + + const result = [[endWord]]; + for (let i = group.length - 1; i >= 0; i--) { + const limit = result.length; + for (let j = 0; j < limit; j++) { + const path = result.shift(); + for (const word of group[i]) { + if (!isValid(path[0], word)) { + continue; + } + result.push([word, ...path]); + } + } + } + + return result; + + function isValid(a, b) { + let count = 0; + for (let i = 0; i < a.length && count < 2; i++) { + if (a[i] !== b[i]) { + count++; + } + } + return count === 1; + } +}; diff --git a/README.md b/README.md index 74b655e5..b283afec 100644 --- a/README.md +++ b/README.md @@ -131,6 +131,7 @@ 123|[Best Time to Buy and Sell Stock III](./0123-best-time-to-buy-and-sell-stock-iii.js)|Hard| 124|[Binary Tree Maximum Path Sum](./0124-binary-tree-maximum-path-sum.js)|Hard| 125|[Valid Palindrome](./0125-valid-palindrome.js)|Easy| +126|[Word Ladder II](./0126-word-ladder-ii.js)|Hard| 127|[Word Ladder](./0127-word-ladder.js)|Hard| 128|[Longest Consecutive Sequence](./0128-longest-consecutive-sequence.js)|Medium| 129|[Sum Root to Leaf Numbers](./0129-sum-root-to-leaf-numbers.js)|Medium| From 6f6bc5941b8a5b66adc24dbd44dc1dde0e5f92e6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 18 Feb 2025 17:29:37 -0600 Subject: [PATCH 645/919] Add solution #309 --- ...ime-to-buy-and-sell-stock-with-cooldown.js | 31 +++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 0309-best-time-to-buy-and-sell-stock-with-cooldown.js diff --git a/0309-best-time-to-buy-and-sell-stock-with-cooldown.js b/0309-best-time-to-buy-and-sell-stock-with-cooldown.js new file mode 100644 index 00000000..8bece31b --- /dev/null +++ b/0309-best-time-to-buy-and-sell-stock-with-cooldown.js @@ -0,0 +1,31 @@ +/** + * 309. Best Time to Buy and Sell Stock with Cooldown + * https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/ + * Difficulty: Medium + * + * You are given an array prices where prices[i] is the price of a given stock on the ith day. + * + * Find the maximum profit you can achieve. You may complete as many transactions as you like + * (i.e., buy one and sell one share of the stock multiple times) with the following restrictions: + * - After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day). + * + * Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock + * before you buy again). + */ + +/** + * @param {number[]} prices + * @return {number} + */ +var maxProfit = function(prices) { + let result = 0; + let remaining = 0; + + for (let i = 0, limit = -Infinity; i < prices.length; i++) { + limit = Math.max(limit, remaining - prices[i]); + remaining = Math.max(remaining, result); + result = limit + prices[i]; + } + + return Math.max(result, remaining); +}; diff --git a/README.md b/README.md index b283afec..599f01f1 100644 --- a/README.md +++ b/README.md @@ -236,6 +236,7 @@ 297|[Serialize and Deserialize Binary Tree](./0297-serialize-and-deserialize-binary-tree.js)|Hard| 303|[Range Sum Query - Immutable](./0303-range-sum-query-immutable.js)|Easy| 306|[Additive Number](./0306-additive-number.js)|Medium| +309|[Best Time to Buy and Sell Stock with Cooldown](./0309-best-time-to-buy-and-sell-stock-with-cooldown.js)|Medium| 316|[Remove Duplicate Letters](./0316-remove-duplicate-letters.js)|Medium| 318|[Maximum Product of Word Lengths](./0318-maximum-product-of-word-lengths.js)|Medium| 322|[Coin Change](./0322-coin-change.js)|Medium| From b42bc46825244467d3b368ffc0d80483457b4598 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 18 Feb 2025 17:32:04 -0600 Subject: [PATCH 646/919] Add solution #355 --- 0355-design-twitter.js | 75 ++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 76 insertions(+) create mode 100644 0355-design-twitter.js diff --git a/0355-design-twitter.js b/0355-design-twitter.js new file mode 100644 index 00000000..f840697b --- /dev/null +++ b/0355-design-twitter.js @@ -0,0 +1,75 @@ +/** + * 355. Design Twitter + * https://leetcode.com/problems/design-twitter/ + * Difficulty: Medium + * + * Design a simplified version of Twitter where users can post tweets, follow/unfollow another user, + * and is able to see the 10 most recent tweets in the user's news feed. + * + * Implement the Twitter class: + * - Twitter() Initializes your twitter object. + * - void postTweet(int userId, int tweetId) Composes a new tweet with ID tweetId by the user + * userId. Each call to this function will be made with a unique tweetId. + * - List getNewsFeed(int userId) Retrieves the 10 most recent tweet IDs in the user's news + * feed. Each item in the news feed must be posted by users who the user followed or by the user + * themself. Tweets must be ordered from most recent to least recent. + * - void follow(int followerId, int followeeId) The user with ID followerId started following the + * user with ID followeeId. + * - void unfollow(int followerId, int followeeId) The user with ID followerId started unfollowing + * the user with ID followeeId. + */ + + +var Twitter = function() { + this.tweets = []; + this.followers = new Map(); +}; + +/** + * @param {number} userId + * @param {number} tweetId + * @return {void} + */ +Twitter.prototype.postTweet = function(userId, tweetId) { + this.tweets.unshift([userId, tweetId]); +}; + +/** + * @param {number} userId + * @return {number[]} + */ +Twitter.prototype.getNewsFeed = function(userId) { + const result = []; + for (let i = 0; i < this.tweets.length && result.length < 10; i++) { + const [user, tweet] = this.tweets[i] ?? []; + if (user === userId || (this.followers.get(userId) && this.followers.get(userId).has(user))) { + result.push(tweet); + } + } + return result; +}; + +/** + * @param {number} followerId + * @param {number} followeeId + * @return {void} + */ +Twitter.prototype.follow = function(followerId, followeeId) { + if (followerId !== followeeId) { + if (!this.followers.has(followerId)) { + this.followers.set(followerId, new Set()); + } + this.followers.get(followerId).add(followeeId); + } +}; + +/** + * @param {number} followerId + * @param {number} followeeId + * @return {void} + */ +Twitter.prototype.unfollow = function(followerId, followeeId) { + if (this.followers.has(followerId)) { + this.followers.get(followerId).delete(followeeId); + } +}; diff --git a/README.md b/README.md index 599f01f1..3d0dfcc1 100644 --- a/README.md +++ b/README.md @@ -251,6 +251,7 @@ 349|[Intersection of Two Arrays](./0349-intersection-of-two-arrays.js)|Easy| 350|[Intersection of Two Arrays II](./0350-intersection-of-two-arrays-ii.js)|Easy| 352|[Data Stream as Disjoint Intervals](./0352-data-stream-as-disjoint-intervals.js)|Hard| +355|[Design Twitter](./0355-design-twitter.js)|Medium| 367|[Valid Perfect Square](./0367-valid-perfect-square.js)|Easy| 371|[Sum of Two Integers](./0371-sum-of-two-integers.js)|Medium| 372|[Super Pow](./0372-super-pow.js)|Medium| From 391c6451b441c2e8206ab3c3c1613be7a04b7bef Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 18 Feb 2025 17:34:15 -0600 Subject: [PATCH 647/919] Add solution #830 --- 0830-positions-of-large-groups.js | 36 +++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 37 insertions(+) create mode 100644 0830-positions-of-large-groups.js diff --git a/0830-positions-of-large-groups.js b/0830-positions-of-large-groups.js new file mode 100644 index 00000000..ce247073 --- /dev/null +++ b/0830-positions-of-large-groups.js @@ -0,0 +1,36 @@ +/** + * 830. Positions of Large Groups + * https://leetcode.com/problems/positions-of-large-groups/ + * Difficulty: Easy + * + * 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. + */ + +/** + * @param {string} s + * @return {number[][]} + */ +var largeGroupPositions = function(s) { + const result = []; + let start = 0; + + for (let i = 1; i <= s.length; i++) { + if (s.length === i || s[i] !== s[start]) { + if (i - start >= 3) { + result.push([start, i - 1]); + } + start = i; + } + } + + return result; +}; diff --git a/README.md b/README.md index 3d0dfcc1..9cfe11fb 100644 --- a/README.md +++ b/README.md @@ -366,6 +366,7 @@ 821|[Shortest Distance to a Character](./0821-shortest-distance-to-a-character.js)|Easy| 824|[Goat Latin](./0824-goat-latin.js)|Easy| 827|[Making A Large Island](./0827-making-a-large-island.js)|Hard| +830|[Positions of Large Groups](./0830-positions-of-large-groups.js)|Easy| 831|[Masking Personal Information](./0831-masking-personal-information.js)|Medium| 841|[Keys and Rooms](./0841-keys-and-rooms.js)|Medium| 844|[Backspace String Compare](./0844-backspace-string-compare.js)|Easy| From d2ee4b9f7607a374e4642c817e1c0f6a09ffcc29 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 19 Feb 2025 17:08:44 -0600 Subject: [PATCH 648/919] Add solution #3452 --- 3452-sum-of-good-numbers.js | 22 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 3452-sum-of-good-numbers.js diff --git a/3452-sum-of-good-numbers.js b/3452-sum-of-good-numbers.js new file mode 100644 index 00000000..714fee4b --- /dev/null +++ b/3452-sum-of-good-numbers.js @@ -0,0 +1,22 @@ +/** + * 3452. Sum of Good Numbers + * https://leetcode.com/problems/sum-of-good-numbers/ + * Difficulty: Easy + * + * Given an array of integers nums and an integer k, an element nums[i] is considered good if + * it is strictly greater than the elements at indices i - k and i + k (if those indices exist). + * If neither of these indices exists, nums[i] is still considered good. + * + * Return the sum of all the good elements in the array. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var sumOfGoodNumbers = function(nums, k) { + return nums.reduce((sum, n, i) => { + return n > (nums[i - k] ?? 0) && n > (nums[i + k] ?? 0) ? sum + n : sum; + }, 0); +}; diff --git a/README.md b/README.md index 9cfe11fb..d210a076 100644 --- a/README.md +++ b/README.md @@ -626,6 +626,7 @@ 3396|[Minimum Number of Operations to Make Elements in Array Distinct](./3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy| 3397|[Maximum Number of Distinct Elements After Operations](./3397-maximum-number-of-distinct-elements-after-operations.js)|Medium| 3402|[Minimum Operations to Make Columns Strictly Increasing](./3402-minimum-operations-to-make-columns-strictly-increasing.js)|Easy| +3452|[Sum of Good Numbers](./3452-sum-of-good-numbers.js)|Easy| ## License From 06251eeaa62b4dacf7204f8d582d695af2878f79 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 19 Feb 2025 17:10:12 -0600 Subject: [PATCH 649/919] Add solution #1769 --- ...perations-to-move-all-balls-to-each-box.js | 37 +++++++++++++++++++ README.md | 1 + 2 files changed, 38 insertions(+) create mode 100644 1769-minimum-number-of-operations-to-move-all-balls-to-each-box.js diff --git a/1769-minimum-number-of-operations-to-move-all-balls-to-each-box.js b/1769-minimum-number-of-operations-to-move-all-balls-to-each-box.js new file mode 100644 index 00000000..d8ba18e8 --- /dev/null +++ b/1769-minimum-number-of-operations-to-move-all-balls-to-each-box.js @@ -0,0 +1,37 @@ +/** + * 1769. Minimum Number of Operations to Move All Balls to Each Box + * https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/ + * Difficulty: Medium + * + * You have n boxes. You are given a binary string boxes of length n, where boxes[i] is '0' if + * the ith box is empty, and '1' if it contains one ball. + * + * In one operation, you can move one ball from a box to an adjacent box. Box i is adjacent to + * box j if abs(i - j) == 1. Note that after doing so, there may be more than one ball in some + * boxes. + * + * Return an array answer of size n, where answer[i] is the minimum number of operations needed + * to move all the balls to the ith box. + * + * Each answer[i] is calculated considering the initial state of the boxes. + */ + +/** + * @param {string} boxes + * @return {number[]} + */ +var minOperations = function(boxes) { + const result = new Array(boxes.length).fill(0); + + for (let i = 0; i < boxes.length; i++) { + let total = 0; + for (let j = 0; j < boxes.length; j++) { + if (boxes[j] === '1') { + total += Math.abs(j - i); + } + } + result[i] = total; + } + + return result; +}; diff --git a/README.md b/README.md index d210a076..1528726c 100644 --- a/README.md +++ b/README.md @@ -513,6 +513,7 @@ 1764|[Form Array by Concatenating Subarrays of Another Array](./1764-form-array-by-concatenating-subarrays-of-another-array.js)|Medium| 1765|[Map of Highest Peak](./1765-map-of-highest-peak.js)|Medium| 1768|[Merge Strings Alternately](./1768-merge-strings-alternately.js)|Easy| +1769|[Minimum Number of Operations to Move All Balls to Each Box](./1769-minimum-number-of-operations-to-move-all-balls-to-each-box.js)|Medium| 1780|[Check if Number is a Sum of Powers of Three](./1780-check-if-number-is-a-sum-of-powers-of-three.js)|Medium| 1790|[Check if One String Swap Can Make Strings Equal](./1790-check-if-one-string-swap-can-make-strings-equal.js)|Easy| 1791|[Find Center of Star Graph](./1791-find-center-of-star-graph.js)|Easy| From dcfdfe8b05cd20893207e9afdf3fe60cc84fdb15 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 19 Feb 2025 17:11:05 -0600 Subject: [PATCH 650/919] Add solution #2381 --- 2381-shifting-letters-ii.js | 38 +++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 39 insertions(+) create mode 100644 2381-shifting-letters-ii.js diff --git a/2381-shifting-letters-ii.js b/2381-shifting-letters-ii.js new file mode 100644 index 00000000..d785f045 --- /dev/null +++ b/2381-shifting-letters-ii.js @@ -0,0 +1,38 @@ +/** + * 2381. Shifting Letters II + * https://leetcode.com/problems/shifting-letters-ii/ + * Difficulty: Medium + * + * You are given a string s of lowercase English letters and a 2D integer array shifts where + * shifts[i] = [starti, endi, directioni]. For every i, shift the characters in s from the + * index starti to the index endi (inclusive) forward if directioni = 1, or shift the characters + * backward if directioni = 0. + * + * Shifting a character forward means replacing it with the next letter in the alphabet (wrapping + * around so that 'z' becomes 'a'). Similarly, shifting a character backward means replacing it + * with the previous letter in the alphabet (wrapping around so that 'a' becomes 'z'). + * + * Return the final string after all such shifts to s are applied. + */ + +/** + * @param {string} s + * @param {number[][]} shifts + * @return {string} + */ +var shiftingLetters = function(s, shifts) { + const compare = new Array(s.length).fill(0); + for (const [start, end, direction] of shifts) { + compare[start] += direction === 1 ? 1 : -1; + if (end + 1 < s.length) { + compare[end + 1] += direction === 1 ? -1 : 1; + } + } + let result = ''; + for (let i = 0, count = 0; i < s.length; i++) { + count = (count + compare[i]) % 26; + count = count < 0 ? count + 26 : count; + result += String.fromCharCode((s.charCodeAt(i) - 97 + count) % 26 + 97); + } + return result; +}; diff --git a/README.md b/README.md index 1528726c..32d86750 100644 --- a/README.md +++ b/README.md @@ -559,6 +559,7 @@ 2352|[Equal Row and Column Pairs](./2352-equal-row-and-column-pairs.js)|Medium| 2364|[Count Number of Bad Pairs](./2364-count-number-of-bad-pairs.js)|Medium| 2375|[Construct Smallest Number From DI String](./2375-construct-smallest-number-from-di-string.js)|Medium| +2381|[Shifting Letters II](./2381-shifting-letters-ii.js)|Medium| 2390|[Removing Stars From a String](./2390-removing-stars-from-a-string.js)|Medium| 2396|[Strictly Palindromic Number](./2396-strictly-palindromic-number.js)|Medium| 2413|[Smallest Even Multiple](./2413-smallest-even-multiple.js)|Easy| From 058418cd74a2549a084b324e36a399b8fc1ebcd5 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 19 Feb 2025 17:12:11 -0600 Subject: [PATCH 651/919] Add solution #1415 --- ...string-of-all-happy-strings-of-length-n.js | 44 +++++++++++++++++++ README.md | 1 + 2 files changed, 45 insertions(+) create mode 100644 1415-the-k-th-lexicographical-string-of-all-happy-strings-of-length-n.js diff --git a/1415-the-k-th-lexicographical-string-of-all-happy-strings-of-length-n.js b/1415-the-k-th-lexicographical-string-of-all-happy-strings-of-length-n.js new file mode 100644 index 00000000..fb169aa1 --- /dev/null +++ b/1415-the-k-th-lexicographical-string-of-all-happy-strings-of-length-n.js @@ -0,0 +1,44 @@ +/** + * 1415. The k-th Lexicographical String of All Happy Strings of Length n + * https://leetcode.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/ + * Difficulty: Medium + * + * A happy string is a string that: + * - consists only of letters of the set ['a', 'b', 'c']. + * - s[i] != s[i + 1] for all values of i from 1 to s.length - 1 (string is 1-indexed). + * + * For example, strings "abc", "ac", "b" and "abcbabcbcb" are all happy strings and strings "aa", + * "baa" and "ababbc" are not happy strings. + * + * Given two integers n and k, consider a list of all happy strings of length n sorted in + * lexicographical order. + * + * Return the kth string of this list or return an empty string if there are less than k happy + * strings of length n. + */ + +/** + * @param {number} n + * @param {number} k + * @return {string} + */ +var getHappyString = function(n, k) { + return backtrack('') || ''; + + function backtrack(str) { + if (str.length === n) { + return --k ? false : str; + } + for (const character of 'abc') { + if (character === str[str.length - 1]) { + continue; + } + const value = backtrack(str + character); + if (value) { + return value; + } + } + + return false; + } +}; diff --git a/README.md b/README.md index 32d86750..db4f7239 100644 --- a/README.md +++ b/README.md @@ -463,6 +463,7 @@ 1402|[Reducing Dishes](./1402-reducing-dishes.js)|Hard| 1408|[String Matching in an Array](./1408-string-matching-in-an-array.js)|Easy| 1410|[HTML Entity Parser](./1410-html-entity-parser.js)|Medium| +1415|[The k-th Lexicographical String of All Happy Strings of Length n](./1415-the-k-th-lexicographical-string-of-all-happy-strings-of-length-n.js)|Medium| 1431|[Kids With the Greatest Number of Candies](./1431-kids-with-the-greatest-number-of-candies.js)|Easy| 1436|[Destination City](./1436-destination-city.js)|Easy| 1437|[Check If All 1's Are at Least Length K Places Away](./1437-check-if-all-1s-are-at-least-length-k-places-away.js)|Easy| From a7458ff597f8aecc9f9547f156bb12bd0a860faa Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 19 Feb 2025 17:12:50 -0600 Subject: [PATCH 652/919] Add solution #319 --- 0319-bulb-switcher.js | 22 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 0319-bulb-switcher.js diff --git a/0319-bulb-switcher.js b/0319-bulb-switcher.js new file mode 100644 index 00000000..6d0c2c7d --- /dev/null +++ b/0319-bulb-switcher.js @@ -0,0 +1,22 @@ +/** + * 319. Bulb Switcher + * https://leetcode.com/problems/bulb-switcher/ + * Difficulty: Medium + * + * There are n bulbs that are initially off. You first turn on all the bulbs, then you turn + * off every second bulb. + * + * On the third round, you toggle every third bulb (turning on if it's off or turning off if + * it's on). For the ith round, you toggle every i bulb. For the nth round, you only toggle + * the last bulb. + * + * Return the number of bulbs that are on after n rounds. + */ + +/** + * @param {number} n + * @return {number} + */ +var bulbSwitch = function(n) { + return Math.floor(n ** 0.5); +}; diff --git a/README.md b/README.md index db4f7239..976bdac5 100644 --- a/README.md +++ b/README.md @@ -239,6 +239,7 @@ 309|[Best Time to Buy and Sell Stock with Cooldown](./0309-best-time-to-buy-and-sell-stock-with-cooldown.js)|Medium| 316|[Remove Duplicate Letters](./0316-remove-duplicate-letters.js)|Medium| 318|[Maximum Product of Word Lengths](./0318-maximum-product-of-word-lengths.js)|Medium| +319|[Bulb Switcher](./0319-bulb-switcher.js)|Medium| 322|[Coin Change](./0322-coin-change.js)|Medium| 326|[Power of Three](./0326-power-of-three.js)|Easy| 328|[Odd Even Linked List](./0328-odd-even-linked-list.js)|Medium| From 60f23950bfd23ddbcd150f8d3e4315d69570242d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 19 Feb 2025 18:20:40 -0600 Subject: [PATCH 653/919] Add solution #1980 --- 1980-find-unique-binary-string.js | 17 +++++++++++++++++ README.md | 1 + 2 files changed, 18 insertions(+) create mode 100644 1980-find-unique-binary-string.js diff --git a/1980-find-unique-binary-string.js b/1980-find-unique-binary-string.js new file mode 100644 index 00000000..88ea38b1 --- /dev/null +++ b/1980-find-unique-binary-string.js @@ -0,0 +1,17 @@ +/** + * 1980. Find Unique Binary String + * https://leetcode.com/problems/find-unique-binary-string/ + * Difficulty: Medium + * + * Given an array of strings nums containing n unique binary strings each of length n, + * return a binary string of length n that does not appear in nums. If there are multiple + * answers, you may return any of them. + */ + +/** + * @param {string[]} nums + * @return {string} + */ +var findDifferentBinaryString = function(nums) { + return nums.map((n, i) => n[i] === '0' ? '1' : '0').join(''); +}; diff --git a/README.md b/README.md index 976bdac5..7afa6370 100644 --- a/README.md +++ b/README.md @@ -531,6 +531,7 @@ 1926|[Nearest Exit from Entrance in Maze](./1926-nearest-exit-from-entrance-in-maze.js)|Medium| 1929|[Concatenation of Array](./1929-concatenation-of-array.js)|Easy| 1935|[Maximum Number of Words You Can Type](./1935-maximum-number-of-words-you-can-type.js)|Easy| +1980|[Find Unique Binary String](./1980-find-unique-binary-string.js)|Medium| 1985|[Find the Kth Largest Integer in the Array](./1985-find-the-kth-largest-integer-in-the-array.js)|Medium| 1996|[The Number of Weak Characters in the Game](./1996-the-number-of-weak-characters-in-the-game.js)|Medium| 2000|[Reverse Prefix of Word](./2000-reverse-prefix-of-word.js)|Easy| From 4750a2fd01199277351eaad6a6aae3e26208b38c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 19 Feb 2025 18:22:16 -0600 Subject: [PATCH 654/919] Add solution #331 --- ...preorder-serialization-of-a-binary-tree.js | 38 +++++++++++++++++++ README.md | 1 + 2 files changed, 39 insertions(+) create mode 100644 0331-verify-preorder-serialization-of-a-binary-tree.js diff --git a/0331-verify-preorder-serialization-of-a-binary-tree.js b/0331-verify-preorder-serialization-of-a-binary-tree.js new file mode 100644 index 00000000..3507b6db --- /dev/null +++ b/0331-verify-preorder-serialization-of-a-binary-tree.js @@ -0,0 +1,38 @@ +/** + * 331. Verify Preorder Serialization of a Binary Tree + * https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/ + * Difficulty: Medium + * + * One way to serialize a binary tree is to use preorder traversal. When we encounter a non-null + * node, we record the node's value. If it is a null node, we record using a sentinel value such + * as '#'. + * + * For example, the above binary tree can be serialized to the string "9,3,4,#,#,1,#,#,2,#,6,#,#", + * where '#' represents a null node. + * + * Given a string of comma-separated values preorder, return true if it is a correct preorder + * traversal serialization of a binary tree. + * + * It is guaranteed that each comma-separated value in the string must be either an integer or + * a character '#' representing null pointer. + * + * You may assume that the input format is always valid. + * For example, it could never contain two consecutive commas, such as "1,,3". + * Note: You are not allowed to reconstruct the tree. + */ + +/** + * @param {string} preorder + * @return {boolean} + */ +var isValidSerialization = function(preorder) { + let result = 1; + for (const node of preorder.split(',')) { + if (result) { + result += node === '#' ? -1 : 1; + } else { + return false; + } + } + return result < 1; +}; diff --git a/README.md b/README.md index 7afa6370..5728662f 100644 --- a/README.md +++ b/README.md @@ -243,6 +243,7 @@ 322|[Coin Change](./0322-coin-change.js)|Medium| 326|[Power of Three](./0326-power-of-three.js)|Easy| 328|[Odd Even Linked List](./0328-odd-even-linked-list.js)|Medium| +331|[Verify Preorder Serialization of a Binary Tree](./0331-verify-preorder-serialization-of-a-binary-tree.js)|Medium| 334|[Increasing Triplet Subsequence](./0334-increasing-triplet-subsequence.js)|Medium| 338|[Counting Bits](./0338-counting-bits.js)|Easy| 342|[Power of Four](./0342-power-of-four.js)|Easy| From 46db58b64571ec658278b451a6d64224fecbc7d6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 19 Feb 2025 18:23:08 -0600 Subject: [PATCH 655/919] Add solution #337 --- 0337-house-robber-iii.js | 38 ++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 39 insertions(+) create mode 100644 0337-house-robber-iii.js diff --git a/0337-house-robber-iii.js b/0337-house-robber-iii.js new file mode 100644 index 00000000..8200ef42 --- /dev/null +++ b/0337-house-robber-iii.js @@ -0,0 +1,38 @@ +/** + * 337. House Robber III + * https://leetcode.com/problems/house-robber-iii/ + * Difficulty: Medium + * + * The thief has found himself a new place for his thievery again. There is only one + * entrance to this area, called root. + * + * Besides the root, each house has one and only one parent house. After a tour, the smart + * thief realized that all houses in this place form a binary tree. It will automatically + * contact the police if two directly-linked houses were broken into on the same night. + * + * Given the root of the binary tree, return the maximum amount of money the thief can rob + * without alerting the police. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number} + */ +var rob = function(root) { + return Math.max(...traverse(root)); + + function traverse(node) { + if (!node) return [0, 0]; + const [l1, l2] = traverse(node.left); + const [r1, r2] = traverse(node.right); + return [node.val + l2 + r2, Math.max(l1 + r1, l2 + r2, l1 + r2, l2 + r1)]; + } +}; diff --git a/README.md b/README.md index 5728662f..947b8e48 100644 --- a/README.md +++ b/README.md @@ -245,6 +245,7 @@ 328|[Odd Even Linked List](./0328-odd-even-linked-list.js)|Medium| 331|[Verify Preorder Serialization of a Binary Tree](./0331-verify-preorder-serialization-of-a-binary-tree.js)|Medium| 334|[Increasing Triplet Subsequence](./0334-increasing-triplet-subsequence.js)|Medium| +337|[House Robber III](./0337-house-robber-iii.js)|Medium| 338|[Counting Bits](./0338-counting-bits.js)|Easy| 342|[Power of Four](./0342-power-of-four.js)|Easy| 344|[Reverse String](./0344-reverse-string.js)|Easy| From d5640478c4ff363e5d26f44f525b1544b7fb2150 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 19 Feb 2025 18:24:01 -0600 Subject: [PATCH 656/919] Add solution #210 --- 0210-course-schedule-ii.js | 52 ++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 53 insertions(+) create mode 100644 0210-course-schedule-ii.js diff --git a/0210-course-schedule-ii.js b/0210-course-schedule-ii.js new file mode 100644 index 00000000..7fc6171b --- /dev/null +++ b/0210-course-schedule-ii.js @@ -0,0 +1,52 @@ +/** + * 210. Course Schedule II + * https://leetcode.com/problems/course-schedule-ii/ + * Difficulty: Medium + * + * There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. + * You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you + * must take course bi first if you want to take course ai. + * + * For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1. + * + * Return the ordering of courses you should take to finish all courses. If there are many valid + * answers, return any of them. If it is impossible to finish all courses, return an empty array. + */ + +/** + * @param {number} numCourses + * @param {number[][]} prerequisites + * @return {number[]} + */ +var findOrder = function(numCourses, prerequisites) { + const graph = Array(numCourses).fill().map(() => []); + const seen = new Set(); + const path = new Set(); + const result = []; + + prerequisites.forEach(([c, p]) => graph[p].push(c)); + + for (let i = 0; i < numCourses; i++) { + if (!seen.has(i) && !dfs(i)) { + return []; + } + } + + return result; + + function dfs(course) { + if (path.has(course)) return false; + if (seen.has(course)) return true; + + path.add(course); + for (const c of graph[course]) { + if (!dfs(c)) { + return false; + } + } + path.delete(course); + seen.add(course); + result.unshift(course); + return true; + } +}; diff --git a/README.md b/README.md index 947b8e48..5e47fecd 100644 --- a/README.md +++ b/README.md @@ -190,6 +190,7 @@ 207|[Course Schedule](./0207-course-schedule.js)|Medium| 208|[Implement Trie (Prefix Tree)](./0208-implement-trie-prefix-tree.js)|Medium| 209|[Minimum Size Subarray Sum](./0209-minimum-size-subarray-sum.js)|Medium| +210|[Course Schedule II](./0210-course-schedule-ii.js)|Medium| 211|[Design Add and Search Words Data Structure](./0211-design-add-and-search-words-data-structure.js)|Medium| 213|[House Robber II](./0213-house-robber-ii.js)|Medium| 214|[Shortest Palindrome](./0214-shortest-palindrome.js)|Hard| From 72d3e06547f528b537d00cd673be8cf8798cda38 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 19 Feb 2025 18:24:43 -0600 Subject: [PATCH 657/919] Add solution #188 --- 0188-best-time-to-buy-and-sell-stock-iv.js | 42 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 43 insertions(+) create mode 100644 0188-best-time-to-buy-and-sell-stock-iv.js diff --git a/0188-best-time-to-buy-and-sell-stock-iv.js b/0188-best-time-to-buy-and-sell-stock-iv.js new file mode 100644 index 00000000..47369272 --- /dev/null +++ b/0188-best-time-to-buy-and-sell-stock-iv.js @@ -0,0 +1,42 @@ +/** + * 188. Best Time to Buy and Sell Stock IV + * https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/ + * Difficulty: Hard + * + * You are given an integer array prices where prices[i] is the price of a given stock on + * the ith day, and an integer k. + * + * Find the maximum profit you can achieve. You may complete at most k transactions: i.e. + * you may buy at most k times and sell at most k times. + * + * Note: You may not engage in multiple transactions simultaneously (i.e., you must sell + * the stock before you buy again). + */ + +/** + * @param {number} k + * @param {number[]} prices + * @return {number} + */ +var maxProfit = function(k, prices) { + if (prices.length < 2 || k === 0) return 0; + + if (k >= prices.length / 2) { + let profit = 0; + for (let i = 1; i < prices.length; i++) { + profit += prices[i] > prices[i - 1] ? (prices[i] - prices[i - 1]) : 0; + } + return profit; + } + + const buy = new Array(k + 1).fill(-Infinity); + const sell = new Array(k + 1).fill(0); + for (let i = 0; i < prices.length; i++) { + for (let j = k; j >= 1; j--) { + sell[j] = Math.max(sell[j], buy[j] + prices[i]); + buy[j] = Math.max(buy[j], sell[j - 1] - prices[i]); + } + } + + return sell[k]; +}; diff --git a/README.md b/README.md index 5e47fecd..348b42c1 100644 --- a/README.md +++ b/README.md @@ -175,6 +175,7 @@ 174|[Dungeon Game](./0174-dungeon-game.js)|Hard| 179|[Largest Number](./0179-largest-number.js)|Medium| 187|[Repeated DNA Sequences](./0187-repeated-dna-sequences.js)|Medium| +188|[Best Time to Buy and Sell Stock IV](./0188-best-time-to-buy-and-sell-stock-iv.js)|Hard| 189|[Rotate Array](./0189-rotate-array.js)|Medium| 190|[Reverse Bits](./0190-reverse-bits.js)|Easy| 191|[Number of 1 Bits](./0191-number-of-1-bits.js)|Easy| From 31848e45ffbd22f695f0ff9991b65d4ab0e864bc Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 20 Feb 2025 00:25:03 -0600 Subject: [PATCH 658/919] Add solution #239 --- 0239-sliding-window-maximum.js | 36 ++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 37 insertions(+) create mode 100644 0239-sliding-window-maximum.js diff --git a/0239-sliding-window-maximum.js b/0239-sliding-window-maximum.js new file mode 100644 index 00000000..b4845467 --- /dev/null +++ b/0239-sliding-window-maximum.js @@ -0,0 +1,36 @@ +/** + * 239. Sliding Window Maximum + * https://leetcode.com/problems/sliding-window-maximum/ + * Difficulty: Hard + * + * You are given an array of integers nums, there is a sliding window of size k which is moving + * from the very left of the array to the very right. You can only see the k numbers in the + * window. Each time the sliding window moves right by one position. + * + * Return the max sliding window. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {number[]} + */ +var maxSlidingWindow = function(nums, k) { + const result = []; + const queue = []; + + for (let i = 0; i < nums.length; i++) { + while (queue.length && queue[0] < i - k + 1) { + queue.shift(); + } + while (queue.length && nums[queue[queue.length - 1]] < nums[i]) { + queue.pop(); + } + queue.push(i); + if (i >= k - 1) { + result.push(nums[queue[0]]); + } + } + + return result; +}; diff --git a/README.md b/README.md index 348b42c1..db80e165 100644 --- a/README.md +++ b/README.md @@ -215,6 +215,7 @@ 236|[Lowest Common Ancestor of a Binary Tree](./0236-lowest-common-ancestor-of-a-binary-tree.js)|Medium| 237|[Delete Node in a Linked List](./0237-delete-node-in-a-linked-list.js)|Easy| 238|[Product of Array Except Self](./0238-product-of-array-except-self.js)|Medium| +239|[Sliding Window Maximum](./0239-sliding-window-maximum.js)|Hard| 242|[Valid Anagram](./0242-valid-anagram.js)|Easy| 257|[Binary Tree Paths](./0257-binary-tree-paths.js)|Easy| 258|[Add Digits](./0258-add-digits.js)|Easy| From 87fd47b0b34cee4f616980b412440e15a4dc50a9 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 20 Feb 2025 00:25:41 -0600 Subject: [PATCH 659/919] Add solution #240 --- 0240-search-a-2d-matrix-ii.js | 25 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 26 insertions(+) create mode 100644 0240-search-a-2d-matrix-ii.js diff --git a/0240-search-a-2d-matrix-ii.js b/0240-search-a-2d-matrix-ii.js new file mode 100644 index 00000000..14777aed --- /dev/null +++ b/0240-search-a-2d-matrix-ii.js @@ -0,0 +1,25 @@ +/** + * 240. Search a 2D Matrix II + * https://leetcode.com/problems/search-a-2d-matrix-ii/ + * Difficulty: Medium + * + * Write an efficient algorithm that searches for a value target in an m x n integer matrix + * matrix. This matrix has the following properties: + * - Integers in each row are sorted in ascending from left to right. + * - Integers in each column are sorted in ascending from top to bottom. + */ + +/** + * @param {number[][]} matrix + * @param {number} target + * @return {boolean} + */ +var searchMatrix = function(matrix, target) { + for (let i = 0, j = matrix[0].length - 1; i < matrix.length && j >= 0;) { + if (matrix[i][j] === target) { + return true; + } + matrix[i][j] > target ? j-- : i++; + } + return false; +}; diff --git a/README.md b/README.md index db80e165..a3abc0a9 100644 --- a/README.md +++ b/README.md @@ -216,6 +216,7 @@ 237|[Delete Node in a Linked List](./0237-delete-node-in-a-linked-list.js)|Easy| 238|[Product of Array Except Self](./0238-product-of-array-except-self.js)|Medium| 239|[Sliding Window Maximum](./0239-sliding-window-maximum.js)|Hard| +240|[Search a 2D Matrix II](./0240-search-a-2d-matrix-ii.js)|Medium| 242|[Valid Anagram](./0242-valid-anagram.js)|Easy| 257|[Binary Tree Paths](./0257-binary-tree-paths.js)|Easy| 258|[Add Digits](./0258-add-digits.js)|Easy| From db7608f246c2d1b93bd7e72d259c63bab0d50830 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 20 Feb 2025 00:26:34 -0600 Subject: [PATCH 660/919] Add solution #300 --- 0300-longest-increasing-subsequence.js | 26 ++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 27 insertions(+) create mode 100644 0300-longest-increasing-subsequence.js diff --git a/0300-longest-increasing-subsequence.js b/0300-longest-increasing-subsequence.js new file mode 100644 index 00000000..532b1e43 --- /dev/null +++ b/0300-longest-increasing-subsequence.js @@ -0,0 +1,26 @@ +/** + * 300. Longest Increasing Subsequence + * https://leetcode.com/problems/longest-increasing-subsequence/ + * Difficulty: Medium + * + * Given an integer array nums, return the length of the longest strictly increasing subsequence. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var lengthOfLIS = function(nums) { + if (!nums.length) return 0; + + const dp = new Array(nums.length).fill(1); + for (let i = 1; i < nums.length; i++) { + for (let j = 0; j < i; j++) { + if (nums[i] > nums[j]) { + dp[i] = Math.max(dp[i], dp[j] + 1); + } + } + } + + return Math.max(...dp); +}; diff --git a/README.md b/README.md index a3abc0a9..3dfacf51 100644 --- a/README.md +++ b/README.md @@ -238,6 +238,7 @@ 292|[Nim Game](./0292-nim-game.js)|Easy| 295|[Find Median from Data Stream](./0295-find-median-from-data-stream.js)|Hard| 297|[Serialize and Deserialize Binary Tree](./0297-serialize-and-deserialize-binary-tree.js)|Hard| +300|[Longest Increasing Subsequence](./0300-longest-increasing-subsequence.js)|Medium| 303|[Range Sum Query - Immutable](./0303-range-sum-query-immutable.js)|Easy| 306|[Additive Number](./0306-additive-number.js)|Medium| 309|[Best Time to Buy and Sell Stock with Cooldown](./0309-best-time-to-buy-and-sell-stock-with-cooldown.js)|Medium| From fc4628443364496552502a6b83c52bb0b4d81556 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 20 Feb 2025 00:27:03 -0600 Subject: [PATCH 661/919] Add solution #315 --- 0315-count-of-smaller-numbers-after-self.js | 31 +++++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 0315-count-of-smaller-numbers-after-self.js diff --git a/0315-count-of-smaller-numbers-after-self.js b/0315-count-of-smaller-numbers-after-self.js new file mode 100644 index 00000000..a1db056e --- /dev/null +++ b/0315-count-of-smaller-numbers-after-self.js @@ -0,0 +1,31 @@ +/** + * 315. Count of Smaller Numbers After Self + * https://leetcode.com/problems/count-of-smaller-numbers-after-self/ + * Difficulty: Hard + * + * Given an integer array nums, return an integer array counts where counts[i] is the + * number of smaller elements to the right of nums[i]. + */ + +/** + * @param {number[]} nums + * @return {number[]} + */ +var countSmaller = function(nums) { + const result = new Array(nums.length).fill(0); + const rank = new Map([...nums].sort((a, b) => a - b).map((n, i) => [n, i])); + const group = new Array(nums.length + 1).fill(0); + + for (let i = nums.length - 1; i >= 0; i--) { + const rankIndex = rank.get(nums[i]) + 1; + for (let j = rankIndex - 1, sum = 0; j > 0; j -= j & -j) { + sum += group[j]; + result[i] = sum; + } + for (let j = rankIndex; j < group.length; j += j & -j) { + group[j]++; + } + } + + return result; +}; diff --git a/README.md b/README.md index 3dfacf51..2894d04e 100644 --- a/README.md +++ b/README.md @@ -242,6 +242,7 @@ 303|[Range Sum Query - Immutable](./0303-range-sum-query-immutable.js)|Easy| 306|[Additive Number](./0306-additive-number.js)|Medium| 309|[Best Time to Buy and Sell Stock with Cooldown](./0309-best-time-to-buy-and-sell-stock-with-cooldown.js)|Medium| +315|[Count of Smaller Numbers After Self](./0315-count-of-smaller-numbers-after-self.js)|Hard| 316|[Remove Duplicate Letters](./0316-remove-duplicate-letters.js)|Medium| 318|[Maximum Product of Word Lengths](./0318-maximum-product-of-word-lengths.js)|Medium| 319|[Bulb Switcher](./0319-bulb-switcher.js)|Medium| From d81a73b33ebfeecbeeaf4bf4bd9b91422f9bc901 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 20 Feb 2025 00:28:11 -0600 Subject: [PATCH 662/919] Add solution #329 --- 0329-longest-increasing-path-in-a-matrix.js | 33 +++++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 0329-longest-increasing-path-in-a-matrix.js diff --git a/0329-longest-increasing-path-in-a-matrix.js b/0329-longest-increasing-path-in-a-matrix.js new file mode 100644 index 00000000..7611ada4 --- /dev/null +++ b/0329-longest-increasing-path-in-a-matrix.js @@ -0,0 +1,33 @@ +/** + * 329. Longest Increasing Path in a Matrix + * https://leetcode.com/problems/longest-increasing-path-in-a-matrix/ + * Difficulty: Hard + * + * Given an m x n integers matrix, return the length of the longest increasing path in matrix. + * + * From each cell, you can either move in four directions: left, right, up, or down. You may + * not move diagonally or move outside the boundary (i.e., wrap-around is not allowed). + */ + +/** + * @param {number[][]} matrix + * @return {number} + */ +var longestIncreasingPath = function(matrix) { + if (!matrix.length) return 0; + const m = matrix.length; + const n = matrix[0].length; + const cache = new Array(m).fill().map(() => new Array(n)); + const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; + + return Math.max(...new Array(m).fill().map((_, i) => + new Array(n).fill().map((_, j) => dfs(i, j))).flat()); + + function dfs(i, j) { + return cache[i][j] || (cache[i][j] = 1 + Math.max(...directions.map(([di, dj]) => { + const [a, b] = [i + di, j + dj]; + return a >= 0 && a < m && b >= 0 && b < n && matrix[a][b] > matrix[i][j] + ? dfs(a, b) : 0; + }))); + } +}; diff --git a/README.md b/README.md index 2894d04e..b6640733 100644 --- a/README.md +++ b/README.md @@ -249,6 +249,7 @@ 322|[Coin Change](./0322-coin-change.js)|Medium| 326|[Power of Three](./0326-power-of-three.js)|Easy| 328|[Odd Even Linked List](./0328-odd-even-linked-list.js)|Medium| +329|[Longest Increasing Path in a Matrix](./0329-longest-increasing-path-in-a-matrix.js)|Hard| 331|[Verify Preorder Serialization of a Binary Tree](./0331-verify-preorder-serialization-of-a-binary-tree.js)|Medium| 334|[Increasing Triplet Subsequence](./0334-increasing-triplet-subsequence.js)|Medium| 337|[House Robber III](./0337-house-robber-iii.js)|Medium| From 453a11de316e663ef49a2b7697b6b2d5d4543c50 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 20 Feb 2025 00:28:44 -0600 Subject: [PATCH 663/919] Add solution #378 --- ...kth-smallest-element-in-a-sorted-matrix.js | 21 +++++++++++++++++++ README.md | 1 + 2 files changed, 22 insertions(+) create mode 100644 0378-kth-smallest-element-in-a-sorted-matrix.js diff --git a/0378-kth-smallest-element-in-a-sorted-matrix.js b/0378-kth-smallest-element-in-a-sorted-matrix.js new file mode 100644 index 00000000..3de46f23 --- /dev/null +++ b/0378-kth-smallest-element-in-a-sorted-matrix.js @@ -0,0 +1,21 @@ +/** + * 378. Kth Smallest Element in a Sorted Matrix + * https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/ + * Difficulty: Medium + * + * Given an n x n matrix where each of the rows and columns is sorted in ascending order, + * return the kth smallest element in the matrix. + * + * Note that it is the kth smallest element in the sorted order, not the kth distinct element. + * + * You must find a solution with a memory complexity better than O(n2). + */ + +/** + * @param {number[][]} matrix + * @param {number} k + * @return {number} + */ +var kthSmallest = function(matrix, k) { + return matrix.flat().sort((a, b) => a - b)[k - 1]; +}; diff --git a/README.md b/README.md index b6640733..1807e5e4 100644 --- a/README.md +++ b/README.md @@ -266,6 +266,7 @@ 371|[Sum of Two Integers](./0371-sum-of-two-integers.js)|Medium| 372|[Super Pow](./0372-super-pow.js)|Medium| 374|[Guess Number Higher or Lower](./0374-guess-number-higher-or-lower.js)|Medium| +378|[Kth Smallest Element in a Sorted Matrix](./0378-kth-smallest-element-in-a-sorted-matrix.js)|Medium| 380|[Insert Delete GetRandom O(1)](./0380-insert-delete-getrandom-o1.js)|Medium| 383|[Ransom Note](./0383-ransom-note.js)|Easy| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| From 9a0357194349c943b8370f6a7206fcdd3ac0f733 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 20 Feb 2025 00:29:13 -0600 Subject: [PATCH 664/919] Add solution #416 --- 0416-partition-equal-subset-sum.js | 34 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 0416-partition-equal-subset-sum.js diff --git a/0416-partition-equal-subset-sum.js b/0416-partition-equal-subset-sum.js new file mode 100644 index 00000000..39cbd131 --- /dev/null +++ b/0416-partition-equal-subset-sum.js @@ -0,0 +1,34 @@ +/** + * 416. Partition Equal Subset Sum + * https://leetcode.com/problems/partition-equal-subset-sum/ + * Difficulty: Medium + * + * Given an integer array nums, return true if you can partition the array into two subsets + * such that the sum of the elements in both subsets is equal or false otherwise. + */ + +/** + * @param {number[]} nums + * @return {boolean} + */ +var canPartition = function(nums) { + const sum = nums.reduce((a, b) => a + b); + if (sum % 2) { + return false; + } + + const target = sum / 2; + let set = new Set([0]); + for (const n of nums) { + const next = new Set(set); + for (const value of set) { + if (value + n === target) { + return true; + } + next.add(value + n); + } + set = next; + } + + return false; +}; diff --git a/README.md b/README.md index 1807e5e4..faaad548 100644 --- a/README.md +++ b/README.md @@ -281,6 +281,7 @@ 412|[Fizz Buzz](./0412-fizz-buzz.js)|Easy| 414|[Third Maximum Number](./0414-third-maximum-number.js)|Easy| 415|[Add Strings](./0415-add-strings.js)|Easy| +416|[Partition Equal Subset Sum](./0416-partition-equal-subset-sum.js)|Medium| 419|[Battleships in a Board](./0419-battleships-in-a-board.js)|Medium| 434|[Number of Segments in a String](./0434-number-of-segments-in-a-string.js)|Easy| 435|[Non-overlapping Intervals](./0435-non-overlapping-intervals.js)|Medium| From 59ee0e53aaa4340ae228d3cbbd6184b0b5ed3e1e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 20 Feb 2025 00:30:00 -0600 Subject: [PATCH 665/919] Add solution #438 --- 0438-find-all-anagrams-in-a-string.js | 40 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 41 insertions(+) create mode 100644 0438-find-all-anagrams-in-a-string.js diff --git a/0438-find-all-anagrams-in-a-string.js b/0438-find-all-anagrams-in-a-string.js new file mode 100644 index 00000000..b73124d6 --- /dev/null +++ b/0438-find-all-anagrams-in-a-string.js @@ -0,0 +1,40 @@ +/** + * 438. Find All Anagrams in a String + * https://leetcode.com/problems/find-all-anagrams-in-a-string/ + * Difficulty: Medium + * + * Given two strings s and p, return an array of all the start indices of p's anagrams in s. + * + * You may return the answer in any order. + */ + +/** + * @param {string} s + * @param {string} p + * @return {number[]} + */ +var findAnagrams = function(s, p) { + const group = new Array(26).fill(0); + const result = []; + + for (let i = 0; i < p.length; i++) { + group[p.charCodeAt(i) - 97]--; + } + + outer: for (let i = 0; i < s.length; i++) { + group[s.charCodeAt(i) - 97]++; + if (i < p.length - 1) { + continue; + } else if (i > p.length - 1) { + group[s.charCodeAt(i - p.length) - 97]--; + } + for (let j = 0; j < 26; j++) { + if (group[j]) { + continue outer; + } + } + result.push(i + 1 - p.length); + } + + return result; +}; diff --git a/README.md b/README.md index faaad548..5fc976c5 100644 --- a/README.md +++ b/README.md @@ -286,6 +286,7 @@ 434|[Number of Segments in a String](./0434-number-of-segments-in-a-string.js)|Easy| 435|[Non-overlapping Intervals](./0435-non-overlapping-intervals.js)|Medium| 437|[Path Sum III](./0437-path-sum-iii.js)|Medium| +438|[Find All Anagrams in a String](./0438-find-all-anagrams-in-a-string.js)|Medium| 441|[Arranging Coins](./0441-arranging-coins.js)|Easy| 442|[Find All Duplicates in an Array](./0442-find-all-duplicates-in-an-array.js)|Medium| 443|[String Compression](./0443-string-compression.js)|Medium| From 7e66bba145fa820eb358baee66a9ef10c3b1d30e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 20 Feb 2025 00:30:51 -0600 Subject: [PATCH 666/919] Add solution #543 --- 0543-diameter-of-binary-tree.js | 38 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 39 insertions(+) create mode 100644 0543-diameter-of-binary-tree.js diff --git a/0543-diameter-of-binary-tree.js b/0543-diameter-of-binary-tree.js new file mode 100644 index 00000000..423dc4c4 --- /dev/null +++ b/0543-diameter-of-binary-tree.js @@ -0,0 +1,38 @@ +/** + * 543. Diameter of Binary Tree + * https://leetcode.com/problems/diameter-of-binary-tree/ + * Difficulty: Easy + * + * Given the root of a binary tree, return the length of the diameter of the tree. + * + * The diameter of a binary tree is the length of the longest path between any two nodes in a + * tree. This path may or may not pass through the root. + * + * The length of a path between two nodes is represented by the number of edges between them. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number} + */ +var diameterOfBinaryTree = function(root) { + let result = 0; + maxDepth(root); + return result; + + function maxDepth(node) { + if (!node) return 0; + const left = maxDepth(node.left); + const right = maxDepth(node.right); + result = Math.max(result, left + right); + return Math.max(left, right) + 1; + } +}; diff --git a/README.md b/README.md index 5fc976c5..cae5a9aa 100644 --- a/README.md +++ b/README.md @@ -318,6 +318,7 @@ 521|[Longest Uncommon Subsequence I](./0521-longest-uncommon-subsequence-i.js)|Easy| 541|[Reverse String II](./0541-reverse-string-ii.js)|Easy| 542|[01 Matrix](./0542-01-matrix.js)|Medium| +543|[Diameter of Binary Tree](./0543-diameter-of-binary-tree.js)|Easy| 547|[Number of Provinces](./0547-number-of-provinces.js)|Medium| 551|[Student Attendance Record I](./0551-student-attendance-record-i.js)|Easy| 557|[Reverse Words in a String III](./0557-reverse-words-in-a-string-iii.js)|Easy| From 2ece86c96396e717f825c71a694d09517cebe6e8 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 20 Feb 2025 00:31:29 -0600 Subject: [PATCH 667/919] Add solution #560 --- 0560-subarray-sum-equals-k.js | 28 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 29 insertions(+) create mode 100644 0560-subarray-sum-equals-k.js diff --git a/0560-subarray-sum-equals-k.js b/0560-subarray-sum-equals-k.js new file mode 100644 index 00000000..944329a7 --- /dev/null +++ b/0560-subarray-sum-equals-k.js @@ -0,0 +1,28 @@ +/** + * 560. Subarray Sum Equals K + * https://leetcode.com/problems/subarray-sum-equals-k/ + * Difficulty: Medium + * + * Given an array of integers nums and an integer k, return the total number of subarrays + * whose sum equals to k. + * + * A subarray is a contiguous non-empty sequence of elements within an array. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var subarraySum = function(nums, k) { + const map = new Map([[0, 1]]); + let result = 0; + + for (let i = 0, count = 0; i < nums.length; i++) { + count += nums[i]; + result += map.get(count - k) ?? 0; + map.set(count, (map.get(count) ?? 0) + 1); + } + + return result; +}; diff --git a/README.md b/README.md index cae5a9aa..dbd77633 100644 --- a/README.md +++ b/README.md @@ -322,6 +322,7 @@ 547|[Number of Provinces](./0547-number-of-provinces.js)|Medium| 551|[Student Attendance Record I](./0551-student-attendance-record-i.js)|Easy| 557|[Reverse Words in a String III](./0557-reverse-words-in-a-string-iii.js)|Easy| +560|[Subarray Sum Equals K](./0560-subarray-sum-equals-k.js)|Medium| 563|[Binary Tree Tilt](./0563-binary-tree-tilt.js)|Easy| 565|[Array Nesting](./0565-array-nesting.js)|Medium| 566|[Reshape the Matrix](./0566-reshape-the-matrix.js)|Easy| From 07e6921bebb9c4ea795653c6e14c25316c043503 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 20 Feb 2025 19:28:59 -0600 Subject: [PATCH 668/919] Add solution #212 --- 0212-word-search-ii.js | 49 ++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 50 insertions(+) create mode 100644 0212-word-search-ii.js diff --git a/0212-word-search-ii.js b/0212-word-search-ii.js new file mode 100644 index 00000000..f8a2c595 --- /dev/null +++ b/0212-word-search-ii.js @@ -0,0 +1,49 @@ +/** + * 212. Word Search II + * https://leetcode.com/problems/word-search-ii/ + * Difficulty: Hard + * + * Given an m x n board of characters and a list of strings words, return all words on the board. + * + * Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells + * are horizontally or vertically neighboring. The same letter cell may not be used more than once + * in a word. + */ + +/** + * @param {character[][]} board + * @param {string[]} words + * @return {string[]} + */ +var findWords = function(board, words) { + const root = {}; + const result = new Set(); + const m = board.length; + const n = board[0].length; + + words.forEach(w => w.split('').reduce((n, c) => n[c] = n[c] || {}, root).word = w); + + for (let i = 0; i < m; i++) { + for (let j = 0; j < n; j++) { + dfs(i, j, root); + } + } + + return Array.from(result); + + function dfs(i, j, node) { + const char = board[i][j]; + const next = node[char]; + if (!next) return; + if (next.word) { + result.add(next.word); + } + board[i][j] = '#'; + for (const [di, dj] of [[0, 1], [1, 0], [0, -1], [-1, 0]]) { + if (i + di >= 0 && i + di < m && j + dj >= 0 && j + dj < n && board[i + di][j + dj] !== '#') { + dfs(i + di, j + dj, next); + } + } + board[i][j] = char; + } +}; diff --git a/README.md b/README.md index dbd77633..82cf4563 100644 --- a/README.md +++ b/README.md @@ -193,6 +193,7 @@ 209|[Minimum Size Subarray Sum](./0209-minimum-size-subarray-sum.js)|Medium| 210|[Course Schedule II](./0210-course-schedule-ii.js)|Medium| 211|[Design Add and Search Words Data Structure](./0211-design-add-and-search-words-data-structure.js)|Medium| +212|[Word Search II](./0212-word-search-ii.js)|Hard| 213|[House Robber II](./0213-house-robber-ii.js)|Medium| 214|[Shortest Palindrome](./0214-shortest-palindrome.js)|Hard| 215|[Kth Largest Element in an Array](./0215-kth-largest-element-in-an-array.js)|Medium| From fd2981f3d74214ae8e60dc8f705cb7bfeb3445cd Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 20 Feb 2025 19:34:53 -0600 Subject: [PATCH 669/919] Add solution #218 --- 0218-the-skyline-problem.js | 54 +++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 55 insertions(+) create mode 100644 0218-the-skyline-problem.js diff --git a/0218-the-skyline-problem.js b/0218-the-skyline-problem.js new file mode 100644 index 00000000..346c802a --- /dev/null +++ b/0218-the-skyline-problem.js @@ -0,0 +1,54 @@ +/** + * 218. The Skyline Problem + * https://leetcode.com/problems/the-skyline-problem/ + * Difficulty: Hard + * + * A city's skyline is the outer contour of the silhouette formed by all the buildings in that + * city when viewed from a distance. Given the locations and heights of all the buildings, + * return the skyline formed by these buildings collectively. + * + * The geometric information of each building is given in the array buildings where + * buildings[i] = [lefti, righti, heighti]: + * - lefti is the x coordinate of the left edge of the ith building. + * - righti is the x coordinate of the right edge of the ith building. + * - heighti is the height of the ith building. + * + * You may assume all buildings are perfect rectangles grounded on an absolutely flat surface + * at height 0. + * + * The skyline should be represented as a list of "key points" sorted by their x-coordinate + * in the form [[x1,y1],[x2,y2],...]. Each key point is the left endpoint of some horizontal + * segment in the skyline except the last point in the list, which always has a y-coordinate + * 0 and is used to mark the skyline's termination where the rightmost building ends. Any ground + * between the leftmost and rightmost buildings should be part of the skyline's contour. + * + * Note: There must be no consecutive horizontal lines of equal height in the output skyline. + * For instance, [...,[2 3],[4 5],[7 5],[11 5],[12 7],...] is not acceptable; the three lines + * of height 5 should be merged into one in the final output as such: [...,[2 3],[4 5],[12 7],...] + */ + +/** + * @param {number[][]} buildings + * @return {number[][]} + */ +var getSkyline = function(buildings) { + const result = []; + const events = buildings.flatMap(([l, r, h]) => [[l, -h], [r, h]]); + + events.sort((a, b) => a[0] - b[0] || a[1] - b[1]); + + for (let i = 0, previous = 0, heights = [0]; i < events.length; i++) { + const [x, h] = events[i]; + if (h < 0) { + heights.push(-h); + } else { + heights.splice(heights.indexOf(h), 1); + } + const value = Math.max(...heights); + if (value !== previous) { + result.push([x, previous = value]); + } + } + + return result; +}; diff --git a/README.md b/README.md index 82cf4563..83dc8b89 100644 --- a/README.md +++ b/README.md @@ -199,6 +199,7 @@ 215|[Kth Largest Element in an Array](./0215-kth-largest-element-in-an-array.js)|Medium| 216|[Combination Sum III](./0216-combination-sum-iii.js)|Medium| 217|[Contains Duplicate](./0217-contains-duplicate.js)|Easy| +218|[The Skyline Problem](./0218-the-skyline-problem.js)|Hard| 219|[Contains Duplicate II](./0219-contains-duplicate-ii.js)|Easy| 220|[Contains Duplicate III](./0220-contains-duplicate-iii.js)|Hard| 222|[Count Complete Tree Nodes](./0222-count-complete-tree-nodes.js)|Easy| From 10544b55c1039c05f33bfaeeb517bf2a3e1feb84 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 20 Feb 2025 19:36:41 -0600 Subject: [PATCH 670/919] Add solution #221 --- 0221-maximal-square.js | 27 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 28 insertions(+) create mode 100644 0221-maximal-square.js diff --git a/0221-maximal-square.js b/0221-maximal-square.js new file mode 100644 index 00000000..fc4e47d2 --- /dev/null +++ b/0221-maximal-square.js @@ -0,0 +1,27 @@ +/** + * 221. Maximal Square + * https://leetcode.com/problems/maximal-square/ + * Difficulty: Medium + * + * Given an m x n binary matrix filled with 0's and 1's, find the largest square containing only + * 1's and return its area. + */ + +/** + * @param {character[][]} matrix + * @return {number} + */ +var maximalSquare = function(matrix) { + const dp = [...new Array(matrix.length + 1)].map(() => new Array(matrix[0].length + 1).fill(0)); + let max = 0; + + for (let i = 1; i < dp.length; i++) { + for (let j = 1; j < dp[0].length; j++) { + if (matrix[i - 1][j - 1] === '1') { + max = Math.max(max, dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]) + 1); + } + } + } + + return max ** 2; +}; diff --git a/README.md b/README.md index 83dc8b89..3e879b53 100644 --- a/README.md +++ b/README.md @@ -202,6 +202,7 @@ 218|[The Skyline Problem](./0218-the-skyline-problem.js)|Hard| 219|[Contains Duplicate II](./0219-contains-duplicate-ii.js)|Easy| 220|[Contains Duplicate III](./0220-contains-duplicate-iii.js)|Hard| +221|[Maximal Square](./0221-maximal-square.js)|Medium| 222|[Count Complete Tree Nodes](./0222-count-complete-tree-nodes.js)|Easy| 224|[Basic Calculator](./0224-basic-calculator.js)|Hard| 225|[Implement Stack using Queues](./0225-implement-stack-using-queues.js)|Easy| From 01813e3f1b6d4c162d9515325151df7e1ce0d87a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 20 Feb 2025 19:37:38 -0600 Subject: [PATCH 671/919] Add solution #223 --- 0223-rectangle-area.js | 31 +++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 0223-rectangle-area.js diff --git a/0223-rectangle-area.js b/0223-rectangle-area.js new file mode 100644 index 00000000..7a609430 --- /dev/null +++ b/0223-rectangle-area.js @@ -0,0 +1,31 @@ +/** + * 223. Rectangle Area + * https://leetcode.com/problems/rectangle-area/ + * Difficulty: Medium + * + * Given the coordinates of two rectilinear rectangles in a 2D plane, return the total area + * covered by the two rectangles. + * + * The first rectangle is defined by its bottom-left corner (ax1, ay1) and its top-right corner + * (ax2, ay2). + * + * The second rectangle is defined by its bottom-left corner (bx1, by1) and its top-right corner + * (bx2, by2). + */ + +/** + * @param {number} ax1 + * @param {number} ay1 + * @param {number} ax2 + * @param {number} ay2 + * @param {number} bx1 + * @param {number} by1 + * @param {number} bx2 + * @param {number} by2 + * @return {number} + */ +var computeArea = function(ax1, ay1, ax2, ay2, bx1, by1, bx2, by2) { + return (ax2 - ax1) * (ay2 - ay1) + (bx2 - bx1) * (by2 - by1) + - Math.max(0, Math.min(ax2, bx2) - Math.max(ax1, bx1)) + * Math.max(0, Math.min(ay2, by2) - Math.max(ay1, by1)); +}; diff --git a/README.md b/README.md index 3e879b53..8dd3032d 100644 --- a/README.md +++ b/README.md @@ -204,6 +204,7 @@ 220|[Contains Duplicate III](./0220-contains-duplicate-iii.js)|Hard| 221|[Maximal Square](./0221-maximal-square.js)|Medium| 222|[Count Complete Tree Nodes](./0222-count-complete-tree-nodes.js)|Easy| +223|[Rectangle Area](./0223-rectangle-area.js)|Medium| 224|[Basic Calculator](./0224-basic-calculator.js)|Hard| 225|[Implement Stack using Queues](./0225-implement-stack-using-queues.js)|Easy| 226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy| From 487275facc02af46262ec6e5f090ac7ecc27166f Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 20 Feb 2025 19:39:01 -0600 Subject: [PATCH 672/919] Add solution #227 --- 0227-basic-calculator-ii.js | 37 +++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 38 insertions(+) create mode 100644 0227-basic-calculator-ii.js diff --git a/0227-basic-calculator-ii.js b/0227-basic-calculator-ii.js new file mode 100644 index 00000000..8572870f --- /dev/null +++ b/0227-basic-calculator-ii.js @@ -0,0 +1,37 @@ +/** + * 227. Basic Calculator II + * https://leetcode.com/problems/basic-calculator-ii/ + * Difficulty: Medium + * + * Given a string s which represents an expression, evaluate this expression and return its value. + * + * The integer division should truncate toward zero. + * + * You may assume that the given expression is always valid. All intermediate results will be in + * the range of [-231, 231 - 1]. + * + * Note: You are not allowed to use any built-in function which evaluates strings as mathematical + * expressions, such as eval(). + */ + +/** + * @param {string} s + * @return {number} + */ +var calculate = function(s) { + const stack = []; + + for (let i = 0, num = 0, sign = '+'; i < s.length; i++) { + if (s[i] >= '0' && s[i] <= '9') num = num * 10 + (s[i] - '0'); + if ((s[i] < '0' && s[i] !== ' ') || i === s.length - 1) { + if (sign === '+') stack.push(num); + else if (sign === '-') stack.push(-num); + else if (sign === '*') stack.push(stack.pop() * num); + else if (sign === '/') stack.push(Math.trunc(stack.pop() / num)); + sign = s[i]; + num = 0; + } + } + + return stack.reduce((a, b) => a + b, 0); +}; diff --git a/README.md b/README.md index 8dd3032d..46cee80a 100644 --- a/README.md +++ b/README.md @@ -208,6 +208,7 @@ 224|[Basic Calculator](./0224-basic-calculator.js)|Hard| 225|[Implement Stack using Queues](./0225-implement-stack-using-queues.js)|Easy| 226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy| +227|[Basic Calculator II](./0227-basic-calculator-ii.js)|Medium| 228|[Summary Ranges](./0228-summary-ranges.js)|Easy| 229|[Majority Element II](./0229-majority-element-ii.js)|Medium| 230|[Kth Smallest Element in a BST](./0230-kth-smallest-element-in-a-bst.js)|Medium| From a364a0d5aa22b51f0506618851233fe622e5d951 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 21 Feb 2025 00:01:32 -0600 Subject: [PATCH 673/919] Add solution #241 --- 0241-different-ways-to-add-parentheses.js | 31 +++++++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 0241-different-ways-to-add-parentheses.js diff --git a/0241-different-ways-to-add-parentheses.js b/0241-different-ways-to-add-parentheses.js new file mode 100644 index 00000000..6823cafd --- /dev/null +++ b/0241-different-ways-to-add-parentheses.js @@ -0,0 +1,31 @@ +/** + * 241. Different Ways to Add Parentheses + * https://leetcode.com/problems/different-ways-to-add-parentheses/ + * Difficulty: Medium + * + * Given a string expression of numbers and operators, return all possible results from + * computing all the different possible ways to group numbers and operators. You may + * return the answer in any order. + * + * The test cases are generated such that the output values fit in a 32-bit integer and + * the number of different results does not exceed 104. + */ + +/** + * @param {string} expression + * @return {number[]} + */ +var diffWaysToCompute = function(expression) { + const results = []; + + for (let i = 0; i < expression.length; i++) { + if ('+-*'.includes(expression[i])) { + const left = diffWaysToCompute(expression.slice(0, i)); + const right = diffWaysToCompute(expression.slice(i + 1)); + left.forEach(l => right.forEach(r => + results.push(expression[i] === '+' ? l + r : expression[i] === '-' ? l - r : l * r))); + } + } + + return results.length ? results : [+expression]; +}; diff --git a/README.md b/README.md index 46cee80a..42fbc8fa 100644 --- a/README.md +++ b/README.md @@ -222,6 +222,7 @@ 238|[Product of Array Except Self](./0238-product-of-array-except-self.js)|Medium| 239|[Sliding Window Maximum](./0239-sliding-window-maximum.js)|Hard| 240|[Search a 2D Matrix II](./0240-search-a-2d-matrix-ii.js)|Medium| +241|[Different Ways to Add Parentheses](./0241-different-ways-to-add-parentheses.js)|Medium| 242|[Valid Anagram](./0242-valid-anagram.js)|Easy| 257|[Binary Tree Paths](./0257-binary-tree-paths.js)|Easy| 258|[Add Digits](./0258-add-digits.js)|Easy| From 55d67721b018008475b85f9846f721abb10501f3 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 21 Feb 2025 00:03:02 -0600 Subject: [PATCH 674/919] Add solution #299 --- 0299-bulls-and-cows.js | 44 ++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 45 insertions(+) create mode 100644 0299-bulls-and-cows.js diff --git a/0299-bulls-and-cows.js b/0299-bulls-and-cows.js new file mode 100644 index 00000000..5becd2dc --- /dev/null +++ b/0299-bulls-and-cows.js @@ -0,0 +1,44 @@ +/** + * 299. Bulls and Cows + * https://leetcode.com/problems/bulls-and-cows/ + * Difficulty: Medium + * + * You are playing the Bulls and Cows game with your friend. + * + * You write down a secret number and ask your friend to guess what the number is. + * When your friend makes a guess, you provide a hint with the following info: + * - The number of "bulls", which are digits in the guess that are in the correct position. + * - The number of "cows", which are digits in the guess that are in your secret number but + * are located in the wrong position. Specifically, the non-bull digits in the guess that + * could be rearranged such that they become bulls. + * + * Given the secret number secret and your friend's guess guess, return the hint for your + * friend's guess. + * + * The hint should be formatted as "xAyB", where x is the number of bulls and y is the number + * of cows. Note that both secret and guess may contain duplicate digits. + */ + +/** + * @param {string} secret + * @param {string} guess + * @return {string} + */ +var getHint = function(secret, guess) { + const map = Array(10).fill(0); + let a = 0; + let b = 0; + + for (const i in secret) { + if (secret[i] === guess[i]) { + a++; + } else { + map[secret[i]]++; + map[guess[i]]--; + b += map[secret[i]] <= 0; + b += map[guess[i]] >= 0; + } + } + + return `${a}A${b}B`; +}; diff --git a/README.md b/README.md index 42fbc8fa..9f62adbd 100644 --- a/README.md +++ b/README.md @@ -244,6 +244,7 @@ 292|[Nim Game](./0292-nim-game.js)|Easy| 295|[Find Median from Data Stream](./0295-find-median-from-data-stream.js)|Hard| 297|[Serialize and Deserialize Binary Tree](./0297-serialize-and-deserialize-binary-tree.js)|Hard| +299|[Bulls and Cows](./0299-bulls-and-cows.js)|Medium| 300|[Longest Increasing Subsequence](./0300-longest-increasing-subsequence.js)|Medium| 303|[Range Sum Query - Immutable](./0303-range-sum-query-immutable.js)|Easy| 306|[Additive Number](./0306-additive-number.js)|Medium| From fbbd1961dc22fc46b494126bc04d2bd7ed198cad Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 21 Feb 2025 00:03:45 -0600 Subject: [PATCH 675/919] Add solution #301 --- 0301-remove-invalid-parentheses.js | 48 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 49 insertions(+) create mode 100644 0301-remove-invalid-parentheses.js diff --git a/0301-remove-invalid-parentheses.js b/0301-remove-invalid-parentheses.js new file mode 100644 index 00000000..31f9ffac --- /dev/null +++ b/0301-remove-invalid-parentheses.js @@ -0,0 +1,48 @@ +/** + * 301. Remove Invalid Parentheses + * https://leetcode.com/problems/remove-invalid-parentheses/ + * Difficulty: Hard + * + * Given a string s that contains parentheses and letters, remove the minimum number of + * invalid parentheses to make the input string valid. + * + * Return a list of unique strings that are valid with the minimum number of removals. + * You may return the answer in any order. + */ + +/** + * @param {string} s + * @return {string[]} + */ +var removeInvalidParentheses = function(s) { + const result = new Set(); + let minRemoved = Infinity; + + backtrack(s, 0, 0, 0, 0, ''); + + return Array.from(result); + + function backtrack(str, index, open, close, removed, curr) { + if (index === s.length) { + if (open === close && removed <= minRemoved) { + if (removed < minRemoved) { + result.clear(); + minRemoved = removed; + } + result.add(curr); + } + return; + } + + if (s[index] !== '(' && s[index] !== ')') { + backtrack(str, index + 1, open, close, removed, curr + s[index]); + } else { + backtrack(str, index + 1, open, close, removed + 1, curr); + if (s[index] === '(') { + backtrack(str, index + 1, open + 1, close, removed, curr + '('); + } else if (close < open) { + backtrack(str, index + 1, open, close + 1, removed, curr + ')'); + } + } + } +}; diff --git a/README.md b/README.md index 9f62adbd..4ac9b9cb 100644 --- a/README.md +++ b/README.md @@ -246,6 +246,7 @@ 297|[Serialize and Deserialize Binary Tree](./0297-serialize-and-deserialize-binary-tree.js)|Hard| 299|[Bulls and Cows](./0299-bulls-and-cows.js)|Medium| 300|[Longest Increasing Subsequence](./0300-longest-increasing-subsequence.js)|Medium| +301|[Remove Invalid Parentheses](./0301-remove-invalid-parentheses.js)|Hard| 303|[Range Sum Query - Immutable](./0303-range-sum-query-immutable.js)|Easy| 306|[Additive Number](./0306-additive-number.js)|Medium| 309|[Best Time to Buy and Sell Stock with Cooldown](./0309-best-time-to-buy-and-sell-stock-with-cooldown.js)|Medium| From 5ca4b41598419b6b0e9af7ff2d5151c3ca44b251 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 21 Feb 2025 00:05:03 -0600 Subject: [PATCH 676/919] Add solution #304 --- 0304-range-sum-query-2d-immutable.js | 45 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 46 insertions(+) create mode 100644 0304-range-sum-query-2d-immutable.js diff --git a/0304-range-sum-query-2d-immutable.js b/0304-range-sum-query-2d-immutable.js new file mode 100644 index 00000000..9bb6e7cd --- /dev/null +++ b/0304-range-sum-query-2d-immutable.js @@ -0,0 +1,45 @@ +/** + * 304. Range Sum Query 2D - Immutable + * https://leetcode.com/problems/range-sum-query-2d-immutable/ + * Difficulty: Medium + * + * Given a 2D matrix matrix, handle multiple queries of the following type: + * - Calculate the sum of the elements of matrix inside the rectangle defined by its upper + * left corner (row1, col1) and lower right corner (row2, col2). + * + * Implement the NumMatrix class: + * - NumMatrix(int[][] matrix) Initializes the object with the integer matrix matrix. + * - int sumRegion(int row1, int col1, int row2, int col2) Returns the sum of the elements + * of matrix inside the rectangle defined by its upper left corner (row1, col1) and lower + * right corner (row2, col2). + * + * You must design an algorithm where sumRegion works on O(1) time complexity. + */ + +/** + * @param {number[][]} matrix + */ +var NumMatrix = function(matrix) { + this.sums = new Array(matrix.length + 1).fill().map(() => { + return new Array(matrix[0].length + 1).fill(0); + }); + + for (let i = 1; i <= matrix.length; i++) { + for (let j = 1; j <= matrix[0].length; j++) { + this.sums[i][j] = matrix[i - 1][j - 1] + this.sums[i - 1][j] + + this.sums[i][j - 1] - this.sums[i - 1][j - 1]; + } + } +}; + +/** + * @param {number} row1 + * @param {number} col1 + * @param {number} row2 + * @param {number} col2 + * @return {number} + */ +NumMatrix.prototype.sumRegion = function(row1, col1, row2, col2) { + return this.sums[row2 + 1][col2 + 1] - this.sums[row2 + 1][col1] + - this.sums[row1][col2 + 1] + this.sums[row1][col1]; +}; diff --git a/README.md b/README.md index 4ac9b9cb..7aef868c 100644 --- a/README.md +++ b/README.md @@ -248,6 +248,7 @@ 300|[Longest Increasing Subsequence](./0300-longest-increasing-subsequence.js)|Medium| 301|[Remove Invalid Parentheses](./0301-remove-invalid-parentheses.js)|Hard| 303|[Range Sum Query - Immutable](./0303-range-sum-query-immutable.js)|Easy| +304|[Range Sum Query 2D - Immutable](./0304-range-sum-query-2d-immutable.js)|Medium| 306|[Additive Number](./0306-additive-number.js)|Medium| 309|[Best Time to Buy and Sell Stock with Cooldown](./0309-best-time-to-buy-and-sell-stock-with-cooldown.js)|Medium| 315|[Count of Smaller Numbers After Self](./0315-count-of-smaller-numbers-after-self.js)|Hard| From b48412170937be8da2717adc7668c51de6c845f4 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 21 Feb 2025 00:06:19 -0600 Subject: [PATCH 677/919] Add solution #307 --- 0307-range-sum-query-mutable.js | 78 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 79 insertions(+) create mode 100644 0307-range-sum-query-mutable.js diff --git a/0307-range-sum-query-mutable.js b/0307-range-sum-query-mutable.js new file mode 100644 index 00000000..726ff678 --- /dev/null +++ b/0307-range-sum-query-mutable.js @@ -0,0 +1,78 @@ +/** + * 307. Range Sum Query - Mutable + * https://leetcode.com/problems/range-sum-query-mutable/ + * Difficulty: Medium + * + * Given an integer array nums, handle multiple queries of the following types: + * 1. Update the value of an element in nums. + * 2. Calculate the sum of the elements of nums between indices left and right inclusive + * where left <= right. + * + * Implement the NumArray class: + * - NumArray(int[] nums) Initializes the object with the integer array nums. + * - void update(int index, int val) Updates the value of nums[index] to be val. + * - int sumRange(int left, int right) Returns the sum of the elements of nums between + * indices left and right inclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right]). + */ + +/** + * @param {number[]} nums + */ +var NumArray = function(nums) { + this.n = nums.length; + this.tree = new Array(2 * this.n); + + for (let i = 0; i < this.n; i++) { + this.tree[this.n + i] = nums[i]; + } + + for (let i = this.n - 1; i > 0; i--) { + this.tree[i] = this.tree[i * 2] + this.tree[i * 2 + 1]; + } +}; + +/** + * @param {number} index + * @param {number} val + * @return {void} + */ +NumArray.prototype.update = function(index, val) { + let position = this.n + index; + this.tree[position] = val; + + while (position) { + let left = position; + let right = position; + if (position % 2 === 0) { + right = position + 1; + } else { + left = position - 1; + } + this.tree[position >> 1] = this.tree[left] + this.tree[right]; + position >>= 1; + } +}; + +/** + * @param {number} left + * @param {number} right + * @return {number} + */ +NumArray.prototype.sumRange = function(left, right) { + let sum = 0; + let l = this.n + left; + let r = this.n + right + 1; + + while (l < r) { + if (l % 2 == 1) { + sum += this.tree[l++]; + } + if (r % 2 == 1) { + sum += this.tree[--r]; + } + l >>= 1; + r >>= 1; + } + + return sum; +}; diff --git a/README.md b/README.md index 7aef868c..c4f035ff 100644 --- a/README.md +++ b/README.md @@ -250,6 +250,7 @@ 303|[Range Sum Query - Immutable](./0303-range-sum-query-immutable.js)|Easy| 304|[Range Sum Query 2D - Immutable](./0304-range-sum-query-2d-immutable.js)|Medium| 306|[Additive Number](./0306-additive-number.js)|Medium| +307|[Range Sum Query - Mutable](./0307-range-sum-query-mutable.js)|Medium| 309|[Best Time to Buy and Sell Stock with Cooldown](./0309-best-time-to-buy-and-sell-stock-with-cooldown.js)|Medium| 315|[Count of Smaller Numbers After Self](./0315-count-of-smaller-numbers-after-self.js)|Hard| 316|[Remove Duplicate Letters](./0316-remove-duplicate-letters.js)|Medium| From 9886756cfca3a5304fbc05e7e5d77380a5165370 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 21 Feb 2025 00:08:09 -0600 Subject: [PATCH 678/919] Add solution #324 --- 0324-wiggle-sort-ii.js | 21 +++++++++++++++++++++ README.md | 1 + 2 files changed, 22 insertions(+) create mode 100644 0324-wiggle-sort-ii.js diff --git a/0324-wiggle-sort-ii.js b/0324-wiggle-sort-ii.js new file mode 100644 index 00000000..649897d7 --- /dev/null +++ b/0324-wiggle-sort-ii.js @@ -0,0 +1,21 @@ +/** + * 324. Wiggle Sort II + * https://leetcode.com/problems/wiggle-sort-ii/ + * Difficulty: Medium + * + * Given an integer array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3] + * + * You may assume the input array always has a valid answer. + */ + +/** + * @param {number[]} nums + * @return {void} Do not return anything, modify nums in-place instead. + */ +var wiggleSort = function(nums) { + nums.sort((a, b) => a - b); + const m = Math.floor((nums.length - 1) / 2); + for (let i = 0, l = m, r = nums.length - 1, t = [...nums]; i < nums.length; i++) { + nums[i] = i % 2 ? t[r--] : t[l--]; + } +}; diff --git a/README.md b/README.md index c4f035ff..0d844c24 100644 --- a/README.md +++ b/README.md @@ -257,6 +257,7 @@ 318|[Maximum Product of Word Lengths](./0318-maximum-product-of-word-lengths.js)|Medium| 319|[Bulb Switcher](./0319-bulb-switcher.js)|Medium| 322|[Coin Change](./0322-coin-change.js)|Medium| +324|[Wiggle Sort II](./0324-wiggle-sort-ii.js)|Medium| 326|[Power of Three](./0326-power-of-three.js)|Easy| 328|[Odd Even Linked List](./0328-odd-even-linked-list.js)|Medium| 329|[Longest Increasing Path in a Matrix](./0329-longest-increasing-path-in-a-matrix.js)|Hard| From f5aa3ca8678e19a671679f4cf140e1a5ba5d4f5b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 21 Feb 2025 00:10:02 -0600 Subject: [PATCH 679/919] Add solution #341 --- 0341-flatten-nested-list-iterator.js | 64 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 65 insertions(+) create mode 100644 0341-flatten-nested-list-iterator.js diff --git a/0341-flatten-nested-list-iterator.js b/0341-flatten-nested-list-iterator.js new file mode 100644 index 00000000..869726e6 --- /dev/null +++ b/0341-flatten-nested-list-iterator.js @@ -0,0 +1,64 @@ +/** + * 341. Flatten Nested List Iterator + * https://leetcode.com/problems/flatten-nested-list-iterator/ + * Difficulty: Medium + * + * You are given a nested list of integers nestedList. Each element is either an integer or a list + * whose elements may also be integers or other lists. Implement an iterator to flatten it. + * + * Implement the NestedIterator class: + * - NestedIterator(List nestedList) Initializes the iterator with the nested list + * nestedList. + * - int next() Returns the next integer in the nested list. + * - boolean hasNext() Returns true if there are still some integers in the nested list and false + * otherwise. + * + * Your code will be tested with the following pseudocode: + * initialize iterator with nestedList + * res = [] + * while iterator.hasNext() + * append iterator.next() to the end of res + * return res + * + * If res matches the expected flattened list, then your code will be judged as correct. + */ + +/** + * @constructor + * @param {NestedInteger[]} nestedList + */ +var NestedIterator = function(nestedList) { + this.stack = []; + this.flatten(nestedList); +}; + +/** + * @this NestedIterator + * @param {NestedInteger[]} nestedList + * @returns {void} + */ +NestedIterator.prototype.flatten = function(list) { + for (let i = list.length - 1; i >= 0; i--) { + this.stack.push(list[i]); + } +}; + +/** + * @this NestedIterator + * @returns {boolean} + */ +NestedIterator.prototype.hasNext = function() { + while (this.stack.length > 0 && !this.stack[this.stack.length - 1].isInteger()) { + const nested = this.stack.pop().getList(); + this.flatten(nested); + } + return this.stack.length > 0; +}; + +/** + * @this NestedIterator + * @returns {integer} + */ +NestedIterator.prototype.next = function() { + return this.stack.pop().getInteger(); +}; diff --git a/README.md b/README.md index 0d844c24..cfe5646b 100644 --- a/README.md +++ b/README.md @@ -265,6 +265,7 @@ 334|[Increasing Triplet Subsequence](./0334-increasing-triplet-subsequence.js)|Medium| 337|[House Robber III](./0337-house-robber-iii.js)|Medium| 338|[Counting Bits](./0338-counting-bits.js)|Easy| +341|[Flatten Nested List Iterator](./0341-flatten-nested-list-iterator.js)|Medium| 342|[Power of Four](./0342-power-of-four.js)|Easy| 344|[Reverse String](./0344-reverse-string.js)|Easy| 345|[Reverse Vowels of a String](./0345-reverse-vowels-of-a-string.js)|Easy| From cd33d3390c6ab8da844c9f615bc88c71bb753fe5 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 21 Feb 2025 00:10:51 -0600 Subject: [PATCH 680/919] Add solution #384 --- 0384-shuffle-an-array.js | 40 ++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 41 insertions(+) create mode 100644 0384-shuffle-an-array.js diff --git a/0384-shuffle-an-array.js b/0384-shuffle-an-array.js new file mode 100644 index 00000000..eed98e2e --- /dev/null +++ b/0384-shuffle-an-array.js @@ -0,0 +1,40 @@ +/** + * 384. Shuffle an Array + * https://leetcode.com/problems/shuffle-an-array/ + * Difficulty: Medium + * + * Given an integer array nums, design an algorithm to randomly shuffle the array. + * All permutations of the array should be equally likely as a result of the shuffling. + * + * Implement the Solution class: + * - Solution(int[] nums) Initializes the object with the integer array nums. + * - int[] reset() Resets the array to its original configuration and returns it. + * - int[] shuffle() Returns a random shuffling of the array. + */ + +/** + * @param {number[]} nums + */ +var Solution = function(nums) { + this.original = [...nums]; + this.result = [...nums]; +}; + +/** + * @return {number[]} + */ +Solution.prototype.reset = function() { + this.result = [...this.original]; + return this.result; +}; + +/** + * @return {number[]} + */ +Solution.prototype.shuffle = function() { + for (let i = this.result.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)); + [this.result[i], this.result[j]] = [this.result[j], this.result[i]]; + } + return this.result; +}; diff --git a/README.md b/README.md index cfe5646b..65a37ec5 100644 --- a/README.md +++ b/README.md @@ -281,6 +281,7 @@ 378|[Kth Smallest Element in a Sorted Matrix](./0378-kth-smallest-element-in-a-sorted-matrix.js)|Medium| 380|[Insert Delete GetRandom O(1)](./0380-insert-delete-getrandom-o1.js)|Medium| 383|[Ransom Note](./0383-ransom-note.js)|Easy| +384|[Shuffle an Array](./0384-shuffle-an-array.js)|Medium| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| 389|[Find the Difference](./0389-find-the-difference.js)|Easy| 392|[Is Subsequence](./0392-is-subsequence.js)|Easy| From cb6eaa91431c7fc5ddb355f0c8051e8a341ce53a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 21 Feb 2025 00:11:33 -0600 Subject: [PATCH 681/919] Add solution #454 --- 0454-4sum-ii.js | 27 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 28 insertions(+) create mode 100644 0454-4sum-ii.js diff --git a/0454-4sum-ii.js b/0454-4sum-ii.js new file mode 100644 index 00000000..0a8bb34a --- /dev/null +++ b/0454-4sum-ii.js @@ -0,0 +1,27 @@ +/** + * 454. 4Sum II + * https://leetcode.com/problems/4sum-ii/ + * Difficulty: Medium + * + * Given four integer arrays nums1, nums2, nums3, and nums4 all of length n, return the number + * of tuples (i, j, k, l) such that: + * - 0 <= i, j, k, l < n + * - nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0 + */ + +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @param {number[]} nums3 + * @param {number[]} nums4 + * @return {number} + */ +var fourSumCount = function(nums1, nums2, nums3, nums4) { + const map = new Map(); + nums1.forEach(n1 => { + nums2.forEach(n2 => map.set(n1 + n2, (map.get(n1 + n2) || 0) + 1)); + }); + return nums3.reduce((count, n3) => { + return count + nums4.reduce((sum, n4) => sum + (map.get(-(n3 + n4)) || 0), 0); + }, 0); +}; diff --git a/README.md b/README.md index 65a37ec5..80a727c9 100644 --- a/README.md +++ b/README.md @@ -307,6 +307,7 @@ 450|[Delete Node in a BST](./0450-delete-node-in-a-bst.js)|Medium| 451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| 452|[Minimum Number of Arrows to Burst Balloons](./0452-minimum-number-of-arrows-to-burst-balloons.js)|Medium| +454|[4Sum II](./0454-4sum-ii.js)|Medium| 456|[132 Pattern](./0456-132-pattern.js)|Medium| 459|[Repeated Substring Pattern](./0459-repeated-substring-pattern.js)|Easy| 461|[Hamming Distance](./0461-hamming-distance.js)|Easy| From 41b65202120fdc51d05cf2e8aea87709d55b7f4f Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 21 Feb 2025 00:13:09 -0600 Subject: [PATCH 682/919] Add solution #1261 --- ...-elements-in-a-contaminated-binary-tree.js | 57 +++++++++++++++++++ README.md | 1 + 2 files changed, 58 insertions(+) create mode 100644 1261-find-elements-in-a-contaminated-binary-tree.js diff --git a/1261-find-elements-in-a-contaminated-binary-tree.js b/1261-find-elements-in-a-contaminated-binary-tree.js new file mode 100644 index 00000000..7952f55e --- /dev/null +++ b/1261-find-elements-in-a-contaminated-binary-tree.js @@ -0,0 +1,57 @@ +/** + * 1261. Find Elements in a Contaminated Binary Tree + * https://leetcode.com/problems/find-elements-in-a-contaminated-binary-tree/ + * Difficulty: Medium + * + * Given a binary tree with the following rules: + * 1. root.val == 0 + * 2. For any treeNode: + * 1. If treeNode.val has a value x and treeNode.left != null, + * then treeNode.left.val == 2 * x + 1 + * 2. If treeNode.val has a value x and treeNode.right != null, + * then treeNode.right.val == 2 * x + 2 + * + * Now the binary tree is contaminated, which means all treeNode.val have + * been changed to -1. + * + * Implement the FindElements class: + * - FindElements(TreeNode* root) Initializes the object with a contaminated binary + * tree and recovers it. + * - bool find(int target) Returns true if the target value exists in the recovered + * 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) + * } + */ +/** + * @param {TreeNode} root + */ +var FindElements = function(root) { + this.values = new Set(); + root.val = 0; + + const traverse = node => { + if (!node) return; + this.values.add(node.val); + if (node.left) node.left.val = 2 * node.val + 1; + if (node.right) node.right.val = 2 * node.val + 2; + traverse(node.left); + traverse(node.right); + }; + + traverse(root); +}; + +/** + * @param {number} target + * @return {boolean} + */ +FindElements.prototype.find = function(target) { + return this.values.has(target); +}; diff --git a/README.md b/README.md index 80a727c9..c2fb9e42 100644 --- a/README.md +++ b/README.md @@ -456,6 +456,7 @@ 1233|[Remove Sub-Folders from the Filesystem](./1233-remove-sub-folders-from-the-filesystem.js)|Medium| 1249|[Minimum Remove to Make Valid Parentheses](./1249-minimum-remove-to-make-valid-parentheses.js)|Medium| 1252|[Cells with Odd Values in a Matrix](./1252-cells-with-odd-values-in-a-matrix.js)|Easy| +1261|[Find Elements in a Contaminated Binary Tree](./1261-find-elements-in-a-contaminated-binary-tree.js)|Medium| 1267|[Count Servers that Communicate](./1267-count-servers-that-communicate.js)|Medium| 1268|[Search Suggestions System](./1268-search-suggestions-system.js)|Medium| 1287|[Element Appearing More Than 25% In Sorted Array](./1287-element-appearing-more-than-25-in-sorted-array.js)|Easy| From 1e3774997c5ab518ca5621305ca820d9c61527fc Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 21 Feb 2025 20:56:00 -0600 Subject: [PATCH 683/919] Add solution #310 --- 0310-minimum-height-trees.js | 54 ++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 55 insertions(+) create mode 100644 0310-minimum-height-trees.js diff --git a/0310-minimum-height-trees.js b/0310-minimum-height-trees.js new file mode 100644 index 00000000..256e870d --- /dev/null +++ b/0310-minimum-height-trees.js @@ -0,0 +1,54 @@ +/** + * 310. Minimum Height Trees + * https://leetcode.com/problems/minimum-height-trees/ + * Difficulty: Medium + * + * A tree is an undirected graph in which any two vertices are connected by exactly one + * path. In other words, any connected graph without simple cycles is a tree. + * + * Given a tree of n nodes labelled from 0 to n - 1, and an array of n - 1 edges where + * edges[i] = [ai, bi] indicates that there is an undirected edge between the two nodes + * ai and bi in the tree, you can choose any node of the tree as the root. When you select + * a node x as the root, the result tree has height h. Among all possible rooted trees, + * those with minimum height (i.e. min(h)) are called minimum height trees (MHTs). + * + * Return a list of all MHTs' root labels. You can return the answer in any order. + * + * The height of a rooted tree is the number of edges on the longest downward path + * between the root and a leaf. + */ + +/** + * @param {number} n + * @param {number[][]} edges + * @return {number[]} + */ +var findMinHeightTrees = function(n, edges) { + if (n === 1) return [0]; + + const lookup = new Array(n).fill().map(() => new Set()); + for (const [a, b] of edges) { + lookup[a].add(b); + lookup[b].add(a); + } + + let result = []; + for (let i = 0; i < n; i++) { + if (lookup[i].size === 1) result.push(i); + } + + while (n > 2) { + n -= result.length; + const modified = []; + for (const item of result) { + const adj = lookup[item].values().next().value; + lookup[adj].delete(item); + if (lookup[adj].size === 1) { + modified.push(adj); + } + } + result = modified; + } + + return result; +}; diff --git a/README.md b/README.md index c2fb9e42..b0e5ad5b 100644 --- a/README.md +++ b/README.md @@ -252,6 +252,7 @@ 306|[Additive Number](./0306-additive-number.js)|Medium| 307|[Range Sum Query - Mutable](./0307-range-sum-query-mutable.js)|Medium| 309|[Best Time to Buy and Sell Stock with Cooldown](./0309-best-time-to-buy-and-sell-stock-with-cooldown.js)|Medium| +310|[Minimum Height Trees](./0310-minimum-height-trees.js)|Medium| 315|[Count of Smaller Numbers After Self](./0315-count-of-smaller-numbers-after-self.js)|Hard| 316|[Remove Duplicate Letters](./0316-remove-duplicate-letters.js)|Medium| 318|[Maximum Product of Word Lengths](./0318-maximum-product-of-word-lengths.js)|Medium| From 99ab8bbabf4e21bc07ba727c340a06c661692e55 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 21 Feb 2025 20:57:18 -0600 Subject: [PATCH 684/919] Add solution #312 --- 0312-burst-balloons.js | 37 +++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 38 insertions(+) create mode 100644 0312-burst-balloons.js diff --git a/0312-burst-balloons.js b/0312-burst-balloons.js new file mode 100644 index 00000000..27907cdf --- /dev/null +++ b/0312-burst-balloons.js @@ -0,0 +1,37 @@ +/** + * 312. Burst Balloons + * https://leetcode.com/problems/burst-balloons/ + * Difficulty: Hard + * + * You are given n balloons, indexed from 0 to n - 1. Each balloon is painted with a number + * on it represented by an array nums. You are asked to burst all the balloons. + * + * If you burst the ith balloon, you will get nums[i - 1] * nums[i] * nums[i + 1] coins. + * If i - 1 or i + 1 goes out of bounds of the array, then treat it as if there is a + * balloon with a 1 painted on it. + * + * Return the maximum coins you can collect by bursting the balloons wisely. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var maxCoins = function(nums) { + const track = [1, ...nums, 1]; + const dp = new Array(nums.length + 2).fill().map(() => new Array(nums.length + 2).fill(0)); + + for (let count = 1; count <= nums.length; count++) { + for (let i = 1; i <= nums.length - count + 1; i++) { + const j = i + count - 1; + for (let k = i; k <= j; k++) { + dp[i - 1][j + 1] = Math.max( + dp[i - 1][j + 1], + dp[i - 1][k] + dp[k][j + 1] + track[i - 1] * track[k] * track[j + 1] + ); + } + } + } + + return dp[0][nums.length + 1]; +}; diff --git a/README.md b/README.md index b0e5ad5b..d08767f4 100644 --- a/README.md +++ b/README.md @@ -253,6 +253,7 @@ 307|[Range Sum Query - Mutable](./0307-range-sum-query-mutable.js)|Medium| 309|[Best Time to Buy and Sell Stock with Cooldown](./0309-best-time-to-buy-and-sell-stock-with-cooldown.js)|Medium| 310|[Minimum Height Trees](./0310-minimum-height-trees.js)|Medium| +312|[Burst Balloons](./0312-burst-balloons.js)|Hard| 315|[Count of Smaller Numbers After Self](./0315-count-of-smaller-numbers-after-self.js)|Hard| 316|[Remove Duplicate Letters](./0316-remove-duplicate-letters.js)|Medium| 318|[Maximum Product of Word Lengths](./0318-maximum-product-of-word-lengths.js)|Medium| From f1a2af8632add71be771dad30934027eb46b1a8e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 21 Feb 2025 20:57:51 -0600 Subject: [PATCH 685/919] Add solution #313 --- 0313-super-ugly-number.js | 36 ++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 37 insertions(+) create mode 100644 0313-super-ugly-number.js diff --git a/0313-super-ugly-number.js b/0313-super-ugly-number.js new file mode 100644 index 00000000..62db64fd --- /dev/null +++ b/0313-super-ugly-number.js @@ -0,0 +1,36 @@ +/** + * 313. Super Ugly Number + * https://leetcode.com/problems/super-ugly-number/ + * Difficulty: Medium + * + * A super ugly number is a positive integer whose prime factors are in the array primes. + * + * Given an integer n and an array of integers primes, return the nth super ugly number. + * + * The nth super ugly number is guaranteed to fit in a 32-bit signed integer. + */ + +/** + * @param {number} n + * @param {number[]} primes + * @return {number} + */ +var nthSuperUglyNumber = function(n, primes) { + const result = [1]; + const pointers = new Array(primes.length).fill(0); + const next = [...primes]; + + while (result.length < n) { + const min = Math.min(...next); + result.push(min); + + for (let i = 0; i < primes.length; i++) { + if (next[i] === min) { + pointers[i]++; + next[i] = primes[i] * result[pointers[i]]; + } + } + } + + return result[n - 1]; +}; diff --git a/README.md b/README.md index d08767f4..8dba7d7d 100644 --- a/README.md +++ b/README.md @@ -254,6 +254,7 @@ 309|[Best Time to Buy and Sell Stock with Cooldown](./0309-best-time-to-buy-and-sell-stock-with-cooldown.js)|Medium| 310|[Minimum Height Trees](./0310-minimum-height-trees.js)|Medium| 312|[Burst Balloons](./0312-burst-balloons.js)|Hard| +313|[Super Ugly Number](./0313-super-ugly-number.js)|Medium| 315|[Count of Smaller Numbers After Self](./0315-count-of-smaller-numbers-after-self.js)|Hard| 316|[Remove Duplicate Letters](./0316-remove-duplicate-letters.js)|Medium| 318|[Maximum Product of Word Lengths](./0318-maximum-product-of-word-lengths.js)|Medium| From 5e4b1d796b6bfed1d06826b9a84eab4ec509272b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 21 Feb 2025 21:05:01 -0600 Subject: [PATCH 686/919] Add solution #321 --- 0321-create-maximum-number.js | 63 +++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 64 insertions(+) create mode 100644 0321-create-maximum-number.js diff --git a/0321-create-maximum-number.js b/0321-create-maximum-number.js new file mode 100644 index 00000000..264c1009 --- /dev/null +++ b/0321-create-maximum-number.js @@ -0,0 +1,63 @@ +/** + * 321. Create Maximum Number + * https://leetcode.com/problems/create-maximum-number/ + * Difficulty: Hard + * + * You are given two integer arrays nums1 and nums2 of lengths m and n respectively. + * nums1 and nums2 represent the digits of two numbers. You are also given an integer k. + * + * Create the maximum number of length k <= m + n from digits of the two numbers. The + * relative order of the digits from the same array must be preserved. + * + * Return an array of the k digits representing the answer. + */ + +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @param {number} k + * @return {number[]} + */ +var maxNumber = function(nums1, nums2, k) { + const m = nums1.length; + const n = nums2.length; + let result = new Array(k).fill(0); + + for (let i = Math.max(0, k - n); i <= Math.min(k, m); i++) { + if (i + n < k) continue; + const candidate = merge( + getMaxSubsequence(nums1, i), + getMaxSubsequence(nums2, k - i), + ); + result = candidate > result ? candidate : result; + } + + return result; + + function getMaxSubsequence(nums, count) { + const stack = []; + let removeIndex = nums.length - count; + + nums.forEach(n => { + while (stack.length && stack[stack.length - 1] < n && removeIndex) { + stack.pop(); + removeIndex--; + } + stack.push(n); + }); + + return stack.slice(0, count); + } + + function merge(a1, a2) { + const result = []; + + while (a1.length || a2.length) { + const compare = a1 > a2 ? a1 : a2; + result.push(compare[0]); + compare.shift(); + } + + return result; + } +}; diff --git a/README.md b/README.md index 8dba7d7d..b3779f86 100644 --- a/README.md +++ b/README.md @@ -259,6 +259,7 @@ 316|[Remove Duplicate Letters](./0316-remove-duplicate-letters.js)|Medium| 318|[Maximum Product of Word Lengths](./0318-maximum-product-of-word-lengths.js)|Medium| 319|[Bulb Switcher](./0319-bulb-switcher.js)|Medium| +321|[Create Maximum Number](./0321-create-maximum-number.js)|Hard| 322|[Coin Change](./0322-coin-change.js)|Medium| 324|[Wiggle Sort II](./0324-wiggle-sort-ii.js)|Medium| 326|[Power of Three](./0326-power-of-three.js)|Easy| From 3724415a2eeaade509ccb01d1f43ea8345acd59c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 21 Feb 2025 21:05:57 -0600 Subject: [PATCH 687/919] Add solution #1028 --- ...-recover-a-tree-from-preorder-traversal.js | 55 +++++++++++++++++++ README.md | 1 + 2 files changed, 56 insertions(+) create mode 100644 1028-recover-a-tree-from-preorder-traversal.js diff --git a/1028-recover-a-tree-from-preorder-traversal.js b/1028-recover-a-tree-from-preorder-traversal.js new file mode 100644 index 00000000..1d247ef8 --- /dev/null +++ b/1028-recover-a-tree-from-preorder-traversal.js @@ -0,0 +1,55 @@ +/** + * 1028. Recover a Tree From Preorder Traversal + * https://leetcode.com/problems/recover-a-tree-from-preorder-traversal/ + * Difficulty: Hard + * + * We run a preorder depth-first search (DFS) on the root of a binary tree. + * + * At each node in this traversal, we output D dashes (where D is the depth of this node), + * then we output the value of this node. If the depth of a node is D, the depth of its + * immediate child is D + 1. The depth of the root node is 0. + * + * If a node has only one child, that child is guaranteed to be the left child. + * + * Given the output traversal of this traversal, recover the tree and return its root. + */ + +/** + * 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 {string} traversal + * @return {TreeNode} + */ +var recoverFromPreorder = function(traversal) { + const stack = []; + + for (let i = 0; i < traversal.length;) { + let depth = 0; + while (traversal[i] === '-') { + depth++; + i++; + } + + let value = 0; + while (i < traversal.length && traversal[i] !== '-') { + value = value * 10 + parseInt(traversal[i]); + i++; + } + + const node = new TreeNode(value); + while (stack.length > depth) stack.pop(); + if (stack.length) { + if (!stack[stack.length - 1].left) stack[stack.length - 1].left = node; + else stack[stack.length - 1].right = node; + } + stack.push(node); + } + + return stack[0]; +}; diff --git a/README.md b/README.md index b3779f86..b16d3031 100644 --- a/README.md +++ b/README.md @@ -437,6 +437,7 @@ 1010|[Pairs of Songs With Total Durations Divisible by 60](./1010-pairs-of-songs-with-total-durations-divisible-by-60.js)|Medium| 1022|[Sum of Root To Leaf Binary Numbers](./1022-sum-of-root-to-leaf-binary-numbers.js)|Easy| 1023|[Camelcase Matching](./1023-camelcase-matching.js)|Medium| +1028|[Recover a Tree From Preorder Traversal](./1028-recover-a-tree-from-preorder-traversal.js)|Hard| 1037|[Valid Boomerang](./1037-valid-boomerang.js)|Easy| 1041|[Robot Bounded In Circle](./1041-robot-bounded-in-circle.js)|Medium| 1047|[Remove All Adjacent Duplicates In String](./1047-remove-all-adjacent-duplicates-in-string.js)|Easy| From e0969138096353a78ad56c8d03431143ef89a2a7 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 22 Feb 2025 00:00:04 -0600 Subject: [PATCH 688/919] Add solution #327 --- 0327-count-of-range-sum.js | 58 ++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 59 insertions(+) create mode 100644 0327-count-of-range-sum.js diff --git a/0327-count-of-range-sum.js b/0327-count-of-range-sum.js new file mode 100644 index 00000000..09e4e4cc --- /dev/null +++ b/0327-count-of-range-sum.js @@ -0,0 +1,58 @@ +/** + * 327. Count of Range Sum + * https://leetcode.com/problems/count-of-range-sum/ + * Difficulty: Hard + * + * Given an integer array nums and two integers lower and upper, return the number of range + * sums that lie in [lower, upper] inclusive. + * + * Range sum S(i, j) is defined as the sum of the elements in nums between indices i and j + * inclusive, where i <= j. + */ + +/** + * @param {number[]} nums + * @param {number} lower + * @param {number} upper + * @return {number} + */ +var countRangeSum = function(nums, lower, upper) { + const result = [0]; + for (let i = 0; i < nums.length; i++) { + result.push(result[i] + nums[i]); + } + + function mergeSort(input, left, right) { + if (left >= right) return 0; + const middle = Math.floor((left + right) / 2); + let count = mergeSort(input, left, middle) + mergeSort(input, middle + 1, right); + let i = left; + let j = middle + 1; + let k = middle + 1; + + while (i <= middle) { + while (j <= right && input[j] - input[i] < lower) j++; + while (k <= right && input[k] - input[i] <= upper) k++; + count += k - j; + i++; + } + + const sorted = []; + i = left; + j = middle + 1; + while (i <= middle || j <= right) { + if (i > middle) sorted.push(input[j++]); + else if (j > right) sorted.push(input[i++]); + else if (input[i] <= input[j]) sorted.push(input[i++]); + else sorted.push(input[j++]); + } + + for (let i = 0; i < sorted.length; i++) { + input[left + i] = sorted[i]; + } + + return count; + } + + return mergeSort(result, 0, result.length - 1); +}; diff --git a/README.md b/README.md index b16d3031..21ff7e95 100644 --- a/README.md +++ b/README.md @@ -263,6 +263,7 @@ 322|[Coin Change](./0322-coin-change.js)|Medium| 324|[Wiggle Sort II](./0324-wiggle-sort-ii.js)|Medium| 326|[Power of Three](./0326-power-of-three.js)|Easy| +327|[Count of Range Sum](./0327-count-of-range-sum.js)|Hard| 328|[Odd Even Linked List](./0328-odd-even-linked-list.js)|Medium| 329|[Longest Increasing Path in a Matrix](./0329-longest-increasing-path-in-a-matrix.js)|Hard| 331|[Verify Preorder Serialization of a Binary Tree](./0331-verify-preorder-serialization-of-a-binary-tree.js)|Medium| From f6fbf311a1cd2409dfb99fb0b8c0e18477b558c6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 22 Feb 2025 00:00:51 -0600 Subject: [PATCH 689/919] Add solution #330 --- 0330-patching-array.js | 31 +++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 0330-patching-array.js diff --git a/0330-patching-array.js b/0330-patching-array.js new file mode 100644 index 00000000..057aa534 --- /dev/null +++ b/0330-patching-array.js @@ -0,0 +1,31 @@ +/** + * 330. Patching Array + * https://leetcode.com/problems/patching-array/ + * Difficulty: Hard + * + * Given a sorted integer array nums and an integer n, add/patch elements to the array such + * that any number in the range [1, n] inclusive can be formed by the sum of some elements + * in the array. + * + * Return the minimum number of patches required. + */ + +/** + * @param {number[]} nums + * @param {number} n + * @return {number} + */ +var minPatches = function(nums, n) { + let result = 0; + + for (let i = 0, k = 1; k <= n;) { + if (i < nums.length && nums[i] <= k) { + k += nums[i++]; + } else { + k += k; + result++; + } + } + + return result; +}; diff --git a/README.md b/README.md index 21ff7e95..4e84890d 100644 --- a/README.md +++ b/README.md @@ -266,6 +266,7 @@ 327|[Count of Range Sum](./0327-count-of-range-sum.js)|Hard| 328|[Odd Even Linked List](./0328-odd-even-linked-list.js)|Medium| 329|[Longest Increasing Path in a Matrix](./0329-longest-increasing-path-in-a-matrix.js)|Hard| +330|[Patching Array](./0330-patching-array.js)|Hard| 331|[Verify Preorder Serialization of a Binary Tree](./0331-verify-preorder-serialization-of-a-binary-tree.js)|Medium| 334|[Increasing Triplet Subsequence](./0334-increasing-triplet-subsequence.js)|Medium| 337|[House Robber III](./0337-house-robber-iii.js)|Medium| From 0119d0c06c328ea721bde3a6205052ead8db7ecf Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 22 Feb 2025 00:01:45 -0600 Subject: [PATCH 690/919] Add solution #332 --- 0332-reconstruct-itinerary.js | 48 +++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 49 insertions(+) create mode 100644 0332-reconstruct-itinerary.js diff --git a/0332-reconstruct-itinerary.js b/0332-reconstruct-itinerary.js new file mode 100644 index 00000000..c9079cb9 --- /dev/null +++ b/0332-reconstruct-itinerary.js @@ -0,0 +1,48 @@ +/** + * 332. Reconstruct Itinerary + * https://leetcode.com/problems/reconstruct-itinerary/ + * Difficulty: Hard + * + * You are given a list of airline tickets where tickets[i] = [fromi, toi] represent the departure + * and the arrival airports of one flight. Reconstruct the itinerary in order and return it. + * + * All of the tickets belong to a man who departs from "JFK", thus, the itinerary must begin with + * "JFK". If there are multiple valid itineraries, you should return the itinerary that has the + * smallest lexical order when read as a single string. + * + * For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"]. + * + * You may assume all tickets form at least one valid itinerary. You must use all the tickets once + * and only once. + */ + +/** + * @param {string[][]} tickets + * @return {string[]} + */ +var findItinerary = function(tickets) { + const graph = new Map(); + const itinerary = []; + + for (const [from, to] of tickets) { + if (!graph.has(from)) { + graph.set(from, []); + } + graph.get(from).push(to); + } + + for (const [_, destinations] of graph) { + destinations.sort().reverse(); + } + + dfs('JFK'); + + return itinerary.reverse(); + + function dfs(airport) { + while (graph.has(airport) && graph.get(airport).length) { + dfs(graph.get(airport).pop()); + } + itinerary.push(airport); + } +}; diff --git a/README.md b/README.md index 4e84890d..b09388bd 100644 --- a/README.md +++ b/README.md @@ -268,6 +268,7 @@ 329|[Longest Increasing Path in a Matrix](./0329-longest-increasing-path-in-a-matrix.js)|Hard| 330|[Patching Array](./0330-patching-array.js)|Hard| 331|[Verify Preorder Serialization of a Binary Tree](./0331-verify-preorder-serialization-of-a-binary-tree.js)|Medium| +332|[Reconstruct Itinerary](./0332-reconstruct-itinerary.js)|Hard| 334|[Increasing Triplet Subsequence](./0334-increasing-triplet-subsequence.js)|Medium| 337|[House Robber III](./0337-house-robber-iii.js)|Medium| 338|[Counting Bits](./0338-counting-bits.js)|Easy| From 146b0fca8f550b9babdc317776c51582d4789b33 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 22 Feb 2025 00:02:19 -0600 Subject: [PATCH 691/919] Add solution #335 --- 0335-self-crossing.js | 33 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 0335-self-crossing.js diff --git a/0335-self-crossing.js b/0335-self-crossing.js new file mode 100644 index 00000000..f94cd59f --- /dev/null +++ b/0335-self-crossing.js @@ -0,0 +1,33 @@ +/** + * 335. Self Crossing + * https://leetcode.com/problems/self-crossing/ + * Difficulty: Hard + * + * You are given an array of integers distance. + * + * You start at the point (0, 0) on an X-Y plane, and you move distance[0] meters to the north, then + * distance[1] meters to the west, distance[2] meters to the south, distance[3] meters to the east, + * and so on. In other words, after each move, your direction changes counter-clockwise. + * + * Return true if your path crosses itself or false if it does not. + */ + +/** + * @param {number[]} d + * @return {boolean} + */ +var isSelfCrossing = function(d) { + for (let i = 3; i < d.length; i++) { + if (d[i] >= d[i - 2] && d[i - 1] <= d[i - 3]) { + return true; + } + if (i >= 4 && d[i - 1] === d[i - 3] && d[i] + d[i - 4] >= d[i - 2]) { + return true; + } + if (i >= 5 && d[i - 2] >= d[i - 4] && d[i] + d[i - 4] >= d[i - 2] + && d[i - 1] <= d[i - 3] && d[i - 1] + d[i - 5] >= d[i - 3]) { + return true; + } + } + return false; +}; diff --git a/README.md b/README.md index b09388bd..f69e3ef6 100644 --- a/README.md +++ b/README.md @@ -270,6 +270,7 @@ 331|[Verify Preorder Serialization of a Binary Tree](./0331-verify-preorder-serialization-of-a-binary-tree.js)|Medium| 332|[Reconstruct Itinerary](./0332-reconstruct-itinerary.js)|Hard| 334|[Increasing Triplet Subsequence](./0334-increasing-triplet-subsequence.js)|Medium| +335|[Self Crossing](./0335-self-crossing.js)|Hard| 337|[House Robber III](./0337-house-robber-iii.js)|Medium| 338|[Counting Bits](./0338-counting-bits.js)|Easy| 341|[Flatten Nested List Iterator](./0341-flatten-nested-list-iterator.js)|Medium| From 8455a7ef508fb4d16a6ef2f31d8834c166000841 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 22 Feb 2025 00:03:13 -0600 Subject: [PATCH 692/919] Add solution #336 --- 0336-palindrome-pairs.js | 57 ++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 58 insertions(+) create mode 100644 0336-palindrome-pairs.js diff --git a/0336-palindrome-pairs.js b/0336-palindrome-pairs.js new file mode 100644 index 00000000..a9018c20 --- /dev/null +++ b/0336-palindrome-pairs.js @@ -0,0 +1,57 @@ +/** + * 336. Palindrome Pairs + * https://leetcode.com/problems/palindrome-pairs/ + * Difficulty: Hard + * + * You are given a 0-indexed array of unique strings words. + * + * A palindrome pair is a pair of integers (i, j) such that: + * - 0 <= i, j < words.length, + * - i != j, and + * - words[i] + words[j] (the concatenation of the two strings) is a palindrome. + * + * Return an array of all the palindrome pairs of words. + * + * You must write an algorithm with O(sum of words[i].length) runtime complexity. + */ + +/** + * @param {string[]} words + * @return {number[][]} + */ +var palindromePairs = function(words) { + const result = []; + const map = new Map(); + const rMap = new Map(); + + words.forEach((word, i) => { + map.set(word, i); + rMap.set(word.split('').reverse().join(''), i); + }); + + words.forEach((word, i) => { + for (let j = 0; j <= word.length; j++) { + if (isPalindrome(word, 0, j - 1)) { + const right = word.slice(j); + if (rMap.has(right) && rMap.get(right) !== i) { + result.push([rMap.get(right), i]); + } + } + if (j < word.length && isPalindrome(word, j, word.length - 1)) { + const left = word.slice(0, j); + if (rMap.has(left) && rMap.get(left) !== i) { + result.push([i, rMap.get(left)]); + } + } + } + }); + + return result; + + function isPalindrome(s, start, end) { + while (start < end) { + if (s[start++] !== s[end--]) return false; + } + return true; + } +}; diff --git a/README.md b/README.md index f69e3ef6..1f4c2df7 100644 --- a/README.md +++ b/README.md @@ -271,6 +271,7 @@ 332|[Reconstruct Itinerary](./0332-reconstruct-itinerary.js)|Hard| 334|[Increasing Triplet Subsequence](./0334-increasing-triplet-subsequence.js)|Medium| 335|[Self Crossing](./0335-self-crossing.js)|Hard| +336|[Palindrome Pairs](./0336-palindrome-pairs.js)|Hard| 337|[House Robber III](./0337-house-robber-iii.js)|Medium| 338|[Counting Bits](./0338-counting-bits.js)|Easy| 341|[Flatten Nested List Iterator](./0341-flatten-nested-list-iterator.js)|Medium| From dce560b65aabf58604b8debd6efc7019e3bd857c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 22 Feb 2025 00:03:50 -0600 Subject: [PATCH 693/919] Add solution #343 --- 0343-integer-break.js | 24 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 0343-integer-break.js diff --git a/0343-integer-break.js b/0343-integer-break.js new file mode 100644 index 00000000..c78d534f --- /dev/null +++ b/0343-integer-break.js @@ -0,0 +1,24 @@ +/** + * 343. Integer Break + * https://leetcode.com/problems/integer-break/ + * Difficulty: Medium + * + * Given an integer n, break it into the sum of k positive integers, where k >= 2, + * and maximize the product of those integers. + * + * Return the maximum product you can get. + */ + +/** + * @param {number} n + * @return {number} + */ +var integerBreak = function(n) { + if (n <= 3) return n - 1; + let product = 1; + while (n > 4) { + product *= 3; + n -= 3; + } + return product * n; +}; diff --git a/README.md b/README.md index 1f4c2df7..dd9dc2df 100644 --- a/README.md +++ b/README.md @@ -276,6 +276,7 @@ 338|[Counting Bits](./0338-counting-bits.js)|Easy| 341|[Flatten Nested List Iterator](./0341-flatten-nested-list-iterator.js)|Medium| 342|[Power of Four](./0342-power-of-four.js)|Easy| +343|[Integer Break](./0343-integer-break.js)|Medium| 344|[Reverse String](./0344-reverse-string.js)|Easy| 345|[Reverse Vowels of a String](./0345-reverse-vowels-of-a-string.js)|Easy| 347|[Top K Frequent Elements](./0347-top-k-frequent-elements.js)|Medium| From 9c279990d0e7da9debdaec191f2d019f353bdd9e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 22 Feb 2025 00:04:36 -0600 Subject: [PATCH 694/919] Add solution #354 --- 0354-russian-doll-envelopes.js | 44 ++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 45 insertions(+) create mode 100644 0354-russian-doll-envelopes.js diff --git a/0354-russian-doll-envelopes.js b/0354-russian-doll-envelopes.js new file mode 100644 index 00000000..79811112 --- /dev/null +++ b/0354-russian-doll-envelopes.js @@ -0,0 +1,44 @@ +/** + * 354. Russian Doll Envelopes + * https://leetcode.com/problems/russian-doll-envelopes/ + * Difficulty: Hard + * + * You are given a 2D array of integers envelopes where envelopes[i] = [wi, hi] represents + * the width and the height of an envelope. + * + * One envelope can fit into another if and only if both the width and height of one envelope + * are greater than the other envelope's width and height. + * + * Return the maximum number of envelopes you can Russian doll (i.e., put one inside the other). + * + * Note: You cannot rotate an envelope. + */ + +/** + * @param {number[][]} envelopes + * @return {number} + */ +var maxEnvelopes = function(envelopes) { + const result = []; + + envelopes.sort((a, b) => a[0] === b[0] ? b[1] - a[1] : a[0] - b[0]); + envelopes.forEach(([_, h]) => { + let left = 0; + let right = result.length; + while (left < right) { + const middle = Math.floor((left + right) / 2); + if (result[middle] >= h) { + right = middle; + } else { + left = middle + 1; + } + } + if (left === result.length) { + result.push(h); + } else { + result[left] = h; + } + }); + + return result.length; +}; diff --git a/README.md b/README.md index dd9dc2df..26392008 100644 --- a/README.md +++ b/README.md @@ -283,6 +283,7 @@ 349|[Intersection of Two Arrays](./0349-intersection-of-two-arrays.js)|Easy| 350|[Intersection of Two Arrays II](./0350-intersection-of-two-arrays-ii.js)|Easy| 352|[Data Stream as Disjoint Intervals](./0352-data-stream-as-disjoint-intervals.js)|Hard| +354|[Russian Doll Envelopes](./0354-russian-doll-envelopes.js)|Hard| 355|[Design Twitter](./0355-design-twitter.js)|Medium| 367|[Valid Perfect Square](./0367-valid-perfect-square.js)|Easy| 371|[Sum of Two Integers](./0371-sum-of-two-integers.js)|Medium| From 0946bfa8fed0c610b028d45efcac814cdc820e00 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 22 Feb 2025 00:05:20 -0600 Subject: [PATCH 695/919] Add solution #357 --- 0357-count-numbers-with-unique-digits.js | 21 +++++++++++++++++++++ README.md | 1 + 2 files changed, 22 insertions(+) create mode 100644 0357-count-numbers-with-unique-digits.js diff --git a/0357-count-numbers-with-unique-digits.js b/0357-count-numbers-with-unique-digits.js new file mode 100644 index 00000000..27cbbae9 --- /dev/null +++ b/0357-count-numbers-with-unique-digits.js @@ -0,0 +1,21 @@ +/** + * 357. Count Numbers with Unique Digits + * https://leetcode.com/problems/count-numbers-with-unique-digits/ + * Difficulty: Medium + * + * Given an integer n, return the count of all numbers with unique digits, x, where 0 <= x < 10n. + */ + +/** + * @param {number} n + * @return {number} + */ +var countNumbersWithUniqueDigits = function(n) { + if (n === 0) return 1; + if (n > 10) return countNumbersWithUniqueDigits(10); + let result = 9; + for (let i = 0; i < n - 1; i++) { + result *= (9 - i); + } + return result + countNumbersWithUniqueDigits(n - 1); +}; diff --git a/README.md b/README.md index 26392008..c1705cb4 100644 --- a/README.md +++ b/README.md @@ -285,6 +285,7 @@ 352|[Data Stream as Disjoint Intervals](./0352-data-stream-as-disjoint-intervals.js)|Hard| 354|[Russian Doll Envelopes](./0354-russian-doll-envelopes.js)|Hard| 355|[Design Twitter](./0355-design-twitter.js)|Medium| +357|[Count Numbers with Unique Digits](./0357-count-numbers-with-unique-digits.js)|Medium| 367|[Valid Perfect Square](./0367-valid-perfect-square.js)|Easy| 371|[Sum of Two Integers](./0371-sum-of-two-integers.js)|Medium| 372|[Super Pow](./0372-super-pow.js)|Medium| From 78c2f11fa85fb0e03aefe3fda7f934ccb3d0b316 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 22 Feb 2025 00:06:07 -0600 Subject: [PATCH 696/919] Add solution #363 --- 0363-max-sum-of-rectangle-no-larger-than-k.js | 41 +++++++++++++++++++ README.md | 1 + 2 files changed, 42 insertions(+) create mode 100644 0363-max-sum-of-rectangle-no-larger-than-k.js diff --git a/0363-max-sum-of-rectangle-no-larger-than-k.js b/0363-max-sum-of-rectangle-no-larger-than-k.js new file mode 100644 index 00000000..ddf21162 --- /dev/null +++ b/0363-max-sum-of-rectangle-no-larger-than-k.js @@ -0,0 +1,41 @@ +/** + * 363. Max Sum of Rectangle No Larger Than K + * https://leetcode.com/problems/max-sum-of-rectangle-no-larger-than-k/ + * Difficulty: Hard + * + * Given an m x n matrix matrix and an integer k, return the max sum of a rectangle in the + * matrix such that its sum is no larger than k. + * + * It is guaranteed that there will be a rectangle with a sum no larger than k. + */ + +/** + * @param {number[][]} matrix + * @param {number} k + * @return {number} + */ +var maxSumSubmatrix = function(matrix, k) { + let max = -Infinity; + + for (let l = 0; l < matrix[0].length; l++) { + const counts = new Array(matrix.length).fill(0); + for (let r = l; r < matrix[0].length; r++) { + for (let i = 0; i < matrix.length; i++) counts[i] += matrix[i][r]; + const set = new Set([0]); + let sum = 0; + let value = -Infinity; + for (const num of counts) { + sum += num; + for (const previous of set) { + if (sum - previous <= k) { + value = Math.max(value, sum - previous); + } + } + set.add(sum); + } + max = Math.max(max, value); + } + } + + return max; +}; diff --git a/README.md b/README.md index c1705cb4..4b2b709c 100644 --- a/README.md +++ b/README.md @@ -286,6 +286,7 @@ 354|[Russian Doll Envelopes](./0354-russian-doll-envelopes.js)|Hard| 355|[Design Twitter](./0355-design-twitter.js)|Medium| 357|[Count Numbers with Unique Digits](./0357-count-numbers-with-unique-digits.js)|Medium| +363|[Max Sum of Rectangle No Larger Than K](./0363-max-sum-of-rectangle-no-larger-than-k.js)|Hard| 367|[Valid Perfect Square](./0367-valid-perfect-square.js)|Easy| 371|[Sum of Two Integers](./0371-sum-of-two-integers.js)|Medium| 372|[Super Pow](./0372-super-pow.js)|Medium| From 85a8a1e2ac0824ad75f869a4805bb37b88c658c3 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 22 Feb 2025 00:06:46 -0600 Subject: [PATCH 697/919] Add solution #365 --- 0365-water-and-jug-problem.js | 31 +++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 0365-water-and-jug-problem.js diff --git a/0365-water-and-jug-problem.js b/0365-water-and-jug-problem.js new file mode 100644 index 00000000..6a2ebb45 --- /dev/null +++ b/0365-water-and-jug-problem.js @@ -0,0 +1,31 @@ +/** + * 365. Water and Jug Problem + * https://leetcode.com/problems/water-and-jug-problem/ + * Difficulty: Medium + * + * You are given two jugs with capacities x liters and y liters. You have an infinite water + * supply. Return whether the total amount of water in both jugs may reach target using the + * following operations: + * - Fill either jug completely with water. + * - Completely empty either jug. + * - Pour water from one jug into another until the receiving jug is full, or the + * transferring jug is empty. + */ + +/** + * @param {number} x + * @param {number} y + * @param {number} target + * @return {boolean} + */ +var canMeasureWater = function(x, y, target) { + if (target > x + y) return false; + if (target === 0) return true; + if (x === 0) return target === y; + if (y === 0) return target === x; + return target % gcd(x, y) === 0; + + function gcd(a, b) { + return b === 0 ? a : gcd(b, a % b); + } +}; diff --git a/README.md b/README.md index 4b2b709c..4d5672f1 100644 --- a/README.md +++ b/README.md @@ -287,6 +287,7 @@ 355|[Design Twitter](./0355-design-twitter.js)|Medium| 357|[Count Numbers with Unique Digits](./0357-count-numbers-with-unique-digits.js)|Medium| 363|[Max Sum of Rectangle No Larger Than K](./0363-max-sum-of-rectangle-no-larger-than-k.js)|Hard| +365|[Water and Jug Problem](./0365-water-and-jug-problem.js)|Medium| 367|[Valid Perfect Square](./0367-valid-perfect-square.js)|Easy| 371|[Sum of Two Integers](./0371-sum-of-two-integers.js)|Medium| 372|[Super Pow](./0372-super-pow.js)|Medium| From 69e41dff2218a5bbd02a19e792e37e809a402a9c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 23 Feb 2025 00:18:00 -0600 Subject: [PATCH 698/919] Add solution #889 --- ...e-from-preorder-and-postorder-traversal.js | 43 +++++++++++++++++++ README.md | 1 + 2 files changed, 44 insertions(+) create mode 100644 0889-construct-binary-tree-from-preorder-and-postorder-traversal.js diff --git a/0889-construct-binary-tree-from-preorder-and-postorder-traversal.js b/0889-construct-binary-tree-from-preorder-and-postorder-traversal.js new file mode 100644 index 00000000..e946b779 --- /dev/null +++ b/0889-construct-binary-tree-from-preorder-and-postorder-traversal.js @@ -0,0 +1,43 @@ +/** + * 889. Construct Binary Tree from Preorder and Postorder Traversal + * https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/ + * Difficulty: Medium + * + * 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. + */ + +/** + * 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) { + if (!preorder.length) return null; + + const root = new TreeNode(preorder[0]); + if (preorder.length === 1) return root; + + const leftSize = postorder.indexOf(preorder[1]) + 1; + root.left = constructFromPrePost( + preorder.slice(1, leftSize + 1), + postorder.slice(0, leftSize) + ); + root.right = constructFromPrePost( + preorder.slice(leftSize + 1), + postorder.slice(leftSize, -1) + ); + + return root; +}; diff --git a/README.md b/README.md index 4d5672f1..694dee70 100644 --- a/README.md +++ b/README.md @@ -420,6 +420,7 @@ 875|[Koko Eating Bananas](./0875-koko-eating-bananas.js)|Medium| 876|[Middle of the Linked List](./0876-middle-of-the-linked-list.js)|Easy| 884|[Uncommon Words from Two Sentences](./0884-uncommon-words-from-two-sentences.js)|Easy| +889|[Construct Binary Tree from Preorder and Postorder Traversal](./0889-construct-binary-tree-from-preorder-and-postorder-traversal.js)|Medium| 890|[Find and Replace Pattern](./0890-find-and-replace-pattern.js)|Medium| 901|[Online Stock Span](./0901-online-stock-span.js)|Medium| 905|[Sort Array By Parity](./0905-sort-array-by-parity.js)|Easy| From 9b45c249903a38f491b8b8556a017001e592d04d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 23 Feb 2025 00:18:47 -0600 Subject: [PATCH 699/919] Add solution #368 --- 0368-largest-divisible-subset.js | 36 ++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 37 insertions(+) create mode 100644 0368-largest-divisible-subset.js diff --git a/0368-largest-divisible-subset.js b/0368-largest-divisible-subset.js new file mode 100644 index 00000000..a357a177 --- /dev/null +++ b/0368-largest-divisible-subset.js @@ -0,0 +1,36 @@ +/** + * 368. Largest Divisible Subset + * https://leetcode.com/problems/largest-divisible-subset/ + * Difficulty: Medium + * + * Given a set of distinct positive integers nums, return the largest subset answer such that + * every pair (answer[i], answer[j]) of elements in this subset satisfies: + * - answer[i] % answer[j] == 0, or + * - answer[j] % answer[i] == 0 + * + * If there are multiple solutions, return any of them. + */ + +/** + * @param {number[]} nums + * @return {number[]} + */ +var largestDivisibleSubset = function(nums) { + nums.sort((a, b) => a - b); + const dp = nums.map(() => [1, -1]); + let max = 0; + for (let i = 1; i < nums.length; i++) { + for (let j = 0; j < i; j++) { + if (nums[i] % nums[j] === 0 && dp[j][0] + 1 > dp[i][0]) { + dp[i] = [dp[j][0] + 1, j], dp[i][0] > dp[max][0] && (max = i); + } + } + } + + const result = []; + for (let i = max; i >= 0; i = dp[i][1]) { + result.unshift(nums[i]); + } + + return result; +}; diff --git a/README.md b/README.md index 694dee70..84f01e20 100644 --- a/README.md +++ b/README.md @@ -289,6 +289,7 @@ 363|[Max Sum of Rectangle No Larger Than K](./0363-max-sum-of-rectangle-no-larger-than-k.js)|Hard| 365|[Water and Jug Problem](./0365-water-and-jug-problem.js)|Medium| 367|[Valid Perfect Square](./0367-valid-perfect-square.js)|Easy| +368|[Largest Divisible Subset](./0368-largest-divisible-subset.js)|Medium| 371|[Sum of Two Integers](./0371-sum-of-two-integers.js)|Medium| 372|[Super Pow](./0372-super-pow.js)|Medium| 374|[Guess Number Higher or Lower](./0374-guess-number-higher-or-lower.js)|Medium| From 47a26cb589225ea20d23fe6418068bcecb50aac6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 23 Feb 2025 00:19:27 -0600 Subject: [PATCH 700/919] Add solution #373 --- 0373-find-k-pairs-with-smallest-sums.js | 38 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 39 insertions(+) create mode 100644 0373-find-k-pairs-with-smallest-sums.js diff --git a/0373-find-k-pairs-with-smallest-sums.js b/0373-find-k-pairs-with-smallest-sums.js new file mode 100644 index 00000000..59ab2d80 --- /dev/null +++ b/0373-find-k-pairs-with-smallest-sums.js @@ -0,0 +1,38 @@ +/** + * 373. Find K Pairs with Smallest Sums + * https://leetcode.com/problems/find-k-pairs-with-smallest-sums/ + * Difficulty: Medium + * + * You are given two integer arrays nums1 and nums2 sorted in non-decreasing order and an integer k. + * + * Define a pair (u, v) which consists of one element from the first array and one element from the + * second array. + * + * Return the k pairs (u1, v1), (u2, v2), ..., (uk, vk) with the smallest sums. + */ + +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @param {number} k + * @return {number[][]} + */ +var kSmallestPairs = function(nums1, nums2, k) { + const heap = new MinPriorityQueue({ compare: (a, b) => a[0] - b[0] }); + const result = []; + + for (let i = 0; i < nums1.length; i++) { + heap.enqueue([nums1[i] + nums2[0], 0]); + } + + while (k > 0 && !heap.isEmpty()) { + const [n, index] = heap.dequeue(); + result.push([n - nums2[index], nums2[index]]); + if (index + 1 < nums2.length) { + heap.enqueue([n - nums2[index] + nums2[index + 1], index + 1]); + } + k--; + } + + return result; +}; diff --git a/README.md b/README.md index 84f01e20..b5039862 100644 --- a/README.md +++ b/README.md @@ -292,6 +292,7 @@ 368|[Largest Divisible Subset](./0368-largest-divisible-subset.js)|Medium| 371|[Sum of Two Integers](./0371-sum-of-two-integers.js)|Medium| 372|[Super Pow](./0372-super-pow.js)|Medium| +373|[Find K Pairs with Smallest Sums](./0373-find-k-pairs-with-smallest-sums.js)|Medium| 374|[Guess Number Higher or Lower](./0374-guess-number-higher-or-lower.js)|Medium| 378|[Kth Smallest Element in a Sorted Matrix](./0378-kth-smallest-element-in-a-sorted-matrix.js)|Medium| 380|[Insert Delete GetRandom O(1)](./0380-insert-delete-getrandom-o1.js)|Medium| From 10bfb73dd7d1a59727f35de4122a0a7ee1be8886 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 23 Feb 2025 00:20:43 -0600 Subject: [PATCH 701/919] Add solution #375 --- 0375-guess-number-higher-or-lower-ii.js | 38 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 39 insertions(+) create mode 100644 0375-guess-number-higher-or-lower-ii.js diff --git a/0375-guess-number-higher-or-lower-ii.js b/0375-guess-number-higher-or-lower-ii.js new file mode 100644 index 00000000..87b4f042 --- /dev/null +++ b/0375-guess-number-higher-or-lower-ii.js @@ -0,0 +1,38 @@ +/** + * 375. Guess Number Higher or Lower II + * https://leetcode.com/problems/guess-number-higher-or-lower-ii/ + * Difficulty: Medium + * + * We are playing the Guessing Game. The game will work as follows: + * 1. I pick a number between 1 and n. + * 2. You guess a number. + * 3. If you guess the right number, you win the game. + * 4. If you guess the wrong number, then I will tell you whether the number I picked is higher + * or lower, and you will continue guessing. + * 5. Every time you guess a wrong number x, you will pay x dollars. If you run out of money, + * you lose the game. + * + * Given a particular n, return the minimum amount of money you need to guarantee a win + * regardless of what number I pick. + */ + +/** + * @param {number} n + * @return {number} + */ +var getMoneyAmount = function(n) { + const dp = new Array(n + 1).fill().map(() => new Array(n + 1).fill(0)); + + for (let i = 2; i <= n; i++) { + for (let j = 1; j <= n - i + 1; j++) { + const k = j + i - 1; + let min = Infinity; + for (let pivot = j; pivot < k; pivot++) { + min = Math.min(min, pivot + Math.max(dp[j][pivot - 1], dp[pivot + 1][k])); + } + dp[j][k] = min; + } + } + + return dp[1][n]; +}; diff --git a/README.md b/README.md index b5039862..d415a733 100644 --- a/README.md +++ b/README.md @@ -294,6 +294,7 @@ 372|[Super Pow](./0372-super-pow.js)|Medium| 373|[Find K Pairs with Smallest Sums](./0373-find-k-pairs-with-smallest-sums.js)|Medium| 374|[Guess Number Higher or Lower](./0374-guess-number-higher-or-lower.js)|Medium| +375|[Guess Number Higher or Lower II](./0375-guess-number-higher-or-lower-ii.js)|Medium| 378|[Kth Smallest Element in a Sorted Matrix](./0378-kth-smallest-element-in-a-sorted-matrix.js)|Medium| 380|[Insert Delete GetRandom O(1)](./0380-insert-delete-getrandom-o1.js)|Medium| 383|[Ransom Note](./0383-ransom-note.js)|Easy| From 121c48bf6326162ca11f6e2a6c90fb34b02d7745 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 23 Feb 2025 00:21:49 -0600 Subject: [PATCH 702/919] Add solution #376 --- 0376-wiggle-subsequence.js | 39 ++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 40 insertions(+) create mode 100644 0376-wiggle-subsequence.js diff --git a/0376-wiggle-subsequence.js b/0376-wiggle-subsequence.js new file mode 100644 index 00000000..d8752999 --- /dev/null +++ b/0376-wiggle-subsequence.js @@ -0,0 +1,39 @@ +/** + * 376. Wiggle Subsequence + * https://leetcode.com/problems/wiggle-subsequence/ + * Difficulty: Medium + * + * A wiggle sequence is a sequence where the differences between successive numbers strictly + * alternate between positive and negative. The first difference (if one exists) may be either + * positive or negative. A sequence with one element and a sequence with two non-equal elements + * are trivially wiggle sequences. + * - For example, [1, 7, 4, 9, 2, 5] is a wiggle sequence because the differences (6, -3, 5, -7, 3) + * alternate between positive and negative. + * - In contrast, [1, 4, 7, 2, 5] and [1, 7, 4, 5, 5] are not wiggle sequences. The first is not + * because its first two differences are positive, and the second is not because its last + * difference is zero. + * + * A subsequence is obtained by deleting some elements (possibly zero) from the original sequence, + * leaving the remaining elements in their original order. + * + * Given an integer array nums, return the length of the longest wiggle subsequence of nums. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var wiggleMaxLength = function(nums) { + let up = 1; + let down = 1; + + for (let i = 1; i < nums.length; i++) { + if (nums[i] > nums[i - 1]) { + up = down + 1; + } else if (nums[i] < nums[i - 1]) { + down = up + 1; + } + } + + return Math.max(up, down); +}; diff --git a/README.md b/README.md index d415a733..1eb3f979 100644 --- a/README.md +++ b/README.md @@ -295,6 +295,7 @@ 373|[Find K Pairs with Smallest Sums](./0373-find-k-pairs-with-smallest-sums.js)|Medium| 374|[Guess Number Higher or Lower](./0374-guess-number-higher-or-lower.js)|Medium| 375|[Guess Number Higher or Lower II](./0375-guess-number-higher-or-lower-ii.js)|Medium| +376|[Wiggle Subsequence](./0376-wiggle-subsequence.js)|Medium| 378|[Kth Smallest Element in a Sorted Matrix](./0378-kth-smallest-element-in-a-sorted-matrix.js)|Medium| 380|[Insert Delete GetRandom O(1)](./0380-insert-delete-getrandom-o1.js)|Medium| 383|[Ransom Note](./0383-ransom-note.js)|Easy| From e186a3264ed4aad6bd42c69b1f47687e9807c949 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 23 Feb 2025 17:34:33 -0600 Subject: [PATCH 703/919] Add solution #377 --- 0377-combination-sum-iv.js | 26 ++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 27 insertions(+) create mode 100644 0377-combination-sum-iv.js diff --git a/0377-combination-sum-iv.js b/0377-combination-sum-iv.js new file mode 100644 index 00000000..ee028c46 --- /dev/null +++ b/0377-combination-sum-iv.js @@ -0,0 +1,26 @@ +/** + * 377. Combination Sum IV + * https://leetcode.com/problems/combination-sum-iv/ + * Difficulty: Medium + * + * Given an array of distinct integers nums and a target integer target, return the number of + * possible combinations that add up to target. + * + * The test cases are generated so that the answer can fit in a 32-bit integer. + */ + +/** + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +var combinationSum4 = function(nums, target) { + const dp = new Array(target + 1).fill(0); + dp[0] = 1; + + for (let i = 1; i <= target; i++) { + nums.forEach(n => dp[i] += i >= n ? dp[i - n] : 0); + } + + return dp[target]; +}; diff --git a/README.md b/README.md index 1eb3f979..c97b9913 100644 --- a/README.md +++ b/README.md @@ -296,6 +296,7 @@ 374|[Guess Number Higher or Lower](./0374-guess-number-higher-or-lower.js)|Medium| 375|[Guess Number Higher or Lower II](./0375-guess-number-higher-or-lower-ii.js)|Medium| 376|[Wiggle Subsequence](./0376-wiggle-subsequence.js)|Medium| +377|[Combination Sum IV](./0377-combination-sum-iv.js)|Medium| 378|[Kth Smallest Element in a Sorted Matrix](./0378-kth-smallest-element-in-a-sorted-matrix.js)|Medium| 380|[Insert Delete GetRandom O(1)](./0380-insert-delete-getrandom-o1.js)|Medium| 383|[Ransom Note](./0383-ransom-note.js)|Easy| From 3394b6dcad39e9aebb530dd22545ba422d5e3ebc Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 23 Feb 2025 17:36:00 -0600 Subject: [PATCH 704/919] Add solution #381 --- ...-delete-getrandom-o1-duplicates-allowed.js | 74 +++++++++++++++++++ README.md | 1 + 2 files changed, 75 insertions(+) create mode 100644 0381-insert-delete-getrandom-o1-duplicates-allowed.js diff --git a/0381-insert-delete-getrandom-o1-duplicates-allowed.js b/0381-insert-delete-getrandom-o1-duplicates-allowed.js new file mode 100644 index 00000000..0591651f --- /dev/null +++ b/0381-insert-delete-getrandom-o1-duplicates-allowed.js @@ -0,0 +1,74 @@ +/** + * 381. Insert Delete GetRandom O(1) - Duplicates allowed + * https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/ + * Difficulty: Hard + * + * RandomizedCollection is a data structure that contains a collection of numbers, possibly + * duplicates (i.e., a multiset). It should support inserting and removing specific elements + * and also reporting a random element. + * + * Implement the RandomizedCollection class: + * - RandomizedCollection() Initializes the empty RandomizedCollection object. + * - bool insert(int val) Inserts an item val into the multiset, even if the item is already + * present. Returns true if the item is not present, false otherwise. + * - bool remove(int val) Removes an item val from the multiset if present. Returns true if + * the item is present, false otherwise. Note that if val has multiple occurrences in the + * multiset, we only remove one of them. + * - int getRandom() Returns a random element from the current multiset of elements. The + * probability of each element being returned is linearly related to the number of the same + * values the multiset contains. + * + * You must implement the functions of the class such that each function works on average O(1) + * time complexity. + * + * Note: The test cases are generated such that getRandom will only be called if there is at + * least one item in the RandomizedCollection. + */ + +var RandomizedCollection = function() { + this.values = []; + this.map = new Map(); +}; + +/** + * @param {number} val + * @return {boolean} + */ +RandomizedCollection.prototype.insert = function(val) { + this.values.push(val); + const values = this.map.get(val) || new Set(); + values.add(this.values.length - 1); + this.map.set(val, values); + return values.size === 1; +}; + +/** + * @param {number} val + * @return {boolean} + */ +RandomizedCollection.prototype.remove = function(val) { + if (!this.map.has(val)) return false; + const values = this.map.get(val); + const index = values.values().next().value; + values.delete(index); + if (index < this.values.length - 1) { + const last = this.values.pop(); + this.values[index] = last; + const lastValues = this.map.get(last); + lastValues.delete(this.values.length); + lastValues.add(index); + } else { + this.values.pop(); + } + if (!values.size) { + this.map.delete(val); + } + return true; +}; + +/** + * @return {number} + */ +RandomizedCollection.prototype.getRandom = function() { + return this.values[Math.floor(Math.random() * this.values.length)]; +}; diff --git a/README.md b/README.md index c97b9913..ea639efb 100644 --- a/README.md +++ b/README.md @@ -299,6 +299,7 @@ 377|[Combination Sum IV](./0377-combination-sum-iv.js)|Medium| 378|[Kth Smallest Element in a Sorted Matrix](./0378-kth-smallest-element-in-a-sorted-matrix.js)|Medium| 380|[Insert Delete GetRandom O(1)](./0380-insert-delete-getrandom-o1.js)|Medium| +381|[Insert Delete GetRandom O(1) - Duplicates allowed](./0381-insert-delete-getrandom-o1-duplicates-allowed.js)|Hard| 383|[Ransom Note](./0383-ransom-note.js)|Easy| 384|[Shuffle an Array](./0384-shuffle-an-array.js)|Medium| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| From 288fe121d8c678821452b6cc2a3095f89b26872a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 23 Feb 2025 17:36:57 -0600 Subject: [PATCH 705/919] Add solution #382 --- 0382-linked-list-random-node.js | 46 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 47 insertions(+) create mode 100644 0382-linked-list-random-node.js diff --git a/0382-linked-list-random-node.js b/0382-linked-list-random-node.js new file mode 100644 index 00000000..9520b572 --- /dev/null +++ b/0382-linked-list-random-node.js @@ -0,0 +1,46 @@ +/** + * 382. Linked List Random Node + * https://leetcode.com/problems/linked-list-random-node/ + * Difficulty: Medium + * + * Given a singly linked list, return a random node's value from the linked list. Each node must + * have the same probability of being chosen. + * + * Implement the Solution class: + * - Solution(ListNode head) Initializes the object with the head of the singly-linked list head. + * - int getRandom() Chooses a node randomly from the list and returns its value. All the nodes + * of the list should be equally likely to be chosen. + */ + +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + */ +var Solution = function(head) { + this.head = head; +}; + +/** + * @return {number} + */ +Solution.prototype.getRandom = function() { + let current = this.head; + let result = current.val; + let count = 1; + + while (current.next) { + current = current.next; + count++; + if (Math.random() < 1 / count) { + result = current.val; + } + } + + return result; +}; diff --git a/README.md b/README.md index ea639efb..eddff92e 100644 --- a/README.md +++ b/README.md @@ -300,6 +300,7 @@ 378|[Kth Smallest Element in a Sorted Matrix](./0378-kth-smallest-element-in-a-sorted-matrix.js)|Medium| 380|[Insert Delete GetRandom O(1)](./0380-insert-delete-getrandom-o1.js)|Medium| 381|[Insert Delete GetRandom O(1) - Duplicates allowed](./0381-insert-delete-getrandom-o1-duplicates-allowed.js)|Hard| +382|[Linked List Random Node](./0382-linked-list-random-node.js)|Medium| 383|[Ransom Note](./0383-ransom-note.js)|Easy| 384|[Shuffle an Array](./0384-shuffle-an-array.js)|Medium| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| From 925d3bd709c26f897cd96e4e3ccea0f97e12a2b3 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 23 Feb 2025 17:37:33 -0600 Subject: [PATCH 706/919] Add solution #385 --- 0385-mini-parser.js | 29 +++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 30 insertions(+) create mode 100644 0385-mini-parser.js diff --git a/0385-mini-parser.js b/0385-mini-parser.js new file mode 100644 index 00000000..26d0836d --- /dev/null +++ b/0385-mini-parser.js @@ -0,0 +1,29 @@ +/** + * 385. Mini Parser + * https://leetcode.com/problems/mini-parser/ + * Difficulty: Medium + * + * Given a string s represents the serialization of a nested list, implement a parser to deserialize + * it and return the deserialized NestedInteger. + * + * Each element is either an integer or a list whose elements may also be integers or other lists. + */ + +/** + * @param {string} s + * @return {NestedInteger} + */ +var deserialize = function(s) { + return traverse(JSON.parse(s)); + + function traverse(str) { + if (Number.isInteger(str)) { + return new NestedInteger(str); + } + const value = new NestedInteger(); + for (const s of str) { + value.add(traverse(s)); + } + return value; + }; +}; diff --git a/README.md b/README.md index eddff92e..9ef57a79 100644 --- a/README.md +++ b/README.md @@ -303,6 +303,7 @@ 382|[Linked List Random Node](./0382-linked-list-random-node.js)|Medium| 383|[Ransom Note](./0383-ransom-note.js)|Easy| 384|[Shuffle an Array](./0384-shuffle-an-array.js)|Medium| +385|[Mini Parser](./0385-mini-parser.js)|Medium| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| 389|[Find the Difference](./0389-find-the-difference.js)|Easy| 392|[Is Subsequence](./0392-is-subsequence.js)|Easy| From ad287b1320e69bcb891fa4e45a957597b8572a8b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 23 Feb 2025 17:38:32 -0600 Subject: [PATCH 707/919] Add solution #386 --- 0386-lexicographical-numbers.js | 32 ++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 0386-lexicographical-numbers.js diff --git a/0386-lexicographical-numbers.js b/0386-lexicographical-numbers.js new file mode 100644 index 00000000..4d0c8685 --- /dev/null +++ b/0386-lexicographical-numbers.js @@ -0,0 +1,32 @@ +/** + * 386. Lexicographical Numbers + * https://leetcode.com/problems/lexicographical-numbers/ + * Difficulty: Medium + * + * Given an integer n, return all the numbers in the range [1, n] sorted in lexicographical order. + * + * You must write an algorithm that runs in O(n) time. + */ + +/** + * @param {number} n + * @return {number[]} + */ +var lexicalOrder = function(n) { + const result = []; + let value = 1; + + for (let i = 0; i < n; i++) { + result.push(value); + if (value * 10 <= n) { + value *= 10; + } else { + while (value % 10 === 9 || value >= n) { + value = Math.floor(value / 10); + } + value++; + } + } + + return result; +}; diff --git a/README.md b/README.md index 9ef57a79..4b227146 100644 --- a/README.md +++ b/README.md @@ -304,6 +304,7 @@ 383|[Ransom Note](./0383-ransom-note.js)|Easy| 384|[Shuffle an Array](./0384-shuffle-an-array.js)|Medium| 385|[Mini Parser](./0385-mini-parser.js)|Medium| +386|[Lexicographical Numbers](./0386-lexicographical-numbers.js)|Medium| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| 389|[Find the Difference](./0389-find-the-difference.js)|Easy| 392|[Is Subsequence](./0392-is-subsequence.js)|Easy| From 1f0170f636a8138c3467b3ee2d0c3cdafe0bad8e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 24 Feb 2025 00:04:00 -0600 Subject: [PATCH 708/919] Add solution #2467 --- 2467-most-profitable-path-in-a-tree.js | 79 ++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 80 insertions(+) create mode 100644 2467-most-profitable-path-in-a-tree.js diff --git a/2467-most-profitable-path-in-a-tree.js b/2467-most-profitable-path-in-a-tree.js new file mode 100644 index 00000000..6e89a2d7 --- /dev/null +++ b/2467-most-profitable-path-in-a-tree.js @@ -0,0 +1,79 @@ +/** + * 2467. Most Profitable Path in a Tree + * https://leetcode.com/problems/most-profitable-path-in-a-tree/ + * Difficulty: Medium + * + * There is an undirected tree with n nodes labeled from 0 to n - 1, rooted at node 0. You are + * given a 2D integer array edges of length n - 1 where edges[i] = [ai, bi] indicates that + * there is an edge between nodes ai and bi in the tree. + * + * At every node i, there is a gate. You are also given an array of even integers amount, where + * amount[i] represents: + * - the price needed to open the gate at node i, if amount[i] is negative, or, + * - the cash reward obtained on opening the gate at node i, otherwise. + * + * The game goes on as follows: + * - Initially, Alice is at node 0 and Bob is at node bob. + * - At every second, Alice and Bob each move to an adjacent node. Alice moves towards some leaf + * node, while Bob moves towards node 0. + * - For every node along their path, Alice and Bob either spend money to open the gate at that + * node, or accept the reward. Note that: + * - If the gate is already open, no price will be required, nor will there be any cash reward. + * - If Alice and Bob reach the node simultaneously, they share the price/reward for opening + * the gate there. In other words, if the price to open the gate is c, then both Alice and + * Bob pay c / 2 each. Similarly, if the reward at the gate is c, both of them receive + * c / 2 each. + * - If Alice reaches a leaf node, she stops moving. Similarly, if Bob reaches node 0, he stops + * moving. Note that these events are independent of each other. + * + * Return the maximum net income Alice can have if she travels towards the optimal leaf node. + */ + +/** + * @param {number[][]} edges + * @param {number} bob + * @param {number[]} amount + * @return {number} + */ +var mostProfitablePath = function(edges, bob, amount) { + const graph = new Array(edges.length + 1).fill().map(() => []); + const path = new Array(edges.length + 1).fill(-1); + + for (const [u, v] of edges) { + graph[u].push(v); + graph[v].push(u); + } + + function traceInitialPath(node, time) { + path[node] = time; + if (node === 0) { + return true; + } + for (const next of graph[node]) { + if (path[next] === -1 && traceInitialPath(next, time + 1)) { + return true; + } + } + path[node] = -1; + return false; + } + + traceInitialPath(bob, 0); + + function dfs(node, parent, time, income) { + const current = (time < path[node] || path[node] === -1) + ? amount[node] + : time === path[node] ? amount[node] / 2 : 0; + let maxIncome = graph[node].length === 1 && node !== 0 ? income + current : -Infinity; + + for (const next of graph[node]) { + if (next !== parent) { + maxIncome = Math.max(maxIncome, dfs(next, node, time + 1, income + current)); + } + } + + return maxIncome === -Infinity ? income + current : maxIncome; + } + + return dfs(0, -1, 0, 0); +}; diff --git a/README.md b/README.md index 4b227146..8e29e36a 100644 --- a/README.md +++ b/README.md @@ -624,6 +624,7 @@ 2427|[Number of Common Factors](./2427-number-of-common-factors.js)|Easy| 2429|[Minimize XOR](./2429-minimize-xor.js)|Medium| 2462|[Total Cost to Hire K Workers](./2462-total-cost-to-hire-k-workers.js)|Medium| +2467|[Most Profitable Path in a Tree](./2467-most-profitable-path-in-a-tree.js)|Medium| 2469|[Convert the Temperature](./2469-convert-the-temperature.js)|Easy| 2482|[Difference Between Ones and Zeros in Row and Column](./2482-difference-between-ones-and-zeros-in-row-and-column.js)|Medium| 2490|[Circular Sentence](./2490-circular-sentence.js)|Easy| From a8834be27db70af8fe6985068f8c948a2f0b45d6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 24 Feb 2025 00:08:29 -0600 Subject: [PATCH 709/919] Add solution #388 --- 0388-longest-absolute-file-path.js | 58 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 59 insertions(+) create mode 100644 0388-longest-absolute-file-path.js diff --git a/0388-longest-absolute-file-path.js b/0388-longest-absolute-file-path.js new file mode 100644 index 00000000..6dcc95b9 --- /dev/null +++ b/0388-longest-absolute-file-path.js @@ -0,0 +1,58 @@ +/** + * 388. Longest Absolute File Path + * https://leetcode.com/problems/longest-absolute-file-path/ + * Difficulty: Medium + * + * Suppose we have a file system that stores both files and directories. An example of one system + * is represented in the following picture: + * + * Here, we have dir as the only directory in the root. dir contains two subdirectories, subdir1 + * and subdir2. subdir1 contains a file file1.ext and subdirectory subsubdir1. subdir2 contains + * a subdirectory subsubdir2, which contains a file file2.ext. + * In text form, it looks like this (with ⟶ representing the tab character): + * + * dir + * ⟶ subdir1 + * ⟶ ⟶ file1.ext + * ⟶ ⟶ subsubdir1 + * ⟶ subdir2 + * ⟶ ⟶ subsubdir2 + * ⟶ ⟶ ⟶ file2.ext + * + * If we were to write this representation in code, it will look like this: + * "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext". + * Note that the '\n' and '\t' are the new-line and tab characters. + * + * Every file and directory has a unique absolute path in the file system, which is the order of + * directories that must be opened to reach the file/directory itself, all concatenated by '/'s. + * Using the above example, the absolute path to file2.ext is "dir/subdir2/subsubdir2/file2.ext". + * Each directory name consists of letters, digits, and/or spaces. Each file name is of the form + * name.extension, where name and extension consist of letters, digits, and/or spaces. + * + * Given a string input representing the file system in the explained format, return the length of + * the longest absolute path to a file in the abstracted file system. If there is no file in the + * system, return 0. + * + * Note that the testcases are generated such that the file system is valid and no file or directory + * name has length 0. + */ + +/** + * @param {string} input + * @return {number} + */ +var lengthLongestPath = function(input) { + const stack = [0]; + let result = 0; + + for (const line of input.split('\n')) { + const level = line.lastIndexOf('\t') + 1; + while (stack.length > level + 1) stack.pop(); + stack.push(stack.at(-1) + line.length - level + 1); + if (line.includes('.')) { + result = Math.max(result, stack.at(-1) - 1); + } + } + + return result; +}; diff --git a/README.md b/README.md index 8e29e36a..6bb27c61 100644 --- a/README.md +++ b/README.md @@ -306,6 +306,7 @@ 385|[Mini Parser](./0385-mini-parser.js)|Medium| 386|[Lexicographical Numbers](./0386-lexicographical-numbers.js)|Medium| 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| +388|[Longest Absolute File Path](./0388-longest-absolute-file-path.js)|Medium| 389|[Find the Difference](./0389-find-the-difference.js)|Easy| 392|[Is Subsequence](./0392-is-subsequence.js)|Easy| 394|[Decode String](./0394-decode-string.js)|Medium| From b344ac5a8e8951907ef06562efb0adc796a19cc2 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 24 Feb 2025 00:09:18 -0600 Subject: [PATCH 710/919] Add solution #390 --- 0390-elimination-game.js | 35 +++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 36 insertions(+) create mode 100644 0390-elimination-game.js diff --git a/0390-elimination-game.js b/0390-elimination-game.js new file mode 100644 index 00000000..a2bba04b --- /dev/null +++ b/0390-elimination-game.js @@ -0,0 +1,35 @@ +/** + * 390. Elimination Game + * https://leetcode.com/problems/elimination-game/ + * Difficulty: Medium + * + * You have a list arr of all integers in the range [1, n] sorted in a strictly increasing order. + * Apply the following algorithm on arr: + * - Starting from left to right, remove the first number and every other number afterward until + * you reach the end of the list. + * - Repeat the previous step again, but this time from right to left, remove the rightmost number + * and every other number from the remaining numbers. + * - Keep repeating the steps again, alternating left to right and right to left, until a single + * number remains. + * + * Given the integer n, return the last number that remains in arr. + */ + +/** + * @param {number} n + * @return {number} + */ +var lastRemaining = function(n) { + let result = 1; + + for (let isRemaining = true, count = n, step = 1; count > 1;) { + if (isRemaining || count % 2 === 1) { + result += step; + } + count = Math.floor(count / 2); + isRemaining = !isRemaining; + step *= 2; + } + + return result; +}; diff --git a/README.md b/README.md index 6bb27c61..1ae5af43 100644 --- a/README.md +++ b/README.md @@ -308,6 +308,7 @@ 387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy| 388|[Longest Absolute File Path](./0388-longest-absolute-file-path.js)|Medium| 389|[Find the Difference](./0389-find-the-difference.js)|Easy| +390|[Elimination Game](./0390-elimination-game.js)|Medium| 392|[Is Subsequence](./0392-is-subsequence.js)|Easy| 394|[Decode String](./0394-decode-string.js)|Medium| 395|[Longest Substring with At Least K Repeating Characters](./0395-longest-substring-with-at-least-k-repeating-characters.js)|Medium| From 8422aa1ab0821794e2e5c486d5702a17ba7f1b37 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 24 Feb 2025 00:09:50 -0600 Subject: [PATCH 711/919] Add solution #391 --- 0391-perfect-rectangle.js | 39 +++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 40 insertions(+) create mode 100644 0391-perfect-rectangle.js diff --git a/0391-perfect-rectangle.js b/0391-perfect-rectangle.js new file mode 100644 index 00000000..5a2f82ed --- /dev/null +++ b/0391-perfect-rectangle.js @@ -0,0 +1,39 @@ +/** + * 391. Perfect Rectangle + * https://leetcode.com/problems/perfect-rectangle/ + * Difficulty: Hard + * + * Given an array rectangles where rectangles[i] = [xi, yi, ai, bi] represents an axis-aligned + * rectangle. The bottom-left point of the rectangle is (xi, yi) and the top-right point of it + * is (ai, bi). + * + * Return true if all the rectangles together form an exact cover of a rectangular region. + */ + +/** + * @param {number[][]} rectangles + * @return {boolean} + */ +var isRectangleCover = function(rectangles) { + const result = new Set(); + let area = 0; + let minX = Infinity; + let maxX = -Infinity; + let minY = Infinity; + let maxY = -Infinity; + + for (const [x1, y1, x2, y2] of rectangles) { + area += (x2 - x1) * (y2 - y1); + minX = Math.min(minX, x1); + minY = Math.min(minY, y1); + maxX = Math.max(maxX, x2); + maxY = Math.max(maxY, y2); + for (const corner of [`${x1},${y1}`, `${x2},${y1}`, `${x1},${y2}`, `${x2},${y2}`]) { + result.has(corner) ? result.delete(corner) : result.add(corner); + } + } + + return area === (maxX - minX) * (maxY - minY) && result.size === 4 + && result.has(`${minX},${minY}`) && result.has(`${maxX},${minY}`) + && result.has(`${minX},${maxY}`) && result.has(`${maxX},${maxY}`); +}; diff --git a/README.md b/README.md index 1ae5af43..9d1c59c9 100644 --- a/README.md +++ b/README.md @@ -309,6 +309,7 @@ 388|[Longest Absolute File Path](./0388-longest-absolute-file-path.js)|Medium| 389|[Find the Difference](./0389-find-the-difference.js)|Easy| 390|[Elimination Game](./0390-elimination-game.js)|Medium| +391|[Perfect Rectangle](./0391-perfect-rectangle.js)|Hard| 392|[Is Subsequence](./0392-is-subsequence.js)|Easy| 394|[Decode String](./0394-decode-string.js)|Medium| 395|[Longest Substring with At Least K Repeating Characters](./0395-longest-substring-with-at-least-k-repeating-characters.js)|Medium| From 65dc955591e3caac5c6ce0961dd8abe1905074a5 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 24 Feb 2025 00:12:13 -0600 Subject: [PATCH 712/919] Add solution #393 --- 0393-utf-8-validation.js | 50 ++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 51 insertions(+) create mode 100644 0393-utf-8-validation.js diff --git a/0393-utf-8-validation.js b/0393-utf-8-validation.js new file mode 100644 index 00000000..5b9c23b7 --- /dev/null +++ b/0393-utf-8-validation.js @@ -0,0 +1,50 @@ +/** + * 393. UTF-8 Validation + * https://leetcode.com/problems/utf-8-validation/ + * Difficulty: Medium + * + * Given an integer array data representing the data, return whether it is a valid UTF-8 encoding + * (i.e. it translates to a sequence of valid UTF-8 encoded characters). + * + * A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules: + * 1. For a 1-byte character, the first bit is a 0, followed by its Unicode code. + * 2. For an n-bytes character, the first n bits are all one's, the n + 1 bit is 0, followed by + * n - 1 bytes with the most significant 2 bits being 10. + * + * This is how the UTF-8 encoding would work: + * Number of Bytes | UTF-8 Octet Sequence + * | (binary) + * --------------------+----------------------------------------- + * 1 | 0xxxxxxx + * 2 | 110xxxxx 10xxxxxx + * 3 | 1110xxxx 10xxxxxx 10xxxxxx + * 4 | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + * + * x denotes a bit in the binary form of a byte that may be either 0 or 1. + * + * Note: The input is an array of integers. Only the least significant 8 bits of each integer is + * used to store the data. This means each integer represents only 1 byte of data. + */ + +/** + * @param {number[]} data + * @return {boolean} + */ +var validUtf8 = function(data) { + let result = 0; + + for (const n of data) { + if (result === 0) { + if (n >> 7 === 0) result = 0; + else if (n >> 5 === 0b110) result = 1; + else if (n >> 4 === 0b1110) result = 2; + else if (n >> 3 === 0b11110) result = 3; + else return false; + } else { + if (n >> 6 !== 0b10) return false; + result--; + } + } + + return result === 0; +}; diff --git a/README.md b/README.md index 9d1c59c9..b8bc5d03 100644 --- a/README.md +++ b/README.md @@ -311,6 +311,7 @@ 390|[Elimination Game](./0390-elimination-game.js)|Medium| 391|[Perfect Rectangle](./0391-perfect-rectangle.js)|Hard| 392|[Is Subsequence](./0392-is-subsequence.js)|Easy| +393|[UTF-8 Validation](./0393-utf-8-validation.js)|Medium| 394|[Decode String](./0394-decode-string.js)|Medium| 395|[Longest Substring with At Least K Repeating Characters](./0395-longest-substring-with-at-least-k-repeating-characters.js)|Medium| 399|[Evaluate Division](./0399-evaluate-division.js)|Medium| From 498c79a7829285a1abc27fd16997e41bcd4438d6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 24 Feb 2025 00:12:47 -0600 Subject: [PATCH 713/919] Add solution #396 --- 0396-rotate-function.js | 32 ++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 0396-rotate-function.js diff --git a/0396-rotate-function.js b/0396-rotate-function.js new file mode 100644 index 00000000..f1ace6c3 --- /dev/null +++ b/0396-rotate-function.js @@ -0,0 +1,32 @@ +/** + * 396. Rotate Function + * https://leetcode.com/problems/rotate-function/ + * Difficulty: Medium + * + * You are given an integer array nums of length n. + * + * Assume arrk to be an array obtained by rotating nums by k positions clock-wise. + * We define the rotation function F on nums as follow: + * - F(k) = 0 * arrk[0] + 1 * arrk[1] + ... + (n - 1) * arrk[n - 1]. + * + * Return the maximum value of F(0), F(1), ..., F(n-1). + * + * The test cases are generated so that the answer fits in a 32-bit integer. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var maxRotateFunction = function(nums) { + const sum = nums.reduce((a, b) => a + b, 0); + let current = nums.reduce((total, n, i) => total + i * n, 0); + let result = current; + + for (let i = 1; i < nums.length; i++) { + current = current + sum - nums.length * nums[nums.length - i]; + result = Math.max(result, current); + } + + return result; +}; diff --git a/README.md b/README.md index b8bc5d03..dd839c02 100644 --- a/README.md +++ b/README.md @@ -314,6 +314,7 @@ 393|[UTF-8 Validation](./0393-utf-8-validation.js)|Medium| 394|[Decode String](./0394-decode-string.js)|Medium| 395|[Longest Substring with At Least K Repeating Characters](./0395-longest-substring-with-at-least-k-repeating-characters.js)|Medium| +396|[Rotate Function](./0396-rotate-function.js)|Medium| 399|[Evaluate Division](./0399-evaluate-division.js)|Medium| 404|[Sum of Left Leaves](./0404-sum-of-left-leaves.js)|Easy| 405|[Convert a Number to Hexadecimal](./0405-convert-a-number-to-hexadecimal.js)|Easy| From 5aa4314fec8a30e0446194825d1b5c1ef3981553 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 24 Feb 2025 00:13:30 -0600 Subject: [PATCH 714/919] Add solution #397 --- 0397-integer-replacement.js | 29 +++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 30 insertions(+) create mode 100644 0397-integer-replacement.js diff --git a/0397-integer-replacement.js b/0397-integer-replacement.js new file mode 100644 index 00000000..6ffd39d5 --- /dev/null +++ b/0397-integer-replacement.js @@ -0,0 +1,29 @@ +/** + * 397. Integer Replacement + * https://leetcode.com/problems/integer-replacement/ + * Difficulty: Medium + * + * Given a positive integer n, you can apply one of the following operations: + * 1. If n is even, replace n with n / 2. + * 2. If n is odd, replace n with either n + 1 or n - 1. + * + * Return the minimum number of operations needed for n to become 1. + */ + +/** + * @param {number} n + * @return {number} + */ +/** + * @param {number} n + * @param {number} count + * @return {number} + */ +var integerReplacement = function(n, count = 0) { + if (n === 1) return count; + if (n % 2 === 0) { + return integerReplacement(n / 2, count + 1); + } else { + return Math.min(integerReplacement(n + 1, count + 1), integerReplacement(n - 1, count + 1)); + } +}; diff --git a/README.md b/README.md index dd839c02..0c9a7797 100644 --- a/README.md +++ b/README.md @@ -315,6 +315,7 @@ 394|[Decode String](./0394-decode-string.js)|Medium| 395|[Longest Substring with At Least K Repeating Characters](./0395-longest-substring-with-at-least-k-repeating-characters.js)|Medium| 396|[Rotate Function](./0396-rotate-function.js)|Medium| +397|[Integer Replacement](./0397-integer-replacement.js)|Medium| 399|[Evaluate Division](./0399-evaluate-division.js)|Medium| 404|[Sum of Left Leaves](./0404-sum-of-left-leaves.js)|Easy| 405|[Convert a Number to Hexadecimal](./0405-convert-a-number-to-hexadecimal.js)|Easy| From 7fa4ec79b0222ec2dd52020b95b46b3d98df96d9 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 24 Feb 2025 00:14:13 -0600 Subject: [PATCH 715/919] Add solution #398 --- 0398-random-pick-index.js | 35 +++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 36 insertions(+) create mode 100644 0398-random-pick-index.js diff --git a/0398-random-pick-index.js b/0398-random-pick-index.js new file mode 100644 index 00000000..92ec2fa9 --- /dev/null +++ b/0398-random-pick-index.js @@ -0,0 +1,35 @@ +/** + * 398. Random Pick Index + * https://leetcode.com/problems/random-pick-index/ + * Difficulty: Medium + * + * Given an integer array nums with possible duplicates, randomly output the index of a given + * target number. You can assume that the given target number must exist in the array. + * + * Implement the Solution class: + * - Solution(int[] nums) Initializes the object with the array nums. + * - int pick(int target) Picks a random index i from nums where nums[i] == target. If there + * are multiple valid i's, then each index should have an equal probability of returning. + */ + +/** + * @param {number[]} nums + */ +var Solution = function(nums) { + this.map = new Map(); + for (let i = 0; i < nums.length; i++) { + if (!this.map.has(nums[i])) { + this.map.set(nums[i], []); + } + this.map.get(nums[i]).push(i); + } +}; + +/** + * @param {number} target + * @return {number} + */ +Solution.prototype.pick = function(target) { + const result = this.map.get(target); + return result[Math.floor(Math.random() * result.length)]; +}; diff --git a/README.md b/README.md index 0c9a7797..211353cd 100644 --- a/README.md +++ b/README.md @@ -316,6 +316,7 @@ 395|[Longest Substring with At Least K Repeating Characters](./0395-longest-substring-with-at-least-k-repeating-characters.js)|Medium| 396|[Rotate Function](./0396-rotate-function.js)|Medium| 397|[Integer Replacement](./0397-integer-replacement.js)|Medium| +398|[Random Pick Index](./0398-random-pick-index.js)|Medium| 399|[Evaluate Division](./0399-evaluate-division.js)|Medium| 404|[Sum of Left Leaves](./0404-sum-of-left-leaves.js)|Easy| 405|[Convert a Number to Hexadecimal](./0405-convert-a-number-to-hexadecimal.js)|Easy| From 967227dd2ee77de4e7545df7337845880b8d6a29 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 24 Feb 2025 00:14:37 -0600 Subject: [PATCH 716/919] Add solution #400 --- 0400-nth-digit.js | 24 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 0400-nth-digit.js diff --git a/0400-nth-digit.js b/0400-nth-digit.js new file mode 100644 index 00000000..43bcf29e --- /dev/null +++ b/0400-nth-digit.js @@ -0,0 +1,24 @@ +/** + * 400. Nth Digit + * https://leetcode.com/problems/nth-digit/ + * Difficulty: Medium + * + * Given an integer n, return the nth digit of the infinite integer sequence + * [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...]. + */ + +/** + * @param {number} n + * @return {number} + */ +var findNthDigit = function(n) { + let total = 1; + let start = 1; + + for (let count = 9; n > total * count; total++, count *= 10, start *= 10) { + n -= total * count; + } + + start += Math.floor((n - 1) / total); + return +(start.toString()[(n - 1) % total]); +}; diff --git a/README.md b/README.md index 211353cd..59ff446d 100644 --- a/README.md +++ b/README.md @@ -318,6 +318,7 @@ 397|[Integer Replacement](./0397-integer-replacement.js)|Medium| 398|[Random Pick Index](./0398-random-pick-index.js)|Medium| 399|[Evaluate Division](./0399-evaluate-division.js)|Medium| +400|[Nth Digit](./0400-nth-digit.js)|Medium| 404|[Sum of Left Leaves](./0404-sum-of-left-leaves.js)|Easy| 405|[Convert a Number to Hexadecimal](./0405-convert-a-number-to-hexadecimal.js)|Easy| 407|[Trapping Rain Water II](./0407-trapping-rain-water-ii.js)|Hard| From fe236c60c65c40e3819de0913f014ccdb9f3bbde Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 24 Feb 2025 00:15:39 -0600 Subject: [PATCH 717/919] Add solution #401 --- 0401-binary-watch.js | 35 +++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 36 insertions(+) create mode 100644 0401-binary-watch.js diff --git a/0401-binary-watch.js b/0401-binary-watch.js new file mode 100644 index 00000000..b8f16531 --- /dev/null +++ b/0401-binary-watch.js @@ -0,0 +1,35 @@ +/** + * 401. Binary Watch + * https://leetcode.com/problems/binary-watch/ + * Difficulty: Easy + * + * A binary watch has 4 LEDs on the top to represent the hours (0-11), and 6 LEDs on the bottom + * to represent the minutes (0-59). Each LED represents a zero or one, with the least significant + * bit on the right. + * - For example, the below binary watch reads "4:51". + * Given an integer turnedOn which represents the number of LEDs that are currently on (ignoring + * the PM), return all possible times the watch could represent. You may return the answer in + * any order. + * The hour must not contain a leading zero. + * - For example, "01:00" is not valid. It should be "1:00". + * The minute must consist of two digits and may contain a leading zero. + * - For example, "10:2" is not valid. It should be "10:02". + */ + +/** + * @param {number} turnedOn + * @return {string[]} + */ +var readBinaryWatch = function(turnedOn) { + const result = []; + + for (let h = 0; h < 12; h++) { + for (let m = 0; m < 60; m++) { + if (h.toString(2).split('1').length - 1 + m.toString(2).split('1').length - 1 === turnedOn) { + result.push(`${h}:${m < 10 ? '0' + m : m}`); + } + } + } + + return result; +}; diff --git a/README.md b/README.md index 59ff446d..105ca05b 100644 --- a/README.md +++ b/README.md @@ -319,6 +319,7 @@ 398|[Random Pick Index](./0398-random-pick-index.js)|Medium| 399|[Evaluate Division](./0399-evaluate-division.js)|Medium| 400|[Nth Digit](./0400-nth-digit.js)|Medium| +401|[Binary Watch](./0401-binary-watch.js)|Easy| 404|[Sum of Left Leaves](./0404-sum-of-left-leaves.js)|Easy| 405|[Convert a Number to Hexadecimal](./0405-convert-a-number-to-hexadecimal.js)|Easy| 407|[Trapping Rain Water II](./0407-trapping-rain-water-ii.js)|Hard| From 7142f6aee0d60a972f3d8c051fefbf7a88548adb Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 25 Feb 2025 02:08:35 -0600 Subject: [PATCH 718/919] Add solution #1524 --- 1524-number-of-sub-arrays-with-odd-sum.js | 26 +++++++++++++++++++++++ README.md | 1 + 2 files changed, 27 insertions(+) create mode 100644 1524-number-of-sub-arrays-with-odd-sum.js diff --git a/1524-number-of-sub-arrays-with-odd-sum.js b/1524-number-of-sub-arrays-with-odd-sum.js new file mode 100644 index 00000000..91974633 --- /dev/null +++ b/1524-number-of-sub-arrays-with-odd-sum.js @@ -0,0 +1,26 @@ +/** + * 1524. Number of Sub-arrays With Odd Sum + * https://leetcode.com/problems/number-of-sub-arrays-with-odd-sum/ + * Difficulty: Medium + * + * Given an array of integers arr, return the number of subarrays with an odd sum. + * + * Since the answer can be very large, return it modulo 109 + 7. + */ + +/** + * @param {number[]} arr + * @return {number} + */ +var numOfSubarrays = function(arr) { + let even = 0; + let odd = 0; + + for (let i = 0, total = 0; i < arr.length; i++) { + total += arr[i]; + odd += +(total % 2 === 1); + even += +(total % 2 === 0); + } + + return (odd * even + odd) % (1e9 + 7); +}; diff --git a/README.md b/README.md index 105ca05b..ecb59db6 100644 --- a/README.md +++ b/README.md @@ -557,6 +557,7 @@ 1507|[Reformat Date](./1507-reformat-date.js)|Easy| 1512|[Number of Good Pairs](./1512-number-of-good-pairs.js)|Easy| 1519|[Number of Nodes in the Sub-Tree With the Same Label](./1519-number-of-nodes-in-the-sub-tree-with-the-same-label.js)|Medium| +1524|[Number of Sub-arrays With Odd Sum](./1524-number-of-sub-arrays-with-odd-sum.js)|Medium| 1528|[Shuffle String](./1528-shuffle-string.js)|Easy| 1535|[Find the Winner of an Array Game](./1535-find-the-winner-of-an-array-game.js)|Medium| 1550|[Three Consecutive Odds](./1550-three-consecutive-odds.js)|Easy| From de083f26f3c766a8c094ed469238ae9dbeb9aa69 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 25 Feb 2025 02:09:22 -0600 Subject: [PATCH 719/919] Add solution #402 --- 0402-remove-k-digits.js | 33 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 0402-remove-k-digits.js diff --git a/0402-remove-k-digits.js b/0402-remove-k-digits.js new file mode 100644 index 00000000..4035c7a7 --- /dev/null +++ b/0402-remove-k-digits.js @@ -0,0 +1,33 @@ +/** + * 402. Remove K Digits + * https://leetcode.com/problems/remove-k-digits/ + * Difficulty: Medium + * + * Given string num representing a non-negative integer num, and an integer k, return + * the smallest possible integer after removing k digits from num. + */ + +/** + * @param {string} num + * @param {number} k + * @return {string} + */ +var removeKdigits = function(num, k) { + const stack = []; + + for (const n of num) { + while (k > 0 && stack.length && stack[stack.length - 1] > n) { + stack.pop(); + k--; + } + stack.push(n); + } + + while (k > 0) { + stack.pop(); + k--; + } + + const result = stack.join('').replace(/^0+/, ''); + return result.length ? result : '0'; +}; diff --git a/README.md b/README.md index ecb59db6..728d69b3 100644 --- a/README.md +++ b/README.md @@ -320,6 +320,7 @@ 399|[Evaluate Division](./0399-evaluate-division.js)|Medium| 400|[Nth Digit](./0400-nth-digit.js)|Medium| 401|[Binary Watch](./0401-binary-watch.js)|Easy| +402|[Remove K Digits](./0402-remove-k-digits.js)|Medium| 404|[Sum of Left Leaves](./0404-sum-of-left-leaves.js)|Easy| 405|[Convert a Number to Hexadecimal](./0405-convert-a-number-to-hexadecimal.js)|Easy| 407|[Trapping Rain Water II](./0407-trapping-rain-water-ii.js)|Hard| From b28513697407eab6545863ccadeb5508581be636 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 25 Feb 2025 02:10:15 -0600 Subject: [PATCH 720/919] Add solution #403 --- 0403-frog-jump.js | 39 +++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 40 insertions(+) create mode 100644 0403-frog-jump.js diff --git a/0403-frog-jump.js b/0403-frog-jump.js new file mode 100644 index 00000000..f667c5d7 --- /dev/null +++ b/0403-frog-jump.js @@ -0,0 +1,39 @@ +/** + * 403. Frog Jump + * https://leetcode.com/problems/frog-jump/ + * Difficulty: Hard + * + * A frog is crossing a river. The river is divided into some number of units, and at each + * unit, there may or may not exist a stone. The frog can jump on a stone, but it must not + * jump into the water. + * + * Given a list of stones positions (in units) in sorted ascending order, determine if the + * frog can cross the river by landing on the last stone. Initially, the frog is on the + * first stone and assumes the first jump must be 1 unit. + * + * If the frog's last jump was k units, its next jump must be either k - 1, k, or k + 1 + * units. The frog can only jump in the forward direction. + */ + +/** + * @param {number[]} stones + * @return {boolean} + */ +var canCross = function(stones) { + const dp = new Map(); + stones.forEach(stone => dp.set(stone, new Set())); + dp.get(0).add(0); + + for (let i = 0; i < stones.length; i++) { + const curr = stones[i]; + for (const prevJump of dp.get(curr)) { + for (const jump of [prevJump - 1, prevJump, prevJump + 1]) { + if (jump > 0 && dp.has(curr + jump)) { + dp.get(curr + jump).add(jump); + } + } + } + } + + return dp.get(stones[stones.length - 1]).size > 0; +}; diff --git a/README.md b/README.md index 728d69b3..26e97898 100644 --- a/README.md +++ b/README.md @@ -321,6 +321,7 @@ 400|[Nth Digit](./0400-nth-digit.js)|Medium| 401|[Binary Watch](./0401-binary-watch.js)|Easy| 402|[Remove K Digits](./0402-remove-k-digits.js)|Medium| +403|[Frog Jump](./0403-frog-jump.js)|Hard| 404|[Sum of Left Leaves](./0404-sum-of-left-leaves.js)|Easy| 405|[Convert a Number to Hexadecimal](./0405-convert-a-number-to-hexadecimal.js)|Easy| 407|[Trapping Rain Water II](./0407-trapping-rain-water-ii.js)|Hard| From a53f77bb7aafd9699fa8f3ae9ef7cc1abc115942 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 25 Feb 2025 02:10:57 -0600 Subject: [PATCH 721/919] Add solution #406 --- 0406-queue-reconstruction-by-height.js | 23 +++++++++++++++++++++++ README.md | 1 + 2 files changed, 24 insertions(+) create mode 100644 0406-queue-reconstruction-by-height.js diff --git a/0406-queue-reconstruction-by-height.js b/0406-queue-reconstruction-by-height.js new file mode 100644 index 00000000..a34dc3ff --- /dev/null +++ b/0406-queue-reconstruction-by-height.js @@ -0,0 +1,23 @@ +/** + * 406. Queue Reconstruction by Height + * https://leetcode.com/problems/queue-reconstruction-by-height/ + * Difficulty: Medium + * + * You are given an array of people, people, which are the attributes of some people in a queue + * (not necessarily in order). Each people[i] = [hi, ki] represents the ith person of height + * hi with exactly ki other people in front who have a height greater than or equal to hi. + * + * Reconstruct and return the queue that is represented by the input array people. The returned + * queue should be formatted as an array queue, where queue[j] = [hj, kj] is the attributes of + * the jth person in the queue (queue[0] is the person at the front of the queue). + */ + +/** + * @param {number[][]} people + * @return {number[][]} + */ +var reconstructQueue = function(people) { + return people + .sort(([h1, k1], [h2, k2]) => h2 - h1 || k1 - k2) + .reduce((queue, person) => queue.splice(person[1], 0, person) && queue, []); +}; diff --git a/README.md b/README.md index 26e97898..52b511b9 100644 --- a/README.md +++ b/README.md @@ -324,6 +324,7 @@ 403|[Frog Jump](./0403-frog-jump.js)|Hard| 404|[Sum of Left Leaves](./0404-sum-of-left-leaves.js)|Easy| 405|[Convert a Number to Hexadecimal](./0405-convert-a-number-to-hexadecimal.js)|Easy| +406|[Queue Reconstruction by Height](./0406-queue-reconstruction-by-height.js)|Medium| 407|[Trapping Rain Water II](./0407-trapping-rain-water-ii.js)|Hard| 412|[Fizz Buzz](./0412-fizz-buzz.js)|Easy| 414|[Third Maximum Number](./0414-third-maximum-number.js)|Easy| From c4339207533dcd66aa19e411e0fe9368d7309c69 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 25 Feb 2025 02:11:55 -0600 Subject: [PATCH 722/919] Add solution #409 --- 0409-longest-palindrome.js | 21 +++++++++++++++++++++ README.md | 1 + 2 files changed, 22 insertions(+) create mode 100644 0409-longest-palindrome.js diff --git a/0409-longest-palindrome.js b/0409-longest-palindrome.js new file mode 100644 index 00000000..93e91cb3 --- /dev/null +++ b/0409-longest-palindrome.js @@ -0,0 +1,21 @@ +/** + * 409. Longest Palindrome + * https://leetcode.com/problems/longest-palindrome/ + * Difficulty: Easy + * + * Given a string s which consists of lowercase or uppercase letters, return the length + * of the longest palindrome that can be built with those letters. + * + * Letters are case sensitive, for example, "Aa" is not considered a palindrome. + */ + +/** + * @param {string} s + * @return {number} + */ +var longestPalindrome = function(s) { + const set = new Set(); + return [...s].reduce((count, c) => { + return set.delete(c) ? count + 2 : (set.add(c), count); + }, 0) + (set.size > 0 ? 1 : 0); +}; diff --git a/README.md b/README.md index 52b511b9..2fa897ad 100644 --- a/README.md +++ b/README.md @@ -326,6 +326,7 @@ 405|[Convert a Number to Hexadecimal](./0405-convert-a-number-to-hexadecimal.js)|Easy| 406|[Queue Reconstruction by Height](./0406-queue-reconstruction-by-height.js)|Medium| 407|[Trapping Rain Water II](./0407-trapping-rain-water-ii.js)|Hard| +409|[Longest Palindrome](./0409-longest-palindrome.js)|Easy| 412|[Fizz Buzz](./0412-fizz-buzz.js)|Easy| 414|[Third Maximum Number](./0414-third-maximum-number.js)|Easy| 415|[Add Strings](./0415-add-strings.js)|Easy| From 90fce9def1b7de4d65c5672c688d35b4ee78051b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 25 Feb 2025 16:21:11 -0600 Subject: [PATCH 723/919] Add solution #2 --- 0002-add-two-numbers.js | 21 ++++++++------------- 1 file changed, 8 insertions(+), 13 deletions(-) diff --git a/0002-add-two-numbers.js b/0002-add-two-numbers.js index 93b52403..81b72151 100644 --- a/0002-add-two-numbers.js +++ b/0002-add-two-numbers.js @@ -4,8 +4,9 @@ * Difficulty: Medium * * You are given two non-empty linked lists representing two non-negative integers. - * The digits are stored in reverse order, and each of their nodes contains a single - * digit. Add the two numbers and return the sum as a linked list. + * + * The digits are stored in reverse order, and each of their nodes contains a single digit. + * Add the two numbers and return the sum as a linked list. * * You may assume the two numbers do not contain any leading zero, except the number 0 itself. */ @@ -24,19 +25,13 @@ */ var addTwoNumbers = function(l1, l2) { const result = new ListNode(); - let tail = result; - let carry = 0; - - while (l1 || l2 || carry) { - const v1 = l1 ? l1.val : 0; - const v2 = l2 ? l2.val : 0; - const v = v1 + v2 + carry; - tail.next = new ListNode(v % 10); + for (let tail = result, carry = 0; l1 || l2 || carry;) { + const value = (l1?.val ?? 0) + (l2?.val ?? 0) + carry; + tail.next = new ListNode(value % 10); tail = tail.next; - carry = v >= 10 ? 1 : 0; - l1 = l1 && l1.next; - l2 = l2 && l2.next; + carry = value >= 10 ? 1 : 0; + [l1, l2] = [l1 && l1.next, l2 && l2.next]; } return result.next; From ee4075861f38211ae7a89f22c362eb9a81ab62e8 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 25 Feb 2025 16:23:33 -0600 Subject: [PATCH 724/919] Add solution #128 --- 0128-longest-consecutive-sequence.js | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/0128-longest-consecutive-sequence.js b/0128-longest-consecutive-sequence.js index b72a6fe5..cb70f331 100644 --- a/0128-longest-consecutive-sequence.js +++ b/0128-longest-consecutive-sequence.js @@ -3,8 +3,8 @@ * https://leetcode.com/problems/longest-consecutive-sequence/ * Difficulty: Medium * - * Given an unsorted array of integers nums, return the length of the - * longest consecutive elements sequence. + * Given an unsorted array of integers nums, return the length of the longest consecutive + * elements sequence. * * You must write an algorithm that runs in O(n) time. */ @@ -17,13 +17,16 @@ var longestConsecutive = function(nums) { const set = new Set(nums); let result = 0; - for (let i = 0; i < nums.length; i++) { - if (!set.has(nums[i] - 1)) { - let streak = 1; - while (set.has(nums[i] + streak)) { - streak++; + for (const num of set) { + if (!set.has(num - 1)) { + let count = 1; + let n = num; + + while (set.has(n + 1)) { + n++; + count++; } - result = Math.max(result, streak); + result = Math.max(result, count); } } From 5e17e61a4a9421bc41c937573d775c593fe4bb6e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 25 Feb 2025 18:14:01 -0600 Subject: [PATCH 725/919] Add solution #283 --- 0283-move-zeroes.js | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/0283-move-zeroes.js b/0283-move-zeroes.js index 3264be77..d3008579 100644 --- a/0283-move-zeroes.js +++ b/0283-move-zeroes.js @@ -3,7 +3,8 @@ * https://leetcode.com/problems/move-zeroes/ * Difficulty: Easy * - * Given an integer array `nums`, move all `0`'s to the end of it while maintaining the relative order of the non-zero elements. + * Given an integer array nums, move all 0's to the end of it while maintaining the + * relative order of the non-zero elements. * * Note that you must do this in-place without making a copy of the array. */ @@ -15,15 +16,7 @@ var moveZeroes = function(nums) { for (let i = 0, j = 0; i < nums.length; i++) { if (nums[i] !== 0) { - swap(nums, i, j++); + [nums[i], nums[j++]] = [nums[j], nums[i]]; } } - - return nums; }; - -function swap(nums, i, j) { - const temp = nums[i]; - nums[i] = nums[j]; - nums[j] = temp; -} From 47a77068f242d16b5f3614d0420a02b77ed9fa13 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 25 Feb 2025 18:18:54 -0600 Subject: [PATCH 726/919] Add solution #42 --- 0042-trapping-rain-water.js | 23 ++++++----------------- 1 file changed, 6 insertions(+), 17 deletions(-) diff --git a/0042-trapping-rain-water.js b/0042-trapping-rain-water.js index 871e37a7..15766764 100644 --- a/0042-trapping-rain-water.js +++ b/0042-trapping-rain-water.js @@ -3,8 +3,8 @@ * https://leetcode.com/problems/trapping-rain-water/ * Difficulty: Hard * - * Given `n` non-negative integers representing an elevation map where the width - * of each bar is `1`, compute how much water it can trap after raining. + * Given n non-negative integers representing an elevation map where the + * width of each bar is 1, compute how much water it can trap after raining. */ /** @@ -12,23 +12,12 @@ * @return {number} */ var trap = function(height) { - const leftMax = []; - const rightMax = []; let result = 0; - leftMax[0] = height[0]; - rightMax[height.length - 1] = height[height.length - 1]; - - for (let i = 1; i < height.length; i++) { - leftMax[i] = Math.max(height[i], leftMax[i - 1]); - } - - for (let i = height.length - 2; i > -1; i--) { - rightMax[i] = Math.max(height[i], rightMax[i + 1]); - } - - for (let i = 0; i < height.length; i++) { - result += Math.min(leftMax[i], rightMax[i]) - height[i]; + for (let left = 0, right = height.length - 1, maxL = 0, maxR = 0; left < right;) { + maxL = Math.max(maxL, height[left]); + maxR = Math.max(maxR, height[right]); + result += maxL < maxR ? maxL - height[left++] : maxR - height[right--]; } return result; From d5ada0ea80ec08f04d2b44e08bb494499b22b2ed Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 25 Feb 2025 18:23:56 -0600 Subject: [PATCH 727/919] Add solution #15 --- 0015-3sum.js | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/0015-3sum.js b/0015-3sum.js index a34d0eff..35d01c95 100644 --- a/0015-3sum.js +++ b/0015-3sum.js @@ -3,8 +3,8 @@ * https://leetcode.com/problems/3sum/ * Difficulty: Medium * - * Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, - * i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. + * Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] + * such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. * * Notice that the solution set must not contain duplicate triplets. */ @@ -14,25 +14,30 @@ * @return {number[][]} */ var threeSum = function(nums) { - const result = new Set(); - + const result = []; nums.sort((a, b) => a - b); for (let i = 0; i < nums.length - 2; i++) { + if (i > 0 && nums[i] === nums[i - 1]) continue; let j = i + 1; let k = nums.length - 1; - while (j < k) { const sum = nums[i] + nums[j] + nums[k]; if (!sum) { - result.add(JSON.stringify([nums[i], nums[j++], nums[k--]])); - } else if (sum > 0) { + result.push([nums[i], nums[j], nums[k]]); + j++; k--; + while (j < k && nums[j] === nums[j - 1]) { + j++; + } + while (j < k && nums[k] === nums[k + 1]) { + k--; + } } else { - j++; + sum < 0 ? j++ : k--; } } } - return [...result].map(JSON.parse); + return result; }; From 002e104b41653388e022a41e0cb5d6713e167305 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 25 Feb 2025 18:35:27 -0600 Subject: [PATCH 728/919] Add solution #763 --- 0763-partition-labels.js | 37 +++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 38 insertions(+) create mode 100644 0763-partition-labels.js diff --git a/0763-partition-labels.js b/0763-partition-labels.js new file mode 100644 index 00000000..0c248ee7 --- /dev/null +++ b/0763-partition-labels.js @@ -0,0 +1,37 @@ +/** + * 763. Partition Labels + * https://leetcode.com/problems/partition-labels/ + * Difficulty: Medium + * + * You are given a string s. We want to partition the string into as many parts as + * possible so that each letter appears in at most one part. For example, the + * string "ababcc" can be partitioned into ["abab", "cc"], but partitions such as + * ["aba", "bcc"] or ["ab", "ab", "cc"] are invalid. + * + * Note that the partition is done so that after concatenating all the parts in + * order, the resultant string should be s. + * + * Return a list of integers representing the size of these parts. + */ + +/** + * @param {string} s + * @return {number[]} + */ +var partitionLabels = function(s) { + const map = new Map(); + for (let i = 0; i < s.length; i++) { + map.set(s[i], i); + } + + const result = []; + for (let i = 0, start = 0, end = 0; i < s.length; i++) { + end = Math.max(end, map.get(s[i])); + if (i === end) { + result.push(end - start + 1); + start = i + 1; + } + } + + return result; +}; diff --git a/README.md b/README.md index 2fa897ad..9fd0e94f 100644 --- a/README.md +++ b/README.md @@ -421,6 +421,7 @@ 747|[Largest Number At Least Twice of Others](./0747-largest-number-at-least-twice-of-others.js)|Easy| 748|[Shortest Completing Word](./0748-shortest-completing-word.js)|Easy| 762|[Prime Number of Set Bits in Binary Representation](./0762-prime-number-of-set-bits-in-binary-representation.js)|Easy| +763|[Partition Labels](./0763-partition-labels.js)|Medium| 784|[Letter Case Permutation](./0784-letter-case-permutation.js)|Medium| 790|[Domino and Tromino Tiling](./0790-domino-and-tromino-tiling.js)|Medium| 791|[Custom Sort String](./0791-custom-sort-string.js)|Medium| From d884d730cf59854566b34f52d7ee0ccb4d83373e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 25 Feb 2025 18:36:13 -0600 Subject: [PATCH 729/919] Add solution #1749 --- 1749-maximum-absolute-sum-of-any-subarray.js | 30 ++++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 1749-maximum-absolute-sum-of-any-subarray.js diff --git a/1749-maximum-absolute-sum-of-any-subarray.js b/1749-maximum-absolute-sum-of-any-subarray.js new file mode 100644 index 00000000..ab122570 --- /dev/null +++ b/1749-maximum-absolute-sum-of-any-subarray.js @@ -0,0 +1,30 @@ +/** + * 1749. Maximum Absolute Sum of Any Subarray + * https://leetcode.com/problems/maximum-absolute-sum-of-any-subarray/ + * Difficulty: Medium + * + * You are given an integer array nums. The absolute sum of a subarray + * [numsl, numsl+1, ..., numsr-1, numsr] is abs(numsl + numsl+1 + ... + numsr-1 + numsr). + * + * Return the maximum absolute sum of any (possibly empty) subarray of nums. + * + * Note that abs(x) is defined as follows: + * - If x is a negative integer, then abs(x) = -x. + * - If x is a non-negative integer, then abs(x) = x. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var maxAbsoluteSum = function(nums) { + let result = 0; + + for (let i = 0, min = 0, max = 0; i < nums.length; i++) { + max = Math.max(nums[i], max + nums[i]); + min = Math.min(nums[i], min + nums[i]); + result = Math.max(result, Math.abs(max), Math.abs(min)); + } + + return result; +}; diff --git a/README.md b/README.md index 9fd0e94f..bc41a92a 100644 --- a/README.md +++ b/README.md @@ -580,6 +580,7 @@ 1726|[Tuple with Same Product](./1726-tuple-with-same-product.js)|Medium| 1732|[Find the Highest Altitude](./1732-find-the-highest-altitude.js)|Easy| 1748|[Sum of Unique Elements](./1748-sum-of-unique-elements.js)|Easy| +1749|[Maximum Absolute Sum of Any Subarray](./1749-maximum-absolute-sum-of-any-subarray.js)|Medium| 1752|[Check if Array Is Sorted and Rotated](./1752-check-if-array-is-sorted-and-rotated.js)|Easy| 1764|[Form Array by Concatenating Subarrays of Another Array](./1764-form-array-by-concatenating-subarrays-of-another-array.js)|Medium| 1765|[Map of Highest Peak](./1765-map-of-highest-peak.js)|Medium| From 5573ce61dc347cf5ba2de3e296a012d8553d0443 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 25 Feb 2025 18:36:56 -0600 Subject: [PATCH 730/919] Add solution #410 --- 0410-split-array-largest-sum.js | 45 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 46 insertions(+) create mode 100644 0410-split-array-largest-sum.js diff --git a/0410-split-array-largest-sum.js b/0410-split-array-largest-sum.js new file mode 100644 index 00000000..3d18d032 --- /dev/null +++ b/0410-split-array-largest-sum.js @@ -0,0 +1,45 @@ +/** + * 410. Split Array Largest Sum + * https://leetcode.com/problems/split-array-largest-sum/ + * Difficulty: Hard + * + * Given an integer array nums and an integer k, split nums into k non-empty subarrays + * such that the largest sum of any subarray is minimized. + * + * Return the minimized largest sum of the split. + * + * A subarray is a contiguous part of the array. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var splitArray = function(nums, k) { + let left = Math.max(...nums); + let right = nums.reduce((a, b) => a + b); + + while (left < right) { + const mid = Math.floor((left + right) / 2); + let count = 1; + let sum = 0; + + for (const num of nums) { + if (sum + num <= mid) { + sum += num; + } else { + count++; + sum = num; + } + } + + if (count > k) { + left = mid + 1; + } else { + right = mid; + } + } + + return left; +}; diff --git a/README.md b/README.md index bc41a92a..c8cebdb6 100644 --- a/README.md +++ b/README.md @@ -327,6 +327,7 @@ 406|[Queue Reconstruction by Height](./0406-queue-reconstruction-by-height.js)|Medium| 407|[Trapping Rain Water II](./0407-trapping-rain-water-ii.js)|Hard| 409|[Longest Palindrome](./0409-longest-palindrome.js)|Easy| +410|[Split Array Largest Sum](./0410-split-array-largest-sum.js)|Hard| 412|[Fizz Buzz](./0412-fizz-buzz.js)|Easy| 414|[Third Maximum Number](./0414-third-maximum-number.js)|Easy| 415|[Add Strings](./0415-add-strings.js)|Easy| From 8b2d9570df654206426a7f2bc3bc7be67204bb23 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 25 Feb 2025 18:37:30 -0600 Subject: [PATCH 731/919] Add solution #413 --- 0413-arithmetic-slices.js | 34 ++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 0413-arithmetic-slices.js diff --git a/0413-arithmetic-slices.js b/0413-arithmetic-slices.js new file mode 100644 index 00000000..607f3152 --- /dev/null +++ b/0413-arithmetic-slices.js @@ -0,0 +1,34 @@ +/** + * 413. Arithmetic Slices + * https://leetcode.com/problems/arithmetic-slices/ + * Difficulty: Medium + * + * An integer array is called arithmetic if it consists of at least three elements and if + * the difference between any two consecutive elements is the same. + * + * For example, [1,3,5,7,9], [7,7,7,7], and [3,-1,-5,-9] are arithmetic sequences. + * + * Given an integer array nums, return the number of arithmetic subarrays of nums. + * + * A subarray is a contiguous subsequence of the array. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var numberOfArithmeticSlices = function(nums) { + if (nums.length < 3) return 0; + let result = 0; + + for (let i = 2, value = 0; i < nums.length; i++) { + if (nums[i] - nums[i - 1] === nums[i - 1] - nums[i - 2]) { + value++; + result += value; + } else { + value = 0; + } + } + + return result; +}; diff --git a/README.md b/README.md index c8cebdb6..9ac220eb 100644 --- a/README.md +++ b/README.md @@ -329,6 +329,7 @@ 409|[Longest Palindrome](./0409-longest-palindrome.js)|Easy| 410|[Split Array Largest Sum](./0410-split-array-largest-sum.js)|Hard| 412|[Fizz Buzz](./0412-fizz-buzz.js)|Easy| +413|[Arithmetic Slices](./0413-arithmetic-slices.js)|Medium| 414|[Third Maximum Number](./0414-third-maximum-number.js)|Easy| 415|[Add Strings](./0415-add-strings.js)|Easy| 416|[Partition Equal Subset Sum](./0416-partition-equal-subset-sum.js)|Medium| From c8d95b81dcfe1ced02b9ef5b21288b581ab275e4 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 25 Feb 2025 18:38:49 -0600 Subject: [PATCH 732/919] Add solution #417 --- 0417-pacific-atlantic-water-flow.js | 63 +++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 64 insertions(+) create mode 100644 0417-pacific-atlantic-water-flow.js diff --git a/0417-pacific-atlantic-water-flow.js b/0417-pacific-atlantic-water-flow.js new file mode 100644 index 00000000..0158b2b8 --- /dev/null +++ b/0417-pacific-atlantic-water-flow.js @@ -0,0 +1,63 @@ +/** + * 417. Pacific Atlantic Water Flow + * https://leetcode.com/problems/pacific-atlantic-water-flow/ + * Difficulty: Medium + * + * There is an m x n rectangular island that borders both the Pacific Ocean and Atlantic Ocean. + * The Pacific Ocean touches the island's left and top edges, and the Atlantic Ocean touches + * the island's right and bottom edges. + * + * The island is partitioned into a grid of square cells. You are given an m x n integer + * matrix heights where heights[r][c] represents the height above sea level of the cell + * at coordinate (r, c). + * + * The island receives a lot of rain, and the rain water can flow to neighboring cells directly + * north, south, east, and west if the neighboring cell's height is less than or equal to the + * current cell's height. Water can flow from any cell adjacent to an ocean into the ocean. + * + * Return a 2D list of grid coordinates result where result[i] = [ri, ci] denotes that rain water + * can flow from cell (ri, ci) to both the Pacific and Atlantic oceans. + */ + +/** + * @param {number[][]} heights + * @return {number[][]} + */ +var pacificAtlantic = function(heights) { + const result = []; + const pacific = new Set(); + const atlantic = new Set(); + + for (let i = 0; i < heights.length; i++) { + dfs(i, 0, pacific); + dfs(i, heights[0].length - 1, atlantic); + } + for (let j = 0; j < heights[0].length; j++) { + dfs(0, j, pacific); + dfs(heights.length - 1, j, atlantic); + } + + for (let i = 0; i < heights.length; i++) { + for (let j = 0; j < heights[0].length; j++) { + const key = `${i},${j}`; + if (pacific.has(key) && atlantic.has(key)) { + result.push([i, j]); + } + } + } + + return result; + + function dfs(r, c, ocean) { + const key = `${r},${c}`; + if (ocean.has(key)) return; + ocean.add(key); + + [[r - 1, c], [r + 1, c], [r, c - 1], [r, c + 1]].forEach(([nr, nc]) => { + if (nr >= 0 && nr < heights.length && nc >= 0 && nc < heights[0].length + && heights[nr][nc] >= heights[r][c]) { + dfs(nr, nc, ocean); + } + }); + } +}; diff --git a/README.md b/README.md index 9ac220eb..ddb27608 100644 --- a/README.md +++ b/README.md @@ -333,6 +333,7 @@ 414|[Third Maximum Number](./0414-third-maximum-number.js)|Easy| 415|[Add Strings](./0415-add-strings.js)|Easy| 416|[Partition Equal Subset Sum](./0416-partition-equal-subset-sum.js)|Medium| +417|[Pacific Atlantic Water Flow](./0417-pacific-atlantic-water-flow.js)|Medium| 419|[Battleships in a Board](./0419-battleships-in-a-board.js)|Medium| 434|[Number of Segments in a String](./0434-number-of-segments-in-a-string.js)|Easy| 435|[Non-overlapping Intervals](./0435-non-overlapping-intervals.js)|Medium| From d4eb941a4c3bfa98aa0969f5827da09baf7b91f6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 26 Feb 2025 01:57:35 -0600 Subject: [PATCH 733/919] Add solution #420 --- 0420-strong-password-checker.js | 60 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 61 insertions(+) create mode 100644 0420-strong-password-checker.js diff --git a/0420-strong-password-checker.js b/0420-strong-password-checker.js new file mode 100644 index 00000000..727562f3 --- /dev/null +++ b/0420-strong-password-checker.js @@ -0,0 +1,60 @@ +/** + * 420. Strong Password Checker + * https://leetcode.com/problems/strong-password-checker/ + * Difficulty: Hard + * + * A password is considered strong if the below conditions are all met: + * - It has at least 6 characters and at most 20 characters. + * - It contains at least one lowercase letter, at least one uppercase letter, and at + * least one digit. + * - It does not contain three repeating characters in a row (i.e., "Baaabb0" is weak, + * but "Baaba0" is strong). + * + * Given a string password, return the minimum number of steps required to make password + * strong. if password is already strong, return 0. + * + * In one step, you can: + * - Insert one character to password, + * - Delete one character from password, or + * - Replace one character of password with another character. + */ + +/** + * @param {string} password + * @return {number} + */ +var strongPasswordChecker = function(password) { + const types = 3 - (/[a-z]/.test(password) + /[A-Z]/.test(password) + /[0-9]/.test(password)); + let replacements = 0; + let modOneCount = 0; + let modTwoCount = 0; + + if (password.length < 6) { + return Math.max(6 - password.length, types); + } + + for (let i = 0; i < password.length;) { + let j = i; + while (j < password.length && password[j] === password[i]) { + j++; + } + const repeatLength = j - i; + if (repeatLength >= 3) { + replacements += Math.floor(repeatLength / 3); + if (repeatLength % 3 === 0) modOneCount++; + if (repeatLength % 3 === 1) modTwoCount++; + } + i = j; + } + + if (password.length <= 20) { + return Math.max(types, replacements); + } + + const deletions = password.length - 20; + replacements -= Math.min(deletions, modOneCount); + replacements -= Math.min(Math.max(deletions - modOneCount, 0), modTwoCount * 2) / 2; + replacements -= Math.max(deletions - modOneCount - modTwoCount * 2, 0) / 3; + + return deletions + Math.max(types, Math.max(0, Math.ceil(replacements))); +}; diff --git a/README.md b/README.md index ddb27608..3adfebf3 100644 --- a/README.md +++ b/README.md @@ -335,6 +335,7 @@ 416|[Partition Equal Subset Sum](./0416-partition-equal-subset-sum.js)|Medium| 417|[Pacific Atlantic Water Flow](./0417-pacific-atlantic-water-flow.js)|Medium| 419|[Battleships in a Board](./0419-battleships-in-a-board.js)|Medium| +420|[Strong Password Checker](./0420-strong-password-checker.js)|Hard| 434|[Number of Segments in a String](./0434-number-of-segments-in-a-string.js)|Easy| 435|[Non-overlapping Intervals](./0435-non-overlapping-intervals.js)|Medium| 437|[Path Sum III](./0437-path-sum-iii.js)|Medium| From ec43b871c4d6cbf63542da4ca8e18a7ba8d38365 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 26 Feb 2025 01:58:12 -0600 Subject: [PATCH 734/919] Add solution #421 --- ...-maximum-xor-of-two-numbers-in-an-array.js | 30 +++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 0421-maximum-xor-of-two-numbers-in-an-array.js diff --git a/0421-maximum-xor-of-two-numbers-in-an-array.js b/0421-maximum-xor-of-two-numbers-in-an-array.js new file mode 100644 index 00000000..0f5433e6 --- /dev/null +++ b/0421-maximum-xor-of-two-numbers-in-an-array.js @@ -0,0 +1,30 @@ +/** + * 421. Maximum XOR of Two Numbers in an Array + * https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/ + * Difficulty: Medium + * + * Given an integer array nums, return the maximum result of nums[i] XOR + * nums[j], where 0 <= i <= j < n. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var findMaximumXOR = function(nums) { + let result = 0; + + for (let i = 31, mask = 0; i >= 0; i--) { + mask |= (1 << i); + const set = new Set(nums.map(num => num & mask)); + const target = result | (1 << i); + for (const prefix of set) { + if (set.has(prefix ^ target)) { + result = target; + break; + } + } + } + + return result; +}; diff --git a/README.md b/README.md index 3adfebf3..e89cda5e 100644 --- a/README.md +++ b/README.md @@ -336,6 +336,7 @@ 417|[Pacific Atlantic Water Flow](./0417-pacific-atlantic-water-flow.js)|Medium| 419|[Battleships in a Board](./0419-battleships-in-a-board.js)|Medium| 420|[Strong Password Checker](./0420-strong-password-checker.js)|Hard| +421|[Maximum XOR of Two Numbers in an Array](./0421-maximum-xor-of-two-numbers-in-an-array.js)|Medium| 434|[Number of Segments in a String](./0434-number-of-segments-in-a-string.js)|Easy| 435|[Non-overlapping Intervals](./0435-non-overlapping-intervals.js)|Medium| 437|[Path Sum III](./0437-path-sum-iii.js)|Medium| From 3b5a0b17811f04a33ce37c331da5bef2c6e3b8d4 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 26 Feb 2025 01:59:01 -0600 Subject: [PATCH 735/919] Add solution #423 --- ...econstruct-original-digits-from-english.js | 28 +++++++++++++++++++ README.md | 1 + 2 files changed, 29 insertions(+) create mode 100644 0423-reconstruct-original-digits-from-english.js diff --git a/0423-reconstruct-original-digits-from-english.js b/0423-reconstruct-original-digits-from-english.js new file mode 100644 index 00000000..1c6a3cc0 --- /dev/null +++ b/0423-reconstruct-original-digits-from-english.js @@ -0,0 +1,28 @@ +/** + * 423. Reconstruct Original Digits from English + * https://leetcode.com/problems/reconstruct-original-digits-from-english/ + * Difficulty: Medium + * + * Given a string s containing an out-of-order English representation of digits 0-9, + * return the digits in ascending order. + */ + +/** + * @param {string} s + * @return {string} + */ +var originalDigits = function(s) { + const c = new Array(26).fill(0); + const d = new Array(10).fill(0); + + for (const char of s) c[char.charCodeAt(0) - 97]++; + + [d[0], d[2], d[4], d[6], d[8]] = [c[25], c[22], c[20], c[23], c[6]]; + d[3] = c[7] - d[8]; + d[5] = c[5] - d[4]; + d[7] = c[18] - d[6]; + d[1] = c[14] - d[0] - d[2] - d[4]; + d[9] = (c[13] - d[1] - d[7]) / 2; + + return d.reduce((str, count, i) => str + String(i).repeat(count), ''); +}; diff --git a/README.md b/README.md index e89cda5e..27dfef40 100644 --- a/README.md +++ b/README.md @@ -337,6 +337,7 @@ 419|[Battleships in a Board](./0419-battleships-in-a-board.js)|Medium| 420|[Strong Password Checker](./0420-strong-password-checker.js)|Hard| 421|[Maximum XOR of Two Numbers in an Array](./0421-maximum-xor-of-two-numbers-in-an-array.js)|Medium| +423|[Reconstruct Original Digits from English](./0423-reconstruct-original-digits-from-english.js)|Medium| 434|[Number of Segments in a String](./0434-number-of-segments-in-a-string.js)|Easy| 435|[Non-overlapping Intervals](./0435-non-overlapping-intervals.js)|Medium| 437|[Path Sum III](./0437-path-sum-iii.js)|Medium| From 989530766ae70a77347e30f69de3b770c6fe993e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 26 Feb 2025 01:59:34 -0600 Subject: [PATCH 736/919] Add solution #424 --- ...longest-repeating-character-replacement.js | 32 +++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 0424-longest-repeating-character-replacement.js diff --git a/0424-longest-repeating-character-replacement.js b/0424-longest-repeating-character-replacement.js new file mode 100644 index 00000000..2db1471e --- /dev/null +++ b/0424-longest-repeating-character-replacement.js @@ -0,0 +1,32 @@ +/** + * 424. Longest Repeating Character Replacement + * https://leetcode.com/problems/longest-repeating-character-replacement/ + * Difficulty: Medium + * + * You are given a string s and an integer k. You can choose any character of the string + * and change it to any other uppercase English character. You can perform this operation + * at most k times. + * + * Return the length of the longest substring containing the same letter you can get after + * performing the above operations. + */ + +/** + * @param {string} s + * @param {number} k + * @return {number} + */ +var characterReplacement = function(s, k) { + const count = new Map(); + let max = 0; + let left = 0; + + return s.split('').reduce((maxLength, char, right) => { + count.set(char, (count.get(char) || 0) + 1); + max = Math.max(max, count.get(char)); + if (right - left + 1 - max > k) { + count.set(s[left], count.get(s[left++]) - 1); + } + return Math.max(maxLength, right - left + 1); + }, 0); +}; diff --git a/README.md b/README.md index 27dfef40..6dd7fb9d 100644 --- a/README.md +++ b/README.md @@ -338,6 +338,7 @@ 420|[Strong Password Checker](./0420-strong-password-checker.js)|Hard| 421|[Maximum XOR of Two Numbers in an Array](./0421-maximum-xor-of-two-numbers-in-an-array.js)|Medium| 423|[Reconstruct Original Digits from English](./0423-reconstruct-original-digits-from-english.js)|Medium| +424|[Longest Repeating Character Replacement](./0424-longest-repeating-character-replacement.js)|Medium| 434|[Number of Segments in a String](./0434-number-of-segments-in-a-string.js)|Easy| 435|[Non-overlapping Intervals](./0435-non-overlapping-intervals.js)|Medium| 437|[Path Sum III](./0437-path-sum-iii.js)|Medium| From e160552b978199edc62dc44f0722e008bc455b0f Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 26 Feb 2025 02:01:52 -0600 Subject: [PATCH 737/919] Add solution #427 --- 0427-construct-quad-tree.js | 54 +++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 55 insertions(+) create mode 100644 0427-construct-quad-tree.js diff --git a/0427-construct-quad-tree.js b/0427-construct-quad-tree.js new file mode 100644 index 00000000..5b663392 --- /dev/null +++ b/0427-construct-quad-tree.js @@ -0,0 +1,54 @@ +/** + * 427. Construct Quad Tree + * https://leetcode.com/problems/construct-quad-tree/ + * Difficulty: Medium + * + * Given a n * n matrix grid of 0's and 1's only. We want to represent grid with a Quad-Tree. + * + * Return the root of the Quad-Tree representing grid. + * + * A Quad-Tree is a tree data structure in which each internal node has exactly four children. + * Besides, each node has two attributes: + * - val: True if the node represents a grid of 1's or False if the node represents a grid of + * 0's. Notice that you can assign the val to True or False when isLeaf is False, and both are + * accepted in the answer. + * - isLeaf: True if the node is a leaf node on the tree or False if the node has four children. + */ + +/** + * // Definition for a QuadTree node. + * function _Node(val,isLeaf,topLeft,topRight,bottomLeft,bottomRight) { + * this.val = val; + * this.isLeaf = isLeaf; + * this.topLeft = topLeft; + * this.topRight = topRight; + * this.bottomLeft = bottomLeft; + * this.bottomRight = bottomRight; + * }; + */ + +/** + * @param {number[][]} grid + * @return {_Node} + */ +var construct = function(grid) { + return build(0, 0, grid.length); + + function build(x, y, n) { + const value = grid[x][y]; + for (let i = x; i < x + n; i++) { + for (let j = y; j < y + n; j++) { + if (grid[i][j] !== value) { + n /= 2; + return new _Node(true, false, + build(x, y, n), + build(x, y + n, n), + build(x + n, y, n), + build(x + n, y + n, n) + ); + } + } + } + return new _Node(value === 1, true, null, null, null, null); + } +}; diff --git a/README.md b/README.md index 6dd7fb9d..08ee4ba9 100644 --- a/README.md +++ b/README.md @@ -339,6 +339,7 @@ 421|[Maximum XOR of Two Numbers in an Array](./0421-maximum-xor-of-two-numbers-in-an-array.js)|Medium| 423|[Reconstruct Original Digits from English](./0423-reconstruct-original-digits-from-english.js)|Medium| 424|[Longest Repeating Character Replacement](./0424-longest-repeating-character-replacement.js)|Medium| +427|[Construct Quad Tree](./0427-construct-quad-tree.js)|Medium| 434|[Number of Segments in a String](./0434-number-of-segments-in-a-string.js)|Easy| 435|[Non-overlapping Intervals](./0435-non-overlapping-intervals.js)|Medium| 437|[Path Sum III](./0437-path-sum-iii.js)|Medium| From f5802411c6e77a70cb79a27dc05fbd8ec2a3dbb7 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 27 Feb 2025 16:40:36 -0600 Subject: [PATCH 738/919] Add solution #873 --- ...length-of-longest-fibonacci-subsequence.js | 42 +++++++++++++++++++ README.md | 1 + 2 files changed, 43 insertions(+) create mode 100644 0873-length-of-longest-fibonacci-subsequence.js diff --git a/0873-length-of-longest-fibonacci-subsequence.js b/0873-length-of-longest-fibonacci-subsequence.js new file mode 100644 index 00000000..c2cc48d4 --- /dev/null +++ b/0873-length-of-longest-fibonacci-subsequence.js @@ -0,0 +1,42 @@ +/** + * 873. Length of Longest Fibonacci Subsequence + * https://leetcode.com/problems/length-of-longest-fibonacci-subsequence/ + * Difficulty: Medium + * + * 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]. + */ + +/** + * @param {number[]} arr + * @return {number} + */ +var lenLongestFibSubseq = function(arr) { + const set = new Set(arr); + let max = 0; + + for (let i = 0; i < arr.length; i++) { + for (let j = i + 1; j < arr.length; j++) { + let [x, y, count] = [arr[i], arr[j], 2]; + + while (set.has(x + y)) { + const next = x + y; + x = y; + y = next; + count++; + } + + max = Math.max(max, count); + } + } + + return max >= 3 ? max : 0; +}; diff --git a/README.md b/README.md index 08ee4ba9..96c7e556 100644 --- a/README.md +++ b/README.md @@ -448,6 +448,7 @@ 867|[Transpose Matrix](./0867-transpose-matrix.js)|Easy| 868|[Binary Gap](./0868-binary-gap.js)|Easy| 872|[Leaf-Similar Trees](./0872-leaf-similar-trees.js)|Easy| +873|[Length of Longest Fibonacci Subsequence](./0873-length-of-longest-fibonacci-subsequence.js)|Medium| 875|[Koko Eating Bananas](./0875-koko-eating-bananas.js)|Medium| 876|[Middle of the Linked List](./0876-middle-of-the-linked-list.js)|Easy| 884|[Uncommon Words from Two Sentences](./0884-uncommon-words-from-two-sentences.js)|Easy| From e39bd970ee074e9fe9b039518fe4552945abbc99 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 27 Feb 2025 16:43:26 -0600 Subject: [PATCH 739/919] Add solution #429 --- 0429-n-ary-tree-level-order-traversal.js | 41 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 42 insertions(+) create mode 100644 0429-n-ary-tree-level-order-traversal.js diff --git a/0429-n-ary-tree-level-order-traversal.js b/0429-n-ary-tree-level-order-traversal.js new file mode 100644 index 00000000..956db6c1 --- /dev/null +++ b/0429-n-ary-tree-level-order-traversal.js @@ -0,0 +1,41 @@ +/** + * 429. N-ary Tree Level Order Traversal + * https://leetcode.com/problems/n-ary-tree-level-order-traversal/ + * Difficulty: Medium + * + * Given an n-ary tree, return the level order traversal of its nodes' values. + * + * Nary-Tree input serialization is represented in their level order traversal, each group of + * children is separated by the null value. + */ + +/** + * // Definition for a _Node. + * function _Node(val,children) { + * this.val = val; + * this.children = children; + * }; + */ + +/** + * @param {_Node|null} root + * @return {number[][]} + */ +var levelOrder = function(root) { + if (!root) return []; + + const result = []; + const queue = [root]; + + while (queue.length) { + const [level, current] = [queue.length, []]; + for (let i = 0; i < level; i++) { + const node = queue.shift(); + current.push(node.val); + queue.push(...node.children); + } + result.push(current); + } + + return result; +}; diff --git a/README.md b/README.md index 96c7e556..a90ead70 100644 --- a/README.md +++ b/README.md @@ -340,6 +340,7 @@ 423|[Reconstruct Original Digits from English](./0423-reconstruct-original-digits-from-english.js)|Medium| 424|[Longest Repeating Character Replacement](./0424-longest-repeating-character-replacement.js)|Medium| 427|[Construct Quad Tree](./0427-construct-quad-tree.js)|Medium| +429|[N-ary Tree Level Order Traversal](./0429-n-ary-tree-level-order-traversal.js)|Medium| 434|[Number of Segments in a String](./0434-number-of-segments-in-a-string.js)|Easy| 435|[Non-overlapping Intervals](./0435-non-overlapping-intervals.js)|Medium| 437|[Path Sum III](./0437-path-sum-iii.js)|Medium| From 600b4ac9de18b3f570accb70100da1f900968ee4 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 27 Feb 2025 16:44:51 -0600 Subject: [PATCH 740/919] Add solution #430 --- ...flatten-a-multilevel-doubly-linked-list.js | 61 +++++++++++++++++++ README.md | 1 + 2 files changed, 62 insertions(+) create mode 100644 0430-flatten-a-multilevel-doubly-linked-list.js diff --git a/0430-flatten-a-multilevel-doubly-linked-list.js b/0430-flatten-a-multilevel-doubly-linked-list.js new file mode 100644 index 00000000..e2a95448 --- /dev/null +++ b/0430-flatten-a-multilevel-doubly-linked-list.js @@ -0,0 +1,61 @@ +/** + * 430. Flatten a Multilevel Doubly Linked List + * https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/ + * Difficulty: Medium + * + * You are given a doubly linked list, which contains nodes that have a next pointer, a previous + * pointer, and an additional child pointer. This child pointer may or may not point to a separate + * doubly linked list, also containing these special nodes. These child lists may have one or more + * children of their own, and so on, to produce a multilevel data structure as shown in the example + * below. + * + * Given the head of the first level of the list, flatten the list so that all the nodes appear in + * a single-level, doubly linked list. Let curr be a node with a child list. The nodes in the child + * list should appear after curr and before curr.next in the flattened list. + * + * Return the head of the flattened list. The nodes in the list must have all of their child + * pointers set to null. + */ + +/** + * // Definition for a _Node. + * function _Node(val,prev,next,child) { + * this.val = val; + * this.prev = prev; + * this.next = next; + * this.child = child; + * }; + */ + +/** + * @param {_Node} head + * @return {_Node} + */ +var flatten = function(head) { + if (!head) return null; + + let current = head; + while (current) { + if (!current.child) { + current = current.next; + } else { + const { child, next } = current; + current.child = null; + current.next = child; + child.prev = current; + + let tail = child; + while (tail.next) { + tail = tail.next; + } + + tail.next = next; + if (next) { + next.prev = tail; + } + current = current.next; + } + } + + return head; +}; diff --git a/README.md b/README.md index a90ead70..89e0be93 100644 --- a/README.md +++ b/README.md @@ -341,6 +341,7 @@ 424|[Longest Repeating Character Replacement](./0424-longest-repeating-character-replacement.js)|Medium| 427|[Construct Quad Tree](./0427-construct-quad-tree.js)|Medium| 429|[N-ary Tree Level Order Traversal](./0429-n-ary-tree-level-order-traversal.js)|Medium| +430|[Flatten a Multilevel Doubly Linked List](./0430-flatten-a-multilevel-doubly-linked-list.js)|Medium| 434|[Number of Segments in a String](./0434-number-of-segments-in-a-string.js)|Easy| 435|[Non-overlapping Intervals](./0435-non-overlapping-intervals.js)|Medium| 437|[Path Sum III](./0437-path-sum-iii.js)|Medium| From e450b6543f82ceff9e08ce04fcca9d39aa93037d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 27 Feb 2025 16:46:27 -0600 Subject: [PATCH 741/919] Add solution #432 --- 0432-all-oone-data-structure.js | 99 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 100 insertions(+) create mode 100644 0432-all-oone-data-structure.js diff --git a/0432-all-oone-data-structure.js b/0432-all-oone-data-structure.js new file mode 100644 index 00000000..dfb52ada --- /dev/null +++ b/0432-all-oone-data-structure.js @@ -0,0 +1,99 @@ +/** + * 432. All O`one Data Structure + * https://leetcode.com/problems/all-oone-data-structure/ + * Difficulty: Hard + * + * Design a data structure to store the strings' count with the ability to return the strings + * with minimum and maximum counts. + * + * Implement the AllOne class: + * - AllOne() Initializes the object of the data structure. + * - inc(String key) Increments the count of the string key by 1. If key does not exist in the + * data structure, insert it with count 1. + * - dec(String key) Decrements the count of the string key by 1. If the count of key is 0 after + * the decrement, remove it from the data structure. It is guaranteed that key exists in the + * data structure before the decrement. + * - getMaxKey() Returns one of the keys with the maximal count. If no element exists, return + * an empty string "". + * - getMinKey() Returns one of the keys with the minimum count. If no element exists, return + * an empty string "". + * + * Note that each function must run in O(1) average time complexity. + */ + +var AllOne = function() { + this.map = new Map(); + this.head = { count: 0, keys: new Set(), prev: null, next: null }; + this.tail = { count: Infinity, keys: new Set(), prev: this.head, next: null }; + this.head.next = this.tail; +}; + +/** + * @param {string} key + * @return {void} + */ +AllOne.prototype.inc = function(key) { + const node = this.map.get(key) || this.head; + const count = node.count + 1; + let next = node.next; + + if (next.count !== count) { + next = { count, keys: new Set(), prev: node, next: node.next }; + node.next.prev = next; + node.next = next; + } + + next.keys.add(key); + node.keys.delete(key); + this.map.set(key, next); + + if (node !== this.head && node.keys.size === 0) { + node.prev.next = node.next; + node.next.prev = node.prev; + } +}; + +/** + * @param {string} key + * @return {void} + */ +AllOne.prototype.dec = function(key) { + const node = this.map.get(key); + const count = node.count - 1; + + node.keys.delete(key); + + if (count === 0) { + this.map.delete(key); + } else { + let prev = node.prev; + if (prev.count !== count) { + prev = { count, keys: new Set(), prev: node.prev, next: node }; + node.prev.next = prev; + node.prev = prev; + } + prev.keys.add(key); + this.map.set(key, prev); + } + + if (node.keys.size === 0) { + node.prev.next = node.next; + node.next.prev = node.prev; + } +}; + +/** + * @return {string} + */ +AllOne.prototype.getMaxKey = function() { + const node = this.tail.prev; + return node === this.head ? '' : node.keys.values().next().value; +}; + +/** + * @return {string} + */ +AllOne.prototype.getMinKey = function() { + const node = this.head.next; + return node === this.tail ? '' : node.keys.values().next().value; +}; diff --git a/README.md b/README.md index 89e0be93..acfb0f28 100644 --- a/README.md +++ b/README.md @@ -342,6 +342,7 @@ 427|[Construct Quad Tree](./0427-construct-quad-tree.js)|Medium| 429|[N-ary Tree Level Order Traversal](./0429-n-ary-tree-level-order-traversal.js)|Medium| 430|[Flatten a Multilevel Doubly Linked List](./0430-flatten-a-multilevel-doubly-linked-list.js)|Medium| +432|[All O`one Data Structure](./0432-all-oone-data-structure.js)|Hard| 434|[Number of Segments in a String](./0434-number-of-segments-in-a-string.js)|Easy| 435|[Non-overlapping Intervals](./0435-non-overlapping-intervals.js)|Medium| 437|[Path Sum III](./0437-path-sum-iii.js)|Medium| From 51a3d39fdf8b81eed758306ac56313643d5aa383 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 27 Feb 2025 16:47:23 -0600 Subject: [PATCH 742/919] Add solution #433 --- 0433-minimum-genetic-mutation.js | 57 ++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 58 insertions(+) create mode 100644 0433-minimum-genetic-mutation.js diff --git a/0433-minimum-genetic-mutation.js b/0433-minimum-genetic-mutation.js new file mode 100644 index 00000000..83d42a76 --- /dev/null +++ b/0433-minimum-genetic-mutation.js @@ -0,0 +1,57 @@ +/** + * 433. Minimum Genetic Mutation + * https://leetcode.com/problems/minimum-genetic-mutation/ + * Difficulty: Medium + * + * A gene string can be represented by an 8-character long string, with choices from + * 'A', 'C', 'G', and 'T'. + * + * Suppose we need to investigate a mutation from a gene string startGene to a gene + * string endGene where one mutation is defined as one single character changed in the + * gene string. + * + * For example, "AACCGGTT" --> "AACCGGTA" is one mutation. + * + * There is also a gene bank bank that records all the valid gene mutations. A gene must + * be in bank to make it a valid gene string. + * + * Given the two gene strings startGene and endGene and the gene bank bank, return the + * minimum number of mutations needed to mutate from startGene to endGene. If there is + * no such a mutation, return -1. + * + * Note that the starting point is assumed to be valid, so it might not be included in + * the bank. + */ + +/** + * @param {string} startGene + * @param {string} endGene + * @param {string[]} bank + * @return {number} + */ +var minMutation = function(startGene, endGene, bank) { + const set = new Set(bank); + if (!set.has(endGene)) return -1; + + const queue = [[startGene, 0]]; + const seen = new Set([startGene]); + + while (queue.length) { + const [gene, steps] = queue.shift(); + if (gene === endGene) return steps; + + for (let i = 0; i < 8; i++) { + for (const char of ['A', 'C', 'G', 'T']) { + if (char !== gene[i]) { + const next = gene.slice(0, i) + char + gene.slice(i + 1); + if (set.has(next) && !seen.has(next)) { + queue.push([next, steps + 1]); + seen.add(next); + } + } + } + } + } + + return -1; +}; diff --git a/README.md b/README.md index acfb0f28..5f984924 100644 --- a/README.md +++ b/README.md @@ -343,6 +343,7 @@ 429|[N-ary Tree Level Order Traversal](./0429-n-ary-tree-level-order-traversal.js)|Medium| 430|[Flatten a Multilevel Doubly Linked List](./0430-flatten-a-multilevel-doubly-linked-list.js)|Medium| 432|[All O`one Data Structure](./0432-all-oone-data-structure.js)|Hard| +433|[Minimum Genetic Mutation](./0433-minimum-genetic-mutation.js)|Medium| 434|[Number of Segments in a String](./0434-number-of-segments-in-a-string.js)|Easy| 435|[Non-overlapping Intervals](./0435-non-overlapping-intervals.js)|Medium| 437|[Path Sum III](./0437-path-sum-iii.js)|Medium| From 6d9f18290a9deceed47c1b54bde8204f4a7a06e6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 27 Feb 2025 17:41:36 -0600 Subject: [PATCH 743/919] Add solution #436 --- 0436-find-right-interval.js | 43 +++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 44 insertions(+) create mode 100644 0436-find-right-interval.js diff --git a/0436-find-right-interval.js b/0436-find-right-interval.js new file mode 100644 index 00000000..c891b7c1 --- /dev/null +++ b/0436-find-right-interval.js @@ -0,0 +1,43 @@ +/** + * 436. Find Right Interval + * https://leetcode.com/problems/find-right-interval/ + * Difficulty: Medium + * + * You are given an array of intervals, where intervals[i] = [starti, endi] and each + * starti is unique. + * + * The right interval for an interval i is an interval j such that startj >= endi and + * startj is minimized. Note that i may equal j. + * + * Return an array of right interval indices for each interval i. If no right interval + * exists for interval i, then put -1 at index i. + */ + +/** + * @param {number[][]} intervals + * @return {number[]} + */ +var findRightInterval = function(intervals) { + const lookup = intervals.map(([start], i) => [start, i]) + .sort((a, b) => a[0] - b[0]); + const result = new Array(intervals.length); + + for (let i = 0; i < intervals.length; i++) { + const target = intervals[i][1]; + let left = 0; + let right = lookup.length - 1; + + while (left <= right) { + const middle = Math.floor((left + right) / 2); + if (lookup[middle][0] >= target) { + right = middle - 1; + } else { + left = middle + 1; + } + } + + result[i] = left < lookup.length ? lookup[left][1] : -1; + } + + return result; +}; diff --git a/README.md b/README.md index 5f984924..14c5f63f 100644 --- a/README.md +++ b/README.md @@ -346,6 +346,7 @@ 433|[Minimum Genetic Mutation](./0433-minimum-genetic-mutation.js)|Medium| 434|[Number of Segments in a String](./0434-number-of-segments-in-a-string.js)|Easy| 435|[Non-overlapping Intervals](./0435-non-overlapping-intervals.js)|Medium| +436|[Find Right Interval](./0436-find-right-interval.js)|Medium| 437|[Path Sum III](./0437-path-sum-iii.js)|Medium| 438|[Find All Anagrams in a String](./0438-find-all-anagrams-in-a-string.js)|Medium| 441|[Arranging Coins](./0441-arranging-coins.js)|Easy| From 99f959d4c51cfbb9f581860284641e2d148beb65 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 27 Feb 2025 17:42:04 -0600 Subject: [PATCH 744/919] Add solution #440 --- ...-k-th-smallest-in-lexicographical-order.js | 35 +++++++++++++++++++ README.md | 1 + 2 files changed, 36 insertions(+) create mode 100644 0440-k-th-smallest-in-lexicographical-order.js diff --git a/0440-k-th-smallest-in-lexicographical-order.js b/0440-k-th-smallest-in-lexicographical-order.js new file mode 100644 index 00000000..87cfe5ac --- /dev/null +++ b/0440-k-th-smallest-in-lexicographical-order.js @@ -0,0 +1,35 @@ +/** + * 440. K-th Smallest in Lexicographical Order + * https://leetcode.com/problems/k-th-smallest-in-lexicographical-order/ + * Difficulty: Hard + * + * Given two integers n and k, return the kth lexicographically smallest integer in + * the range [1, n]. + */ + +/** + * @param {number} n + * @param {number} k + * @return {number} + */ +var findKthNumber = function(n, k) { + let result = 1; + k--; + + while (k > 0) { + let count = 0; + for (let first = result, last = result + 1; first <= n; first *= 10, last *= 10) { + count += Math.min(n + 1, last) - first; + } + + if (count <= k) { + result++; + k -= count; + } else { + result *= 10; + k--; + } + } + + return result; +}; diff --git a/README.md b/README.md index 14c5f63f..917d4f55 100644 --- a/README.md +++ b/README.md @@ -349,6 +349,7 @@ 436|[Find Right Interval](./0436-find-right-interval.js)|Medium| 437|[Path Sum III](./0437-path-sum-iii.js)|Medium| 438|[Find All Anagrams in a String](./0438-find-all-anagrams-in-a-string.js)|Medium| +440|[K-th Smallest in Lexicographical Order](./0440-k-th-smallest-in-lexicographical-order.js)|Hard| 441|[Arranging Coins](./0441-arranging-coins.js)|Easy| 442|[Find All Duplicates in an Array](./0442-find-all-duplicates-in-an-array.js)|Medium| 443|[String Compression](./0443-string-compression.js)|Medium| From 1aa61838830c0972b47fbbc72806a6dd0f08c849 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 27 Feb 2025 17:42:48 -0600 Subject: [PATCH 745/919] Add solution #445 --- 0445-add-two-numbers-ii.js | 48 ++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 49 insertions(+) create mode 100644 0445-add-two-numbers-ii.js diff --git a/0445-add-two-numbers-ii.js b/0445-add-two-numbers-ii.js new file mode 100644 index 00000000..ce0cb33f --- /dev/null +++ b/0445-add-two-numbers-ii.js @@ -0,0 +1,48 @@ +/** + * 445. Add Two Numbers II + * https://leetcode.com/problems/add-two-numbers-ii/ + * Difficulty: Medium + * + * You are given two non-empty linked lists representing two non-negative integers. The most + * significant digit comes first and each of their nodes contains a single digit. Add the two + * numbers and return the sum as a linked list. + * + * You may assume the two numbers do not contain any leading zero, except the number 0 itself. + */ + +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} l1 + * @param {ListNode} l2 + * @return {ListNode} + */ +var addTwoNumbers = function(l1, l2) { + const s1 = []; + const s2 = []; + let carry = 0; + let head = null; + + while (l1) { + s1.push(l1.val); + l1 = l1.next; + } + + while (l2) { + s2.push(l2.val); + l2 = l2.next; + } + + while (s1.length || s2.length || carry) { + const sum = (s1.pop() || 0) + (s2.pop() || 0) + carry; + carry = sum / 10 | 0; + head = Object.assign(new ListNode(sum % 10), { next: head }); + } + + return head; +}; diff --git a/README.md b/README.md index 917d4f55..8bf2a339 100644 --- a/README.md +++ b/README.md @@ -353,6 +353,7 @@ 441|[Arranging Coins](./0441-arranging-coins.js)|Easy| 442|[Find All Duplicates in an Array](./0442-find-all-duplicates-in-an-array.js)|Medium| 443|[String Compression](./0443-string-compression.js)|Medium| +445|[Add Two Numbers II](./0445-add-two-numbers-ii.js)|Medium| 448|[Find All Numbers Disappeared in an Array](./0448-find-all-numbers-disappeared-in-an-array.js)|Easy| 450|[Delete Node in a BST](./0450-delete-node-in-a-bst.js)|Medium| 451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| From e32b51c16a3a4f9546ab14589eb243ff6844f123 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 27 Feb 2025 17:43:36 -0600 Subject: [PATCH 746/919] Add solution #446 --- 0446-arithmetic-slices-ii-subsequence.js | 41 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 42 insertions(+) create mode 100644 0446-arithmetic-slices-ii-subsequence.js diff --git a/0446-arithmetic-slices-ii-subsequence.js b/0446-arithmetic-slices-ii-subsequence.js new file mode 100644 index 00000000..e2292526 --- /dev/null +++ b/0446-arithmetic-slices-ii-subsequence.js @@ -0,0 +1,41 @@ +/** + * 446. Arithmetic Slices II - Subsequence + * https://leetcode.com/problems/arithmetic-slices-ii-subsequence/ + * Difficulty: Hard + * + * Given an integer array nums, return the number of all the arithmetic subsequences of nums. + * + * A sequence of numbers is called arithmetic if it consists of at least three elements and if + * the difference between any two consecutive elements is the same. + * + * - For example, [1, 3, 5, 7, 9], [7, 7, 7, 7], and [3, -1, -5, -9] are arithmetic sequences. + * - For example, [1, 1, 2, 5, 7] is not an arithmetic sequence. + * + * A subsequence of an array is a sequence that can be formed by removing some elements (possibly + * none) of the array. + * + * - For example, [2,5,10] is a subsequence of [1,2,1,2,4,1,5,10]. + * + * The test cases are generated so that the answer fits in 32-bit integer. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var numberOfArithmeticSlices = function(nums) { + const dp = new Array(nums.length).fill().map(() => new Map()); + let result = 0; + + for (let i = 1; i < nums.length; i++) { + for (let j = 0; j < i; j++) { + const diff = nums[i] - nums[j]; + const prev = dp[j].get(diff) || 0; + const current = (dp[i].get(diff) || 0) + prev + 1; + dp[i].set(diff, current); + result += prev; + } + } + + return result; +}; diff --git a/README.md b/README.md index 8bf2a339..01441738 100644 --- a/README.md +++ b/README.md @@ -354,6 +354,7 @@ 442|[Find All Duplicates in an Array](./0442-find-all-duplicates-in-an-array.js)|Medium| 443|[String Compression](./0443-string-compression.js)|Medium| 445|[Add Two Numbers II](./0445-add-two-numbers-ii.js)|Medium| +446|[Arithmetic Slices II - Subsequence](./0446-arithmetic-slices-ii-subsequence.js)|Hard| 448|[Find All Numbers Disappeared in an Array](./0448-find-all-numbers-disappeared-in-an-array.js)|Easy| 450|[Delete Node in a BST](./0450-delete-node-in-a-bst.js)|Medium| 451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| From cc892896c62256cf98bb28e174237dfcbb087205 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 27 Feb 2025 17:44:07 -0600 Subject: [PATCH 747/919] Add solution #447 --- 0447-number-of-boomerangs.js | 33 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 0447-number-of-boomerangs.js diff --git a/0447-number-of-boomerangs.js b/0447-number-of-boomerangs.js new file mode 100644 index 00000000..20156e9f --- /dev/null +++ b/0447-number-of-boomerangs.js @@ -0,0 +1,33 @@ +/** + * 447. Number of Boomerangs + * https://leetcode.com/problems/number-of-boomerangs/ + * Difficulty: Medium + * + * You are given n points in the plane that are all distinct, where points[i] = [xi, yi]. + * A boomerang is a tuple of points (i, j, k) such that the distance between i and j equals + * the distance between i and k (the order of the tuple matters). + * + * Return the number of boomerangs. + */ + +/** + * @param {number[][]} points + * @return {number} + */ +var numberOfBoomerangs = function(points) { + let count = 0; + + for (let i = 0; i < points.length; i++) { + const distances = new Map(); + for (let j = 0; j < points.length; j++) { + if (i === j) continue; + const d = (points[i][0] - points[j][0]) ** 2 + (points[i][1] - points[j][1]) ** 2; + distances.set(d, (distances.get(d) || 0) + 1); + } + for (const d of distances.values()) { + if (d > 1) count += d * (d - 1); + } + } + + return count; +}; diff --git a/README.md b/README.md index 01441738..8b633e9d 100644 --- a/README.md +++ b/README.md @@ -355,6 +355,7 @@ 443|[String Compression](./0443-string-compression.js)|Medium| 445|[Add Two Numbers II](./0445-add-two-numbers-ii.js)|Medium| 446|[Arithmetic Slices II - Subsequence](./0446-arithmetic-slices-ii-subsequence.js)|Hard| +447|[Number of Boomerangs](./0447-number-of-boomerangs.js)|Medium| 448|[Find All Numbers Disappeared in an Array](./0448-find-all-numbers-disappeared-in-an-array.js)|Easy| 450|[Delete Node in a BST](./0450-delete-node-in-a-bst.js)|Medium| 451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| From 697a0f59a2d3cefac09472b3fc400a8219c24f0c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 27 Feb 2025 17:50:52 -0600 Subject: [PATCH 748/919] Add solution #290 --- 0290-word-pattern.js | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/0290-word-pattern.js b/0290-word-pattern.js index 293062d4..34bd7732 100644 --- a/0290-word-pattern.js +++ b/0290-word-pattern.js @@ -5,8 +5,11 @@ * * Given a pattern and a string s, find if s follows the same pattern. * - * Here follow means a full match, such that there is a bijection between - * a letter in pattern and a non-empty word in s. + * Here follow means a full match, such that there is a bijection between a letter in + * pattern and a non-empty word in s. Specifically: + * - Each letter in pattern maps to exactly one unique word in s. + * - Each unique word in s maps to exactly one letter in pattern. + * - No two letters map to the same word, and no two words map to the same letter. */ /** @@ -15,15 +18,12 @@ * @return {boolean} */ var wordPattern = function(pattern, s) { - const words = s.split(/\s+/); + const words = s.split(' '); + if (pattern.length !== words.length) return false; const map = new Map(); - - return words.every((word, index) => { - const offset = pattern.length === words.length ? index + 1 : words.length / pattern.length; - const sequence = pattern.slice(index, offset); - if (!map.has(sequence) && !Array.from(map.values()).includes(word)) { - map.set(sequence, word); - } - return map.get(sequence) === word && pattern.length <= words.length; - }); + return pattern.split('').every((char, i) => + map.has(char) + ? map.get(char) === words[i] + : !([...map.values()].includes(words[i])) && map.set(char, words[i]) + ); }; From fb1533b3b7fe7bd3b7ea2e43b1517bc1dd3eb2fa Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 28 Feb 2025 01:10:13 -0600 Subject: [PATCH 749/919] Add solution #1092 --- 1092-shortest-common-supersequence.js | 50 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 51 insertions(+) create mode 100644 1092-shortest-common-supersequence.js diff --git a/1092-shortest-common-supersequence.js b/1092-shortest-common-supersequence.js new file mode 100644 index 00000000..7a09b1c0 --- /dev/null +++ b/1092-shortest-common-supersequence.js @@ -0,0 +1,50 @@ +/** + * 1092. Shortest Common Supersequence + * https://leetcode.com/problems/shortest-common-supersequence/ + * Difficulty: Hard + * + * Given two strings str1 and str2, return the shortest string that has both str1 and str2 as + * subsequences. If there are multiple valid strings, return any of them. + * + * A string s is a subsequence of string t if deleting some number of characters from t (possibly + * 0) results in the string s. + */ + +/** + * @param {string} str1 + * @param {string} str2 + * @return {string} + */ +var shortestCommonSupersequence = function(str1, str2) { + const dp = new Array(str1.length + 1).fill().map(() => new Array(str2.length + 1).fill(0)); + let result = ''; + + for (let i = 0; i <= str1.length; i++) { + dp[i][0] = i; + } + for (let j = 0; j <= str2.length; j++) { + dp[0][j] = j; + } + + for (let i = 1; i <= str1.length; i++) { + for (let j = 1; j <= str2.length; j++) { + dp[i][j] = str1[i-1] === str2[j-1] ? dp[i-1][j-1] + 1 : Math.min(dp[i-1][j], dp[i][j-1]) + 1; + } + } + + for (let i = str1.length, j = str2.length; i > 0 || j > 0;) { + if (!i) { + result = str2[--j] + result; + } else if (!j) { + result = str1[--i] + result; + } else if (str1[i-1] === str2[j-1]) { + result = str1[--i] + (str2[--j], result); + } else { + dp[i][j] === dp[i-1][j] + 1 + ? result = str1[--i] + result + : result = str2[--j] + result; + } + } + + return result; +}; diff --git a/README.md b/README.md index 8b633e9d..079d1c5c 100644 --- a/README.md +++ b/README.md @@ -497,6 +497,7 @@ 1071|[Greatest Common Divisor of Strings](./1071-greatest-common-divisor-of-strings.js)|Easy| 1079|[Letter Tile Possibilities](./1079-letter-tile-possibilities.js)|Medium| 1081|[Smallest Subsequence of Distinct Characters](./1081-smallest-subsequence-of-distinct-characters.js)|Medium| +1092|[Shortest Common Supersequence](./1092-shortest-common-supersequence.js)|Hard| 1103|[Distribute Candies to People](./1103-distribute-candies-to-people.js)|Easy| 1108|[Defanging an IP Address](./1108-defanging-an-ip-address.js)|Easy| 1122|[Relative Sort Array](./1122-relative-sort-array.js)|Easy| From 36e5e8be6828babfba7017f4436134a2c0d4ff6a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 28 Feb 2025 01:11:30 -0600 Subject: [PATCH 750/919] Add solution #449 --- 0449-serialize-and-deserialize-bst.js | 66 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 67 insertions(+) create mode 100644 0449-serialize-and-deserialize-bst.js diff --git a/0449-serialize-and-deserialize-bst.js b/0449-serialize-and-deserialize-bst.js new file mode 100644 index 00000000..ba794e66 --- /dev/null +++ b/0449-serialize-and-deserialize-bst.js @@ -0,0 +1,66 @@ +/** + * 449. Serialize and Deserialize BST + * https://leetcode.com/problems/serialize-and-deserialize-bst/ + * Difficulty: Medium + * + * Serialization is converting a data structure or object into a sequence of bits so that it + * can be stored in a file or memory buffer, or transmitted across a network connection link + * to be reconstructed later in the same or another computer environment. + * + * Design an algorithm to serialize and deserialize a binary search tree. There is no restriction + * on how your serialization/deserialization algorithm should work. You need to ensure that a + * binary search tree can be serialized to a string, and this string can be deserialized to the + * original tree structure. + * + * The encoded string should be as compact as possible. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ + +/** + * Encodes a tree to a single string. + * + * @param {TreeNode} root + * @return {string} + */ +var serialize = function(root) { + if (!root) return ''; + + const result = []; + preorder(root); + return result.join(','); + + function preorder(node) { + if (!node) return; + result.push(node.val); + preorder(node.left); + preorder(node.right); + } +}; + +/** + * Decodes your encoded data to tree. + * + * @param {string} data + * @return {TreeNode} + */ +var deserialize = function(data) { + if (!data) return null; + + return buildBST(data.split(',').map(Number), 0, Infinity); + + function buildBST(input, min, max) { + if (!input.length || input[0] < min || input[0] > max) return null; + const val = input.shift(); + const root = new TreeNode(val); + root.left = buildBST(input, min, val); + root.right = buildBST(input, val, max); + return root; + } +}; diff --git a/README.md b/README.md index 079d1c5c..bb09a80f 100644 --- a/README.md +++ b/README.md @@ -357,6 +357,7 @@ 446|[Arithmetic Slices II - Subsequence](./0446-arithmetic-slices-ii-subsequence.js)|Hard| 447|[Number of Boomerangs](./0447-number-of-boomerangs.js)|Medium| 448|[Find All Numbers Disappeared in an Array](./0448-find-all-numbers-disappeared-in-an-array.js)|Easy| +449|[Serialize and Deserialize BST](./0449-serialize-and-deserialize-bst.js)|Medium| 450|[Delete Node in a BST](./0450-delete-node-in-a-bst.js)|Medium| 451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| 452|[Minimum Number of Arrows to Burst Balloons](./0452-minimum-number-of-arrows-to-burst-balloons.js)|Medium| From f98fc0ad36980035f5493554b6caf27f01c1efc0 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 28 Feb 2025 01:11:59 -0600 Subject: [PATCH 751/919] Add solution #453 --- 0453-minimum-moves-to-equal-array-elements.js | 19 +++++++++++++++++++ README.md | 1 + 2 files changed, 20 insertions(+) create mode 100644 0453-minimum-moves-to-equal-array-elements.js diff --git a/0453-minimum-moves-to-equal-array-elements.js b/0453-minimum-moves-to-equal-array-elements.js new file mode 100644 index 00000000..174e284c --- /dev/null +++ b/0453-minimum-moves-to-equal-array-elements.js @@ -0,0 +1,19 @@ +/** + * 453. Minimum Moves to Equal Array Elements + * https://leetcode.com/problems/minimum-moves-to-equal-array-elements/ + * Difficulty: Medium + * + * Given an integer array nums of size n, return the minimum number of moves required to + * make all array elements equal. + * + * In one move, you can increment n - 1 elements of the array by 1. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var minMoves = function(nums) { + const min = Math.min(...nums); + return nums.reduce((sum, num) => sum + num - min, 0); +}; diff --git a/README.md b/README.md index bb09a80f..6f419f80 100644 --- a/README.md +++ b/README.md @@ -361,6 +361,7 @@ 450|[Delete Node in a BST](./0450-delete-node-in-a-bst.js)|Medium| 451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium| 452|[Minimum Number of Arrows to Burst Balloons](./0452-minimum-number-of-arrows-to-burst-balloons.js)|Medium| +453|[Minimum Moves to Equal Array Elements](./0453-minimum-moves-to-equal-array-elements.js)|Medium| 454|[4Sum II](./0454-4sum-ii.js)|Medium| 456|[132 Pattern](./0456-132-pattern.js)|Medium| 459|[Repeated Substring Pattern](./0459-repeated-substring-pattern.js)|Easy| From 5463f6d212c4a1c6969056d5dd1491b9c69b2734 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 28 Feb 2025 01:12:39 -0600 Subject: [PATCH 752/919] Add solution #455 --- 0455-assign-cookies.js | 32 ++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 0455-assign-cookies.js diff --git a/0455-assign-cookies.js b/0455-assign-cookies.js new file mode 100644 index 00000000..54f3386b --- /dev/null +++ b/0455-assign-cookies.js @@ -0,0 +1,32 @@ +/** + * 455. Assign Cookies + * https://leetcode.com/problems/assign-cookies/ + * Difficulty: Easy + * + * Assume you are an awesome parent and want to give your children some cookies. But, you + * should give each child at most one cookie. + * + * Each child i has a greed factor g[i], which is the minimum size of a cookie that the + * child will be content with; and each cookie j has a size s[j]. If s[j] >= g[i], we can + * assign the cookie j to the child i, and the child i will be content. Your goal is to + * maximize the number of your content children and output the maximum number. + */ + +/** + * @param {number[]} g + * @param {number[]} s + * @return {number} + */ +var findContentChildren = function(g, s) { + g.sort((a, b) => a - b); + s.sort((a, b) => a - b); + + let result = 0; + for (let j = 0; result < g.length && j < s.length; j++) { + if (s[j] >= g[result]) { + result++; + } + } + + return result; +}; diff --git a/README.md b/README.md index 6f419f80..d0db0960 100644 --- a/README.md +++ b/README.md @@ -363,6 +363,7 @@ 452|[Minimum Number of Arrows to Burst Balloons](./0452-minimum-number-of-arrows-to-burst-balloons.js)|Medium| 453|[Minimum Moves to Equal Array Elements](./0453-minimum-moves-to-equal-array-elements.js)|Medium| 454|[4Sum II](./0454-4sum-ii.js)|Medium| +455|[Assign Cookies](./0455-assign-cookies.js)|Easy| 456|[132 Pattern](./0456-132-pattern.js)|Medium| 459|[Repeated Substring Pattern](./0459-repeated-substring-pattern.js)|Easy| 461|[Hamming Distance](./0461-hamming-distance.js)|Easy| From cf03b41956c566440a49a71f32e2ef9051b91d68 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 28 Feb 2025 01:14:31 -0600 Subject: [PATCH 753/919] Add solution #457 --- 0457-circular-array-loop.js | 47 +++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 48 insertions(+) create mode 100644 0457-circular-array-loop.js diff --git a/0457-circular-array-loop.js b/0457-circular-array-loop.js new file mode 100644 index 00000000..801580a8 --- /dev/null +++ b/0457-circular-array-loop.js @@ -0,0 +1,47 @@ +/** + * 457. Circular Array Loop + * https://leetcode.com/problems/circular-array-loop/ + * Difficulty: Medium + * + * You are playing a game involving a circular array of non-zero integers nums. Each nums[i] + * denotes the number of indices forward/backward you must move if you are located at index i: + * - If nums[i] is positive, move nums[i] steps forward, and + * - If nums[i] is negative, move nums[i] steps backward. + * + * Since the array is circular, you may assume that moving forward from the last element puts + * you on the first element, and moving backwards from the first element puts you on the last + * element. + * + * A cycle in the array consists of a sequence of indices seq of length k where: + * - Following the movement rules above results in the repeating index sequence seq[0] -> seq[1] + * -> ... -> seq[k - 1] -> seq[0] -> ... + * - Every nums[seq[j]] is either all positive or all negative. + * - k > 1 + * + * Return true if there is a cycle in nums, or false otherwise. + */ + +/** + * @param {number[]} nums + * @return {boolean} + */ +var circularArrayLoop = function(nums) { + const n = nums.length; + + for (let i = 0; i < n; i++) { + if (dfs(i, i, nums[i] > 0)) return true; + } + + return false; + + function dfs(current, prev, flag) { + if (nums[current] === 0) return current != prev; + if (flag != (nums[current] > 0)) return false; + const moves = nums[current]; + nums[current] = 0; + const next = (current + (moves % n) + n) % n; + const result = dfs(next, current, flag); + nums[current] = moves; + return result; + } +}; diff --git a/README.md b/README.md index d0db0960..5396b58e 100644 --- a/README.md +++ b/README.md @@ -365,6 +365,7 @@ 454|[4Sum II](./0454-4sum-ii.js)|Medium| 455|[Assign Cookies](./0455-assign-cookies.js)|Easy| 456|[132 Pattern](./0456-132-pattern.js)|Medium| +457|[Circular Array Loop](./0457-circular-array-loop.js)|Medium| 459|[Repeated Substring Pattern](./0459-repeated-substring-pattern.js)|Easy| 461|[Hamming Distance](./0461-hamming-distance.js)|Easy| 463|[Island Perimeter](./0463-island-perimeter.js)|Medium| From 3d0a19ea135dd1040fdbdedd62039aebb4b2af6a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 1 Mar 2025 17:05:39 -0600 Subject: [PATCH 754/919] Add solution #2460 --- 2460-apply-operations-to-an-array.js | 33 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 2460-apply-operations-to-an-array.js diff --git a/2460-apply-operations-to-an-array.js b/2460-apply-operations-to-an-array.js new file mode 100644 index 00000000..daf93479 --- /dev/null +++ b/2460-apply-operations-to-an-array.js @@ -0,0 +1,33 @@ +/** + * 2460. Apply Operations to an Array + * https://leetcode.com/problems/apply-operations-to-an-array/ + * Difficulty: Easy + * + * You are given a 0-indexed array nums of size n consisting of non-negative integers. + * + * You need to apply n - 1 operations to this array where, in the ith operation (0-indexed), + * you will apply the following on the ith element of nums: + * - If nums[i] == nums[i + 1], then multiply nums[i] by 2 and set nums[i + 1] to 0. + * Otherwise, you skip this operation. + * + * After performing all the operations, shift all the 0's to the end of the array. + * - For example, the array [1,0,2,0,0,1] after shifting all its 0's to the end, is [1,2,1,0,0,0]. + * + * Return the resulting array. + * + * Note that the operations are applied sequentially, not all at once. + */ + +/** + * @param {number[]} nums + * @return {number[]} + */ +var applyOperations = function(nums) { + for (let i = 0; i < nums.length - 1; i++) { + if (nums[i] === nums[i + 1]) { + nums[i] *= 2; + nums[i + 1] = 0; + } + } + return [...nums.filter(n => n), ...nums.filter(n => !n)]; +}; diff --git a/README.md b/README.md index 5396b58e..276ff351 100644 --- a/README.md +++ b/README.md @@ -662,6 +662,7 @@ 2425|[Bitwise XOR of All Pairings](./2425-bitwise-xor-of-all-pairings.js)|Medium| 2427|[Number of Common Factors](./2427-number-of-common-factors.js)|Easy| 2429|[Minimize XOR](./2429-minimize-xor.js)|Medium| +2460|[Apply Operations to an Array](./2460-apply-operations-to-an-array.js)|Easy| 2462|[Total Cost to Hire K Workers](./2462-total-cost-to-hire-k-workers.js)|Medium| 2467|[Most Profitable Path in a Tree](./2467-most-profitable-path-in-a-tree.js)|Medium| 2469|[Convert the Temperature](./2469-convert-the-temperature.js)|Easy| From d468998def13ab75f21c4c9969c0d9952c03f8ef Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 1 Mar 2025 17:06:48 -0600 Subject: [PATCH 755/919] Add solution #1930 --- ...nique-length-3-palindromic-subsequences.js | 38 +++++++++++++++++++ README.md | 1 + 2 files changed, 39 insertions(+) create mode 100644 1930-unique-length-3-palindromic-subsequences.js diff --git a/1930-unique-length-3-palindromic-subsequences.js b/1930-unique-length-3-palindromic-subsequences.js new file mode 100644 index 00000000..538d69b5 --- /dev/null +++ b/1930-unique-length-3-palindromic-subsequences.js @@ -0,0 +1,38 @@ +/** + * 1930. Unique Length-3 Palindromic Subsequences + * https://leetcode.com/problems/unique-length-3-palindromic-subsequences/ + * Difficulty: Medium + * + * Given a string s, return the number of unique palindromes of length three that are a + * subsequence of s. + * + * Note that even if there are multiple ways to obtain the same subsequence, it is still + * only counted once. + * + * A palindrome is a string that reads the same forwards and backwards. + * + * A subsequence of a string is a new string generated from the original string with some + * characters (can be none) deleted without changing the relative order of the remaining + * characters. + * + * For example, "ace" is a subsequence of "abcde". + */ + +/** + * @param {string} s + * @return {number} + */ +var countPalindromicSubsequence = function(s) { + let result = 0; + + for (let i = 0; i < 26; ++i) { + const char = String.fromCharCode(i + 97); + const left = s.indexOf(char); + const right = s.lastIndexOf(char); + if (left !== -1 && right !== -1 && left < right) { + result += new Set(s.substring(left + 1, right)).size; + } + } + + return result; +}; diff --git a/README.md b/README.md index 276ff351..2455ff4f 100644 --- a/README.md +++ b/README.md @@ -623,6 +623,7 @@ 1920|[Build Array from Permutation](./1920-build-array-from-permutation.js)|Easy| 1926|[Nearest Exit from Entrance in Maze](./1926-nearest-exit-from-entrance-in-maze.js)|Medium| 1929|[Concatenation of Array](./1929-concatenation-of-array.js)|Easy| +1930|[Unique Length-3 Palindromic Subsequences](./1930-unique-length-3-palindromic-subsequences.js)|Medium| 1935|[Maximum Number of Words You Can Type](./1935-maximum-number-of-words-you-can-type.js)|Easy| 1980|[Find Unique Binary String](./1980-find-unique-binary-string.js)|Medium| 1985|[Find the Kth Largest Integer in the Array](./1985-find-the-kth-largest-integer-in-the-array.js)|Medium| From 298768ed9eff70483060f661a4d697cee869c3bd Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 1 Mar 2025 17:08:43 -0600 Subject: [PATCH 756/919] Add solution #458 --- 0458-poor-pigs.js | 40 ++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 41 insertions(+) create mode 100644 0458-poor-pigs.js diff --git a/0458-poor-pigs.js b/0458-poor-pigs.js new file mode 100644 index 00000000..5aceeb21 --- /dev/null +++ b/0458-poor-pigs.js @@ -0,0 +1,40 @@ +/** + * 458. Poor Pigs + * https://leetcode.com/problems/poor-pigs/ + * Difficulty: Hard + * + * There are buckets buckets of liquid, where exactly one of the buckets is poisonous. To figure + * out which one is poisonous, you feed some number of (poor) pigs the liquid to see whether + * they will die or not. Unfortunately, you only have minutesToTest minutes to determine which + * bucket is poisonous. + * + * You can feed the pigs according to these steps: + * 1. Choose some live pigs to feed. + * 2. For each pig, choose which buckets to feed it. The pig will consume all the chosen buckets + * simultaneously and will take no time. Each pig can feed from any number of buckets, and each + * bucket can be fed from by any number of pigs. + * 3. Wait for minutesToDie minutes. You may not feed any other pigs during this time. + * 4. After minutesToDie minutes have passed, any pigs that have been fed the poisonous bucket + * will die, and all others will survive. + * 5. Repeat this process until you run out of time. + * + * Given buckets, minutesToDie, and minutesToTest, return the minimum number of pigs needed to + * figure out which bucket is poisonous within the allotted time. + */ + +/** + * @param {number} buckets + * @param {number} minutesToDie + * @param {number} minutesToTest + * @return {number} + */ +var poorPigs = function(buckets, minutesToDie, minutesToTest) { + const max = Math.floor(minutesToTest / minutesToDie) + 1; + let result = 0; + + while (Math.pow(max, result) < buckets) { + result++; + } + + return result; +}; diff --git a/README.md b/README.md index 2455ff4f..eeef9180 100644 --- a/README.md +++ b/README.md @@ -366,6 +366,7 @@ 455|[Assign Cookies](./0455-assign-cookies.js)|Easy| 456|[132 Pattern](./0456-132-pattern.js)|Medium| 457|[Circular Array Loop](./0457-circular-array-loop.js)|Medium| +458|[Poor Pigs](./0458-poor-pigs.js)|Hard| 459|[Repeated Substring Pattern](./0459-repeated-substring-pattern.js)|Easy| 461|[Hamming Distance](./0461-hamming-distance.js)|Easy| 463|[Island Perimeter](./0463-island-perimeter.js)|Medium| From b0143d6b48580170a576550db22be23612367c2e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 1 Mar 2025 17:11:20 -0600 Subject: [PATCH 757/919] Add solution #460 --- 0460-lfu-cache.js | 93 +++++++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 94 insertions(+) create mode 100644 0460-lfu-cache.js diff --git a/0460-lfu-cache.js b/0460-lfu-cache.js new file mode 100644 index 00000000..87a50d53 --- /dev/null +++ b/0460-lfu-cache.js @@ -0,0 +1,93 @@ +/** + * 460. LFU Cache + * https://leetcode.com/problems/lfu-cache/ + * Difficulty: Hard + * + * Design and implement a data structure for a Least Frequently Used (LFU) cache. + * + * Implement the LFUCache class: + * - LFUCache(int capacity) Initializes the object with the capacity of the data structure. + * - int get(int key) Gets the value of the key if the key exists in the cache. Otherwise, + * returns -1. + * - void put(int key, int value) Update the value of the key if present, or inserts the + * key if not already present. When the cache reaches its capacity, it should invalidate + * and remove the least frequently used key before inserting a new item. For this problem, + * when there is a tie (i.e., two or more keys with the same frequency), the least recently + * used key would be invalidated. + * + * To determine the least frequently used key, a use counter is maintained for each key in + * the cache. The key with the smallest use counter is the least frequently used key. + * + * When a key is first inserted into the cache, its use counter is set to 1 (due to the + * put operation). The use counter for a key in the cache is incremented either a get or + * put operation is called on it. + * + * The functions get and put must each run in O(1) average time complexity. + */ + +/** + * @param {number} capacity + */ +var LFUCache = function(capacity) { + this.capacity = capacity; + this.size = 0; + this.minFreq = 0; + this.values = new Map(); + this.freq = new Map(); + this.keys = new Map(); +}; + +/** + * @param {number} key + * @return {number} + */ +LFUCache.prototype.get = function(key) { + if (!this.values.has(key)) return -1; + + const freq = this.freq.get(key); + this.freq.set(key, freq + 1); + + this.keys.get(freq).delete(key); + if (!this.keys.get(freq).size) { + this.keys.delete(freq); + if (this.minFreq === freq) this.minFreq++; + } + + if (!this.keys.has(freq + 1)) this.keys.set(freq + 1, new Set()); + this.keys.get(freq + 1).add(key); + + return this.values.get(key); +}; + +/** + * @param {number} key + * @param {number} value + * @return {void} + */ +LFUCache.prototype.put = function(key, value) { + if (this.capacity === 0) return; + + if (this.values.has(key)) { + this.values.set(key, value); + this.get(key); + return; + } + + if (this.size === this.capacity) { + const keyToRemove = this.keys.get(this.minFreq).values().next().value; + this.keys.get(this.minFreq).delete(keyToRemove); + if (!this.keys.get(this.minFreq).size) { + this.keys.delete(this.minFreq); + } + this.values.delete(keyToRemove); + this.freq.delete(keyToRemove); + this.size--; + } + + this.values.set(key, value); + this.freq.set(key, 1); + if (!this.keys.has(1)) this.keys.set(1, new Set()); + this.keys.get(1).add(key); + this.minFreq = 1; + this.size++; +}; diff --git a/README.md b/README.md index eeef9180..a474a5d6 100644 --- a/README.md +++ b/README.md @@ -368,6 +368,7 @@ 457|[Circular Array Loop](./0457-circular-array-loop.js)|Medium| 458|[Poor Pigs](./0458-poor-pigs.js)|Hard| 459|[Repeated Substring Pattern](./0459-repeated-substring-pattern.js)|Easy| +460|[LFU Cache](./0460-lfu-cache.js)|Hard| 461|[Hamming Distance](./0461-hamming-distance.js)|Easy| 463|[Island Perimeter](./0463-island-perimeter.js)|Medium| 472|[Concatenated Words](./0472-concatenated-words.js)|Hard| From bef0d7acbe963fa51ad2c831fe6b2c5134a18cfb Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 1 Mar 2025 17:11:56 -0600 Subject: [PATCH 758/919] Add solution #462 --- ...inimum-moves-to-equal-array-elements-ii.js | 22 +++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 0462-minimum-moves-to-equal-array-elements-ii.js diff --git a/0462-minimum-moves-to-equal-array-elements-ii.js b/0462-minimum-moves-to-equal-array-elements-ii.js new file mode 100644 index 00000000..53cdc8a8 --- /dev/null +++ b/0462-minimum-moves-to-equal-array-elements-ii.js @@ -0,0 +1,22 @@ +/** + * 462. Minimum Moves to Equal Array Elements II + * https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/ + * Difficulty: Medium + * + * Given an integer array nums of size n, return the minimum number of moves + * required to make all array elements equal. + * + * In one move, you can increment or decrement an element of the array by 1. + * + * Test cases are designed so that the answer will fit in a 32-bit integer. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var minMoves2 = function(nums) { + nums.sort((a, b) => a - b); + const median = nums[Math.floor(nums.length / 2)]; + return nums.reduce((sum, num) => sum + Math.abs(num - median), 0); +}; diff --git a/README.md b/README.md index a474a5d6..e2960439 100644 --- a/README.md +++ b/README.md @@ -370,6 +370,7 @@ 459|[Repeated Substring Pattern](./0459-repeated-substring-pattern.js)|Easy| 460|[LFU Cache](./0460-lfu-cache.js)|Hard| 461|[Hamming Distance](./0461-hamming-distance.js)|Easy| +462|[Minimum Moves to Equal Array Elements II](./0462-minimum-moves-to-equal-array-elements-ii.js)|Medium| 463|[Island Perimeter](./0463-island-perimeter.js)|Medium| 472|[Concatenated Words](./0472-concatenated-words.js)|Hard| 476|[Number Complement](./0476-number-complement.js)|Easy| From 82f7cb0a341d3212fe937bdbfd5b8884becea009 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 1 Mar 2025 17:13:56 -0600 Subject: [PATCH 759/919] Add solution #3402 --- 3402-minimum-operations-to-make-columns-strictly-increasing.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/3402-minimum-operations-to-make-columns-strictly-increasing.js b/3402-minimum-operations-to-make-columns-strictly-increasing.js index 18b4b600..54266a5f 100644 --- a/3402-minimum-operations-to-make-columns-strictly-increasing.js +++ b/3402-minimum-operations-to-make-columns-strictly-increasing.js @@ -1,6 +1,6 @@ /** * 3402. Minimum Operations to Make Columns Strictly Increasing - * https://leetcode.com/problems/minimum-operations-to-make-columns-strictly-increasing + * https://leetcode.com/problems/minimum-operations-to-make-columns-strictly-increasing/ * Difficulty: Easy * * You are given a m x n matrix grid consisting of non-negative integers. From 336d9f4666390f662fcb6e2bc22f9f8c4eb89155 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 1 Mar 2025 17:39:18 -0600 Subject: [PATCH 760/919] Add solution #464 --- 0464-can-i-win.js | 49 +++++++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 50 insertions(+) create mode 100644 0464-can-i-win.js diff --git a/0464-can-i-win.js b/0464-can-i-win.js new file mode 100644 index 00000000..1dce8068 --- /dev/null +++ b/0464-can-i-win.js @@ -0,0 +1,49 @@ +/** + * 464. Can I Win + * https://leetcode.com/problems/can-i-win/ + * Difficulty: Medium + * + * In the "100 game" two players take turns adding, to a running total, any integer from 1 to 10. + * The player who first causes the running total to reach or exceed 100 wins. + * + * What if we change the game so that players cannot re-use integers? + * + * For example, two players might take turns drawing from a common pool of numbers from 1 to 15 + * without replacement until they reach a total >= 100. + * + * Given two integers maxChoosableInteger and desiredTotal, return true if the first player to + * move can force a win, otherwise, return false. Assume both players play optimally. + */ + +/** + * @param {number} maxChoosableInteger + * @param {number} desiredTotal + * @return {boolean} + */ +var canIWin = function(maxChoosableInteger, desiredTotal) { + const memo = new Map(); + const sum = (maxChoosableInteger * (maxChoosableInteger + 1)) / 2; + + if (desiredTotal <= 0) return true; + if (sum < desiredTotal) return false; + + return check(0, desiredTotal); + + function check(state, remaining) { + if (remaining <= 0) return false; + + const key = state.toString(); + if (memo.has(key)) return memo.get(key); + + for (let i = 1; i <= maxChoosableInteger; i++) { + const mask = 1 << i; + if (!(state & mask) && (i >= remaining || !check(state | mask, remaining - i))) { + memo.set(key, true); + return true; + } + } + + memo.set(key, false); + return false; + } +}; diff --git a/README.md b/README.md index e2960439..ccabab01 100644 --- a/README.md +++ b/README.md @@ -372,6 +372,7 @@ 461|[Hamming Distance](./0461-hamming-distance.js)|Easy| 462|[Minimum Moves to Equal Array Elements II](./0462-minimum-moves-to-equal-array-elements-ii.js)|Medium| 463|[Island Perimeter](./0463-island-perimeter.js)|Medium| +464|[Can I Win](./0464-can-i-win.js)|Medium| 472|[Concatenated Words](./0472-concatenated-words.js)|Hard| 476|[Number Complement](./0476-number-complement.js)|Easy| 482|[License Key Formatting](./0482-license-key-formatting.js)|Easy| From 26b97f73710fcf749517bc079ca0c6429c3005df Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 1 Mar 2025 17:40:17 -0600 Subject: [PATCH 761/919] Add solution #466 --- 0466-count-the-repetitions.js | 56 +++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 57 insertions(+) create mode 100644 0466-count-the-repetitions.js diff --git a/0466-count-the-repetitions.js b/0466-count-the-repetitions.js new file mode 100644 index 00000000..5ceb7b2a --- /dev/null +++ b/0466-count-the-repetitions.js @@ -0,0 +1,56 @@ +/** + * 466. Count The Repetitions + * https://leetcode.com/problems/count-the-repetitions/ + * Difficulty: Hard + * + * We define str = [s, n] as the string str which consists of the string s concatenated n times. + * + * - For example, str == ["abc", 3] =="abcabcabc". + * + * We define that string s1 can be obtained from string s2 if we can remove some characters from + * s2 such that it becomes s1. + * + * - For example, s1 = "abc" can be obtained from s2 = "abdbec" based on our definition by + * removing the bolded underlined characters. + * + * You are given two strings s1 and s2 and two integers n1 and n2. You have the two strings + * str1 = [s1, n1] and str2 = [s2, n2]. + * + * Return the maximum integer m such that str = [str2, m] can be obtained from str1. + */ + +/** + * @param {string} s1 + * @param {number} n1 + * @param {string} s2 + * @param {number} n2 + * @return {number} + */ +var getMaxRepetitions = function(s1, n1, s2, n2) { + const pattern = {}; + let s2Count = 0; + let s2Index = 0; + + for (let i = 0; i < n1; i++) { + for (let j = 0; j < s1.length; j++) { + if (s1[j] === s2[s2Index]) { + s2Index++; + if (s2Index === s2.length) { + s2Index = 0; + s2Count++; + } + } + } + + if (pattern[s2Index]) { + const [prevIndex, prevCount] = pattern[s2Index]; + const remainingCycles = Math.floor((n1 - i - 1) / (i - prevIndex)); + i += remainingCycles * (i - prevIndex); + s2Count += remainingCycles * (s2Count - prevCount); + } else { + pattern[s2Index] = [i, s2Count]; + } + } + + return Math.floor(s2Count / n2); +}; diff --git a/README.md b/README.md index ccabab01..5b3f5ff4 100644 --- a/README.md +++ b/README.md @@ -373,6 +373,7 @@ 462|[Minimum Moves to Equal Array Elements II](./0462-minimum-moves-to-equal-array-elements-ii.js)|Medium| 463|[Island Perimeter](./0463-island-perimeter.js)|Medium| 464|[Can I Win](./0464-can-i-win.js)|Medium| +466|[Count The Repetitions](./0466-count-the-repetitions.js)|Hard| 472|[Concatenated Words](./0472-concatenated-words.js)|Hard| 476|[Number Complement](./0476-number-complement.js)|Easy| 482|[License Key Formatting](./0482-license-key-formatting.js)|Easy| From 29b02e2ea6b2cccd71207c36dceb1080a1b0ad89 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 1 Mar 2025 17:41:04 -0600 Subject: [PATCH 762/919] Add solution #467 --- ...-unique-substrings-in-wraparound-string.js | 28 +++++++++++++++++++ README.md | 1 + 2 files changed, 29 insertions(+) create mode 100644 0467-unique-substrings-in-wraparound-string.js diff --git a/0467-unique-substrings-in-wraparound-string.js b/0467-unique-substrings-in-wraparound-string.js new file mode 100644 index 00000000..ff358dd9 --- /dev/null +++ b/0467-unique-substrings-in-wraparound-string.js @@ -0,0 +1,28 @@ +/** + * 467. Unique Substrings in Wraparound String + * https://leetcode.com/problems/unique-substrings-in-wraparound-string/ + * Difficulty: Medium + * + * We define the string base to be the infinite wraparound string of "abcdefghijklmnopqrstuvwxyz", + * so base will look like this: + * - "...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd....". + * + * Given a string s, return the number of unique non-empty substrings of s are present in base. + */ + +/** + * @param {string} s + * @return {number} + */ +var findSubstringInWraproundString = function(s) { + const maxLength = new Array(26).fill(0); + let count = 0; + + for (let i = 0; i < s.length; i++) { + count = i > 0 && (s.charCodeAt(i) - s.charCodeAt(i - 1) - 1) % 26 === 0 ? count + 1 : 1; + const index = s.charCodeAt(i) - 97; + maxLength[index] = Math.max(maxLength[index], count); + } + + return maxLength.reduce((sum, n) => sum + n, 0); +}; diff --git a/README.md b/README.md index 5b3f5ff4..45ed7841 100644 --- a/README.md +++ b/README.md @@ -374,6 +374,7 @@ 463|[Island Perimeter](./0463-island-perimeter.js)|Medium| 464|[Can I Win](./0464-can-i-win.js)|Medium| 466|[Count The Repetitions](./0466-count-the-repetitions.js)|Hard| +467|[Unique Substrings in Wraparound String](./0467-unique-substrings-in-wraparound-string.js)|Medium| 472|[Concatenated Words](./0472-concatenated-words.js)|Hard| 476|[Number Complement](./0476-number-complement.js)|Easy| 482|[License Key Formatting](./0482-license-key-formatting.js)|Easy| From 8959ae84ee646ce9781483cb577acf61075956af Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 1 Mar 2025 17:42:30 -0600 Subject: [PATCH 763/919] Add solution #468 --- 0468-validate-ip-address.js | 33 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 0468-validate-ip-address.js diff --git a/0468-validate-ip-address.js b/0468-validate-ip-address.js new file mode 100644 index 00000000..3a5a6384 --- /dev/null +++ b/0468-validate-ip-address.js @@ -0,0 +1,33 @@ +/** + * 468. Validate IP Address + * https://leetcode.com/problems/validate-ip-address/ + * Difficulty: Medium + * + * Given a string queryIP, return "IPv4" if IP is a valid IPv4 address, "IPv6" if IP is a valid + * IPv6 address or "Neither" if IP is not a correct IP of any type. + * + * A valid IPv4 address is an IP in the form "x1.x2.x3.x4" where 0 <= xi <= 255 and xi cannot + * contain leading zeros. For example, "192.168.1.1" and "192.168.1.0" are valid IPv4 addresses + * while "192.168.01.1", "192.168.1.00", and "192.168@1.1" are invalid IPv4 addresses. + * + * A valid IPv6 address is an IP in the form "x1:x2:x3:x4:x5:x6:x7:x8" where: + * - 1 <= xi.length <= 4 + * - xi is a hexadecimal string which may contain digits, lowercase English letter ('a' to 'f') + * and upper-case English letters ('A' to 'F'). + * - Leading zeros are allowed in xi. + * + * For example, "2001:0db8:85a3:0000:0000:8a2e:0370:7334" and "2001:db8:85a3:0:0:8A2E:0370:7334" + * are valid IPv6 addresses, while "2001:0db8:85a3::8A2E:037j:7334" and + * "02001:0db8:85a3:0000:0000:8a2e:0370:7334" are invalid IPv6 addresses. + */ + +/** + * @param {string} queryIP + * @return {string} + */ +var validIPAddress = function(queryIP) { + const ipv4 = /^((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.){3}(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])$/; + const ipv6 = /^([\da-fA-F]{1,4}:){7}[\da-fA-F]{1,4}$/; + + return ipv4.test(queryIP) ? 'IPv4' : ipv6.test(queryIP) ? 'IPv6' : 'Neither'; +}; diff --git a/README.md b/README.md index 45ed7841..6aa8b977 100644 --- a/README.md +++ b/README.md @@ -375,6 +375,7 @@ 464|[Can I Win](./0464-can-i-win.js)|Medium| 466|[Count The Repetitions](./0466-count-the-repetitions.js)|Hard| 467|[Unique Substrings in Wraparound String](./0467-unique-substrings-in-wraparound-string.js)|Medium| +468|[Validate IP Address](./0468-validate-ip-address.js)|Medium| 472|[Concatenated Words](./0472-concatenated-words.js)|Hard| 476|[Number Complement](./0476-number-complement.js)|Easy| 482|[License Key Formatting](./0482-license-key-formatting.js)|Easy| From 2bffa05acf7bdf20871f82a7e3228fd989460d6b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 1 Mar 2025 17:43:43 -0600 Subject: [PATCH 764/919] Add solution #470 --- 0470-implement-rand10-using-rand7.js | 28 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 29 insertions(+) create mode 100644 0470-implement-rand10-using-rand7.js diff --git a/0470-implement-rand10-using-rand7.js b/0470-implement-rand10-using-rand7.js new file mode 100644 index 00000000..1ed60242 --- /dev/null +++ b/0470-implement-rand10-using-rand7.js @@ -0,0 +1,28 @@ +/** + * 470. Implement Rand10() Using Rand7() + * https://leetcode.com/problems/implement-rand10-using-rand7/ + * Difficulty: Medium + * + * Given the API rand7() that generates a uniform random integer in the range [1, 7], + * write a function rand10() that generates a uniform random integer in the range [1, 10]. + * You can only call the API rand7(), and you shouldn't call any other API. Please do not + * use a language's built-in random API. + * + * Each test case will have one internal argument n, the number of times that your implemented + * function rand10() will be called while testing. Note that this is not an argument passed to + * rand10(). + */ + +/** + * The rand7() API is already defined for you. + * var rand7 = function() {} + * @return {number} a random integer in the range 1 to 7 + */ +var rand10 = function() { + while (true) { + const n = (rand7() - 1) * 7 + rand7(); + if (n <= 40) { + return (n % 10) + 1; + } + } +}; diff --git a/README.md b/README.md index 6aa8b977..d23bb5dd 100644 --- a/README.md +++ b/README.md @@ -376,6 +376,7 @@ 466|[Count The Repetitions](./0466-count-the-repetitions.js)|Hard| 467|[Unique Substrings in Wraparound String](./0467-unique-substrings-in-wraparound-string.js)|Medium| 468|[Validate IP Address](./0468-validate-ip-address.js)|Medium| +470|[Implement Rand10() Using Rand7()](./0470-implement-rand10-using-rand7.js)|Medium| 472|[Concatenated Words](./0472-concatenated-words.js)|Hard| 476|[Number Complement](./0476-number-complement.js)|Easy| 482|[License Key Formatting](./0482-license-key-formatting.js)|Easy| From b49ca7d827afe30e7afa2856cea87bebd7894d0e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 2 Mar 2025 16:19:34 -0600 Subject: [PATCH 765/919] Add solution #2570 --- 2570-merge-two-2d-arrays-by-summing-values.js | 34 +++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 2570-merge-two-2d-arrays-by-summing-values.js diff --git a/2570-merge-two-2d-arrays-by-summing-values.js b/2570-merge-two-2d-arrays-by-summing-values.js new file mode 100644 index 00000000..7a0bc18d --- /dev/null +++ b/2570-merge-two-2d-arrays-by-summing-values.js @@ -0,0 +1,34 @@ +/** + * 2570. Merge Two 2D Arrays by Summing Values + * https://leetcode.com/problems/merge-two-2d-arrays-by-summing-values/ + * Difficulty: Easy + * + * You are given two 2D integer arrays nums1 and nums2. + * - nums1[i] = [idi, vali] indicate that the number with the id idi has a value equal to vali. + * - nums2[i] = [idi, vali] indicate that the number with the id idi has a value equal to vali. + * + * Each array contains unique ids and is sorted in ascending order by id. + * + * Merge the two arrays into one array that is sorted in ascending order by id, respecting the + * following conditions: + * - Only ids that appear in at least one of the two arrays should be included in the resulting + * array. + * - Each id should be included only once and its value should be the sum of the values of this + * id in the two arrays. If the id does not exist in one of the two arrays, then assume its + * value in that array to be 0. + * + * Return the resulting array. The returned array must be sorted in ascending order by id. + */ + +/** + * @param {number[][]} nums1 + * @param {number[][]} nums2 + * @return {number[][]} + */ +var mergeArrays = function(nums1, nums2) { + const map = new Map(nums1); + for (const [key, value] of nums2) { + map.set(key, (map.get(key) ?? 0) + value); + } + return [...map].sort((a, b) => a[0] - b[0]); +}; diff --git a/README.md b/README.md index d23bb5dd..63014e81 100644 --- a/README.md +++ b/README.md @@ -681,6 +681,7 @@ 2529|[Maximum Count of Positive Integer and Negative Integer](./2529-maximum-count-of-positive-integer-and-negative-integer.js)|Easy| 2535|[Difference Between Element Sum and Digit Sum of an Array](./2535-difference-between-element-sum-and-digit-sum-of-an-array.js)|Easy| 2542|[Maximum Subsequence Score](./2542-maximum-subsequence-score.js)|Medium| +2570|[Merge Two 2D Arrays by Summing Values](./2570-merge-two-2d-arrays-by-summing-values.js)|Easy| 2618|[Check if Object Instance of Class](./2618-check-if-object-instance-of-class.js)|Medium| 2619|[Array Prototype Last](./2619-array-prototype-last.js)|Easy| 2620|[Counter](./2620-counter.js)|Easy| From d191f7a010dcca87b8c60a6ddec75207237307a0 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 2 Mar 2025 16:20:26 -0600 Subject: [PATCH 766/919] Add solution #473 --- 0473-matchsticks-to-square.js | 39 +++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 40 insertions(+) create mode 100644 0473-matchsticks-to-square.js diff --git a/0473-matchsticks-to-square.js b/0473-matchsticks-to-square.js new file mode 100644 index 00000000..d596647c --- /dev/null +++ b/0473-matchsticks-to-square.js @@ -0,0 +1,39 @@ +/** + * 473. Matchsticks to Square + * https://leetcode.com/problems/matchsticks-to-square/ + * Difficulty: Medium + * + * You are given an integer array matchsticks where matchsticks[i] is the length of the ith + * matchstick. You want to use all the matchsticks to make one square. You should not break + * any stick, but you can link them up, and each matchstick must be used exactly one time. + * + * Return true if you can make this square and false otherwise. + */ + +/** + * @param {number[]} matchsticks + * @return {boolean} + */ +var makesquare = function(matchsticks) { + if (matchsticks.length < 4) return false; + const sum = matchsticks.reduce((a, b) => a + b); + if (sum % 4) return false; + + const side = sum / 4; + matchsticks.sort((a, b) => b - a); + if (matchsticks[0] > side) return false; + + const sides = [0, 0, 0, 0]; + return (function backtrack(index) { + if (index === matchsticks.length) return true; + for (let i = 0; i < 4; i++) { + if (sides[i] + matchsticks[index] <= side) { + sides[i] += matchsticks[index]; + if (backtrack(index + 1)) return true; + sides[i] -= matchsticks[index]; + if (!sides[i]) break; + } + } + return false; + })(0); +}; diff --git a/README.md b/README.md index 63014e81..caad8c6e 100644 --- a/README.md +++ b/README.md @@ -378,6 +378,7 @@ 468|[Validate IP Address](./0468-validate-ip-address.js)|Medium| 470|[Implement Rand10() Using Rand7()](./0470-implement-rand10-using-rand7.js)|Medium| 472|[Concatenated Words](./0472-concatenated-words.js)|Hard| +473|[Matchsticks to Square](./0473-matchsticks-to-square.js)|Medium| 476|[Number Complement](./0476-number-complement.js)|Easy| 482|[License Key Formatting](./0482-license-key-formatting.js)|Easy| 485|[Max Consecutive Ones](./0485-max-consecutive-ones.js)|Easy| From 1fd9ab3b402c95a73271c43dc122724186bf9b04 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 2 Mar 2025 16:21:00 -0600 Subject: [PATCH 767/919] Add solution #474 --- 0474-ones-and-zeroes.js | 32 ++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 0474-ones-and-zeroes.js diff --git a/0474-ones-and-zeroes.js b/0474-ones-and-zeroes.js new file mode 100644 index 00000000..a7008edb --- /dev/null +++ b/0474-ones-and-zeroes.js @@ -0,0 +1,32 @@ +/** + * 474. Ones and Zeroes + * https://leetcode.com/problems/ones-and-zeroes/ + * Difficulty: Medium + * + * You are given an array of binary strings strs and two integers m and n. + * + * Return the size of the largest subset of strs such that there are at most m 0's and n 1's + * in the subset. + * + * A set x is a subset of a set y if all elements of x are also elements of y. + */ + +/** + * @param {string[]} strs + * @param {number} m + * @param {number} n + * @return {number} + */ +var findMaxForm = function(strs, m, n) { + const dp = Array.from({ length: m + 1 }, () => new Uint16Array(n + 1)); + for (const str of strs) { + const zeros = (str.match(/0/g) || []).length; + const ones = str.length - zeros; + for (let i = m; i >= zeros; i--) { + for (let j = n; j >= ones; j--) { + dp[i][j] = Math.max(dp[i][j], dp[i - zeros][j - ones] + 1); + } + } + } + return dp[m][n]; +}; diff --git a/README.md b/README.md index caad8c6e..0cc68f6c 100644 --- a/README.md +++ b/README.md @@ -379,6 +379,7 @@ 470|[Implement Rand10() Using Rand7()](./0470-implement-rand10-using-rand7.js)|Medium| 472|[Concatenated Words](./0472-concatenated-words.js)|Hard| 473|[Matchsticks to Square](./0473-matchsticks-to-square.js)|Medium| +474|[Ones and Zeroes](./0474-ones-and-zeroes.js)|Medium| 476|[Number Complement](./0476-number-complement.js)|Easy| 482|[License Key Formatting](./0482-license-key-formatting.js)|Easy| 485|[Max Consecutive Ones](./0485-max-consecutive-ones.js)|Easy| From b036bbd7f40cf41b223962cc70d8321ea8d0b50d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 2 Mar 2025 16:21:50 -0600 Subject: [PATCH 768/919] Add solution #475 --- 0475-heaters.js | 35 +++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 36 insertions(+) create mode 100644 0475-heaters.js diff --git a/0475-heaters.js b/0475-heaters.js new file mode 100644 index 00000000..a395021e --- /dev/null +++ b/0475-heaters.js @@ -0,0 +1,35 @@ +/** + * 475. Heaters + * https://leetcode.com/problems/heaters/ + * Difficulty: Medium + * + * Winter is coming! During the contest, your first job is to design a standard heater with + * a fixed warm radius to warm all the houses. + * + * Every house can be warmed, as long as the house is within the heater's warm radius range. + * + * Given the positions of houses and heaters on a horizontal line, return the minimum radius + * standard of heaters so that those heaters could cover all houses. + * + * Notice that all the heaters follow your radius standard, and the warm radius will the same. + */ + +/** + * @param {number[]} houses + * @param {number[]} heaters + * @return {number} + */ +var findRadius = function(houses, heaters) { + let result = 0; + + houses.sort((a, b) => a - b); + heaters.sort((a, b) => a - b); + for (let i = 0, j = 0; i < houses.length; i++) { + while (j < heaters.length - 1 && houses[i] - heaters[j] > heaters[j + 1] - houses[i]) { + j++; + } + result = Math.max(result, Math.abs(heaters[j] - houses[i])); + } + + return result; +}; diff --git a/README.md b/README.md index 0cc68f6c..d00e72b6 100644 --- a/README.md +++ b/README.md @@ -380,6 +380,7 @@ 472|[Concatenated Words](./0472-concatenated-words.js)|Hard| 473|[Matchsticks to Square](./0473-matchsticks-to-square.js)|Medium| 474|[Ones and Zeroes](./0474-ones-and-zeroes.js)|Medium| +475|[Heaters](./0475-heaters.js)|Medium| 476|[Number Complement](./0476-number-complement.js)|Easy| 482|[License Key Formatting](./0482-license-key-formatting.js)|Easy| 485|[Max Consecutive Ones](./0485-max-consecutive-ones.js)|Easy| From f651204c49c117a60aff2c8803d8374b7134793b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 2 Mar 2025 16:22:21 -0600 Subject: [PATCH 769/919] Add solution #477 --- 0477-total-hamming-distance.js | 26 ++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 27 insertions(+) create mode 100644 0477-total-hamming-distance.js diff --git a/0477-total-hamming-distance.js b/0477-total-hamming-distance.js new file mode 100644 index 00000000..b3bd8424 --- /dev/null +++ b/0477-total-hamming-distance.js @@ -0,0 +1,26 @@ +/** + * 477. Total Hamming Distance + * https://leetcode.com/problems/total-hamming-distance/ + * Difficulty: Medium + * + * The Hamming distance between two integers is the number of positions at which the + * corresponding bits are different. + * + * Given an integer array nums, return the sum of Hamming distances between all the + * pairs of the integers in nums. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var totalHammingDistance = function(nums) { + let result = 0; + + for (let bit = 0; bit < 32; bit++) { + const ones = nums.reduce((count, n) => count + ((n >> bit) & 1), 0); + result += ones * (nums.length - ones); + } + + return result; +}; diff --git a/README.md b/README.md index d00e72b6..1b463dcc 100644 --- a/README.md +++ b/README.md @@ -382,6 +382,7 @@ 474|[Ones and Zeroes](./0474-ones-and-zeroes.js)|Medium| 475|[Heaters](./0475-heaters.js)|Medium| 476|[Number Complement](./0476-number-complement.js)|Easy| +477|[Total Hamming Distance](./0477-total-hamming-distance.js)|Medium| 482|[License Key Formatting](./0482-license-key-formatting.js)|Easy| 485|[Max Consecutive Ones](./0485-max-consecutive-ones.js)|Easy| 486|[Predict the Winner](./0486-predict-the-winner.js)|Medium| From cb86817125fd8ff9d2ef2bbd441822878d277420 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 2 Mar 2025 16:40:07 -0600 Subject: [PATCH 770/919] Add solution #637 --- 0637-average-of-levels-in-binary-tree.js | 41 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 42 insertions(+) create mode 100644 0637-average-of-levels-in-binary-tree.js diff --git a/0637-average-of-levels-in-binary-tree.js b/0637-average-of-levels-in-binary-tree.js new file mode 100644 index 00000000..2299f9bb --- /dev/null +++ b/0637-average-of-levels-in-binary-tree.js @@ -0,0 +1,41 @@ +/** + * 637. Average of Levels in Binary Tree + * https://leetcode.com/problems/average-of-levels-in-binary-tree/ + * Difficulty: Easy + * + * Given the root of a binary tree, return the average value of the nodes on each level in the + * form of an array. Answers within 10-5 of the actual answer will be accepted. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number[]} + */ +var averageOfLevels = function(root) { + const result = []; + const queue = [root]; + + while (queue.length) { + const level = queue.length; + let sum = 0; + + for (let i = 0; i < level; i++) { + const node = queue.shift(); + sum += node.val; + if (node.left) queue.push(node.left); + if (node.right) queue.push(node.right); + } + + result.push(sum / level); + } + + return result; +}; diff --git a/README.md b/README.md index 1b463dcc..6e7fed9b 100644 --- a/README.md +++ b/README.md @@ -419,6 +419,7 @@ 617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy| 621|[Task Scheduler](./0621-task-scheduler.js)|Medium| 628|[Maximum Product of Three Numbers](./0628-maximum-product-of-three-numbers.js)|Easy| +637|[Average of Levels in Binary Tree](./0637-average-of-levels-in-binary-tree.js)|Easy| 643|[Maximum Average Subarray I](./0643-maximum-average-subarray-i.js)|Easy| 645|[Set Mismatch](./0645-set-mismatch.js)|Medium| 648|[Replace Words](./0648-replace-words.js)|Medium| From d67e64a34e59961345c42799b102776000acb240 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 2 Mar 2025 16:40:49 -0600 Subject: [PATCH 771/919] Add solution #530 --- 0530-minimum-absolute-difference-in-bst.js | 36 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 37 insertions(+) create mode 100644 0530-minimum-absolute-difference-in-bst.js diff --git a/0530-minimum-absolute-difference-in-bst.js b/0530-minimum-absolute-difference-in-bst.js new file mode 100644 index 00000000..be78b143 --- /dev/null +++ b/0530-minimum-absolute-difference-in-bst.js @@ -0,0 +1,36 @@ +/** + * 530. Minimum Absolute Difference in BST + * https://leetcode.com/problems/minimum-absolute-difference-in-bst/ + * Difficulty: Easy + * + * Given the root of a Binary Search Tree (BST), return the minimum absolute difference between + * the values of any two different nodes in the 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) + * } + */ +/** + * @param {TreeNode} root + * @return {number} + */ +var getMinimumDifference = function(root) { + let result = Infinity; + let previous = null; + + inorder(root); + return result; + + function inorder(node) { + if (!node) return; + inorder(node.left); + result = previous === null ? result : Math.min(result, node.val - previous); + previous = node.val; + inorder(node.right); + } +}; diff --git a/README.md b/README.md index 6e7fed9b..6802ca49 100644 --- a/README.md +++ b/README.md @@ -399,6 +399,7 @@ 509|[Fibonacci Number](./0509-fibonacci-number.js)|Easy| 520|[Detect Capital](./0520-detect-capital.js)|Easy| 521|[Longest Uncommon Subsequence I](./0521-longest-uncommon-subsequence-i.js)|Easy| +530|[Minimum Absolute Difference in BST](./0530-minimum-absolute-difference-in-bst.js)|Easy| 541|[Reverse String II](./0541-reverse-string-ii.js)|Easy| 542|[01 Matrix](./0542-01-matrix.js)|Medium| 543|[Diameter of Binary Tree](./0543-diameter-of-binary-tree.js)|Easy| From 2022ada583e87a01113c80120655f18ef3ee0d15 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 2 Mar 2025 16:41:41 -0600 Subject: [PATCH 772/919] Add solution #783 --- 0783-minimum-distance-between-bst-nodes.js | 36 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 37 insertions(+) create mode 100644 0783-minimum-distance-between-bst-nodes.js diff --git a/0783-minimum-distance-between-bst-nodes.js b/0783-minimum-distance-between-bst-nodes.js new file mode 100644 index 00000000..a18f65f6 --- /dev/null +++ b/0783-minimum-distance-between-bst-nodes.js @@ -0,0 +1,36 @@ +/** + * 783. Minimum Distance Between BST Nodes + * https://leetcode.com/problems/minimum-distance-between-bst-nodes/ + * Difficulty: Easy + * + * Given the root of a Binary Search Tree (BST), return the minimum difference between + * the values of any two different nodes in the 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) + * } + */ +/** + * @param {TreeNode} root + * @return {number} + */ +var minDiffInBST = function(root) { + let result = Infinity; + let previous = null; + + inorder(root); + return result; + + function inorder(node) { + if (!node) return; + inorder(node.left); + result = previous === null ? result : Math.min(result, node.val - previous); + previous = node.val; + inorder(node.right); + } +}; diff --git a/README.md b/README.md index 6802ca49..9a2cc3ba 100644 --- a/README.md +++ b/README.md @@ -457,6 +457,7 @@ 748|[Shortest Completing Word](./0748-shortest-completing-word.js)|Easy| 762|[Prime Number of Set Bits in Binary Representation](./0762-prime-number-of-set-bits-in-binary-representation.js)|Easy| 763|[Partition Labels](./0763-partition-labels.js)|Medium| +783|[Minimum Distance Between BST Nodes](./0783-minimum-distance-between-bst-nodes.js)|Easy| 784|[Letter Case Permutation](./0784-letter-case-permutation.js)|Medium| 790|[Domino and Tromino Tiling](./0790-domino-and-tromino-tiling.js)|Medium| 791|[Custom Sort String](./0791-custom-sort-string.js)|Medium| From d1fa70a748c50ba61f4771b8449114fcf7959873 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 2 Mar 2025 16:43:48 -0600 Subject: [PATCH 773/919] Add solution #909 --- 0909-snakes-and-ladders.js | 70 ++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 71 insertions(+) create mode 100644 0909-snakes-and-ladders.js diff --git a/0909-snakes-and-ladders.js b/0909-snakes-and-ladders.js new file mode 100644 index 00000000..feb15ef6 --- /dev/null +++ b/0909-snakes-and-ladders.js @@ -0,0 +1,70 @@ +/** + * 909. Snakes and Ladders + * https://leetcode.com/problems/snakes-and-ladders/ + * Difficulty: Medium + * + * You are given an n x n integer matrix board where the cells are labeled from 1 to n2 in a + * Boustrophedon style starting from the bottom left of the board (i.e. board[n - 1][0]) and + * alternating direction each row. + * + * You start on square 1 of the board. In each move, starting from square curr, do the following: + * - Choose a destination square next with a label in the range [curr + 1, min(curr + 6, n2)]. + * - This choice simulates the result of a standard 6-sided die roll: i.e., there are always at + * most 6 destinations, regardless of the size of the board. + * - If next has a snake or ladder, you must move to the destination of that snake or ladder. + * Otherwise, you move to next. + * - The game ends when you reach the square n2. + * + * A board square on row r and column c has a snake or ladder if board[r][c] != -1. The destination + * of that snake or ladder is board[r][c]. Squares 1 and n2 are not the starting points of any + * snake or ladder. + * + * Note that you only take a snake or ladder at most once per dice roll. If the destination to a + * snake or ladder is the start of another snake or ladder, you do not follow the subsequent snake + * or ladder. + * + * - For example, suppose the board is [[-1,4],[-1,3]], and on the first move, your destination + * square is 2. You follow the ladder to square 3, but do not follow the subsequent ladder to 4. + * + * Return the least number of dice rolls required to reach the square n2. If it is not possible to + * reach the square, return -1. + */ + +/** + * @param {number[][]} board + * @return {number} + */ +var snakesAndLadders = function(board) { + const target = board.length * board.length; + const queue = [1]; + const seen = new Set([1]); + let moves = 0; + + while (queue.length) { + const size = queue.length; + for (let i = 0; i < size; i++) { + const current = queue.shift(); + if (current === target) return moves; + for (let dice = 1; dice <= 6 && current + dice <= target; dice++) { + const next = current + dice; + const [r, c] = getCoordinates(next); + const destination = board[r][c] === -1 ? next : board[r][c]; + if (!seen.has(destination)) { + seen.add(destination); + queue.push(destination); + } + } + } + moves++; + } + + return -1; + + function getCoordinates(square) { + const r = board.length - 1 - Math.floor((square - 1) / board.length); + const c = (board.length - 1 - r) % 2 === 0 + ? (square - 1) % board.length + : board.length - 1 - (square - 1) % board.length; + return [r, c]; + } +}; diff --git a/README.md b/README.md index 9a2cc3ba..223a2c44 100644 --- a/README.md +++ b/README.md @@ -484,6 +484,7 @@ 890|[Find and Replace Pattern](./0890-find-and-replace-pattern.js)|Medium| 901|[Online Stock Span](./0901-online-stock-span.js)|Medium| 905|[Sort Array By Parity](./0905-sort-array-by-parity.js)|Easy| +909|[Snakes and Ladders](./0909-snakes-and-ladders.js)|Medium| 912|[Sort an Array](./0912-sort-an-array.js)|Medium| 914|[X of a Kind in a Deck of Cards](./0914-x-of-a-kind-in-a-deck-of-cards.js)|Medium| 916|[Word Subsets](./0916-word-subsets.js)|Medium| From 85e9a48f7db122fe959d6a53839cc49ce80d162e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 2 Mar 2025 16:44:28 -0600 Subject: [PATCH 774/919] Add solution #918 --- 0918-maximum-sum-circular-subarray.js | 34 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 0918-maximum-sum-circular-subarray.js diff --git a/0918-maximum-sum-circular-subarray.js b/0918-maximum-sum-circular-subarray.js new file mode 100644 index 00000000..59eaa655 --- /dev/null +++ b/0918-maximum-sum-circular-subarray.js @@ -0,0 +1,34 @@ +/** + * 918. Maximum Sum Circular Subarray + * https://leetcode.com/problems/maximum-sum-circular-subarray/ + * Difficulty: Medium + * + * Given a circular integer array nums of length n, return the maximum possible sum of + * a non-empty subarray of nums. + * + * A circular array means the end of the array connects to the beginning of the array. + * Formally, the next element of nums[i] is nums[(i + 1) % n] and the previous element + * of nums[i] is nums[(i - 1 + n) % n]. + * + * A subarray may only include each element of the fixed buffer nums at most once. + * Formally, for a subarray nums[i], nums[i + 1], ..., nums[j], there does not exist + * i <= k1, k2 <= j with k1 % n == k2 % n. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var maxSubarraySumCircular = function(nums) { + let [min, max, sum] = [nums[0], nums[0], nums[0]]; + + for (let i = 1, prevMin = nums[0], prevMax = nums[0]; i < nums.length; i++) { + prevMax = Math.max(nums[i], prevMax + nums[i]); + max = Math.max(max, prevMax); + prevMin = Math.min(nums[i], prevMin + nums[i]); + min = Math.min(min, prevMin); + sum += nums[i]; + } + + return max > 0 ? Math.max(max, sum - min) : max; +}; diff --git a/README.md b/README.md index 223a2c44..b0f698c2 100644 --- a/README.md +++ b/README.md @@ -488,6 +488,7 @@ 912|[Sort an Array](./0912-sort-an-array.js)|Medium| 914|[X of a Kind in a Deck of Cards](./0914-x-of-a-kind-in-a-deck-of-cards.js)|Medium| 916|[Word Subsets](./0916-word-subsets.js)|Medium| +918|[Maximum Sum Circular Subarray](./0918-maximum-sum-circular-subarray.js)|Medium| 922|[Sort Array By Parity II](./0922-sort-array-by-parity-ii.js)|Easy| 925|[Long Pressed Name](./0925-long-pressed-name.js)|Easy| 926|[Flip String to Monotone Increasing](./0926-flip-string-to-monotone-increasing.js)|Medium| From 63649d0819a40e8481eb8410c2c1ad620f4fdc83 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 2 Mar 2025 22:02:56 -0600 Subject: [PATCH 775/919] Add solution #2161 --- ...artition-array-according-to-given-pivot.js | 31 +++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 2161-partition-array-according-to-given-pivot.js diff --git a/2161-partition-array-according-to-given-pivot.js b/2161-partition-array-according-to-given-pivot.js new file mode 100644 index 00000000..72a90b40 --- /dev/null +++ b/2161-partition-array-according-to-given-pivot.js @@ -0,0 +1,31 @@ +/** + * 2161. Partition Array According to Given Pivot + * https://leetcode.com/problems/partition-array-according-to-given-pivot/ + * Difficulty: Medium + * + * You are given a 0-indexed integer array nums and an integer pivot. Rearrange nums such that + * the following conditions are satisfied: + * - Every element less than pivot appears before every element greater than pivot. + * - Every element equal to pivot appears in between the elements less than and greater than + * pivot. + * - The relative order of the elements less than pivot and the elements greater than pivot + * is maintained. + * - More formally, consider every pi, pj where pi is the new position of the ith element + * and pj is the new position of the jth element. If i < j and both elements are smaller + * (or larger) than pivot, then pi < pj. + * + * Return nums after the rearrangement. + */ + +/** + * @param {number[]} nums + * @param {number} pivot + * @return {number[]} + */ +var pivotArray = function(nums, pivot) { + return [ + ...nums.filter(x => x < pivot), + ...nums.filter(x => x === pivot), + ...nums.filter(x => x > pivot), + ]; +}; diff --git a/README.md b/README.md index b0f698c2..7c56bc95 100644 --- a/README.md +++ b/README.md @@ -662,6 +662,7 @@ 2129|[Capitalize the Title](./2129-capitalize-the-title.js)|Easy| 2130|[Maximum Twin Sum of a Linked List](./2130-maximum-twin-sum-of-a-linked-list.js)|Medium| 2154|[Keep Multiplying Found Values by Two](./2154-keep-multiplying-found-values-by-two.js)|Easy| +2161|[Partition Array According to Given Pivot](./2161-partition-array-according-to-given-pivot.js)|Medium| 2185|[Counting Words With a Given Prefix](./2185-counting-words-with-a-given-prefix.js)|Easy| 2215|[Find the Difference of Two Arrays](./2215-find-the-difference-of-two-arrays.js)|Easy| 2235|[Add Two Integers](./2235-add-two-integers.js)|Easy| From 80aaf1213ac572b460a2711b7351f5d49a95ea2f Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 2 Mar 2025 22:06:28 -0600 Subject: [PATCH 776/919] Add solution #478 --- 0478-generate-random-point-in-a-circle.js | 37 +++++++++++++++++++++++ README.md | 1 + 2 files changed, 38 insertions(+) create mode 100644 0478-generate-random-point-in-a-circle.js diff --git a/0478-generate-random-point-in-a-circle.js b/0478-generate-random-point-in-a-circle.js new file mode 100644 index 00000000..d4dee73c --- /dev/null +++ b/0478-generate-random-point-in-a-circle.js @@ -0,0 +1,37 @@ +/** + * 478. Generate Random Point in a Circle + * https://leetcode.com/problems/generate-random-point-in-a-circle/ + * Difficulty: Medium + * + * Given the radius and the position of the center of a circle, implement the function randPoint + * which generates a uniform random point inside the circle. + * + * Implement the Solution class: + * - Solution(double radius, double x_center, double y_center) initializes the object with the + * radius of the circle radius and the position of the center (x_center, y_center). + * - randPoint() returns a random point inside the circle. A point on the circumference of the + * circle is considered to be in the circle. The answer is returned as an array [x, y]. + */ + +/** + * @param {number} radius + * @param {number} x + * @param {number} y + */ +var Solution = function(radius, x, y) { + this.r = radius; + this.x = x; + this.y = y; +}; + +/** + * @return {number[]} + */ +Solution.prototype.randPoint = function() { + while (true) { + const [x, y] = [Math.random() * 2 - 1, Math.random() * 2 - 1]; + if (x * x + y * y <= 1) { + return [this.x + x * this.r, this.y + y * this.r]; + } + } +}; diff --git a/README.md b/README.md index 7c56bc95..dc8fc9a3 100644 --- a/README.md +++ b/README.md @@ -383,6 +383,7 @@ 475|[Heaters](./0475-heaters.js)|Medium| 476|[Number Complement](./0476-number-complement.js)|Easy| 477|[Total Hamming Distance](./0477-total-hamming-distance.js)|Medium| +478|[Generate Random Point in a Circle](./0478-generate-random-point-in-a-circle.js)|Medium| 482|[License Key Formatting](./0482-license-key-formatting.js)|Easy| 485|[Max Consecutive Ones](./0485-max-consecutive-ones.js)|Easy| 486|[Predict the Winner](./0486-predict-the-winner.js)|Medium| From 7ddce1e4e6b7d979e878c64fb6403b931a16ef63 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 2 Mar 2025 22:07:39 -0600 Subject: [PATCH 777/919] Add solution #479 --- 0479-largest-palindrome-product.js | 26 ++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 27 insertions(+) create mode 100644 0479-largest-palindrome-product.js diff --git a/0479-largest-palindrome-product.js b/0479-largest-palindrome-product.js new file mode 100644 index 00000000..1673b5d1 --- /dev/null +++ b/0479-largest-palindrome-product.js @@ -0,0 +1,26 @@ +/** + * 479. Largest Palindrome Product + * https://leetcode.com/problems/largest-palindrome-product/ + * Difficulty: Hard + * + * Given an integer n, return the largest palindromic integer that can be represented as the + * product of two n-digits integers. Since the answer can be very large, return it modulo 1337. + */ + +/** + * @param {number} n + * @return {number} + */ +var largestPalindrome = function(n) { + if (n === 1) return 9; + const max = 10 ** n - 1; + for (let a = 1; a <= 9 * 10 ** (n - 1); a++) { + const h = max - a + 1; + const l = BigInt(String(h).split('').reverse().join('')); + const x = BigInt(a) * BigInt(a) - 4n * l; + if (x < 0) continue; + const sqrtX = BigInt(Math.floor(Math.sqrt(Number(x)))); + if (sqrtX * sqrtX !== x && (sqrtX + 1n) * (sqrtX + 1n) !== x) continue; + return Number((l + 10n ** BigInt(n) * BigInt(h)) % 1337n); + } +}; diff --git a/README.md b/README.md index dc8fc9a3..c478f7a8 100644 --- a/README.md +++ b/README.md @@ -384,6 +384,7 @@ 476|[Number Complement](./0476-number-complement.js)|Easy| 477|[Total Hamming Distance](./0477-total-hamming-distance.js)|Medium| 478|[Generate Random Point in a Circle](./0478-generate-random-point-in-a-circle.js)|Medium| +479|[Largest Palindrome Product](./0479-largest-palindrome-product.js)|Hard| 482|[License Key Formatting](./0482-license-key-formatting.js)|Easy| 485|[Max Consecutive Ones](./0485-max-consecutive-ones.js)|Easy| 486|[Predict the Winner](./0486-predict-the-winner.js)|Medium| From d3b2d606a8af6654ec4a2e7154d3a76299fea59a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 2 Mar 2025 22:09:29 -0600 Subject: [PATCH 778/919] Add solution #480 --- 0480-sliding-window-median.js | 47 +++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 48 insertions(+) create mode 100644 0480-sliding-window-median.js diff --git a/0480-sliding-window-median.js b/0480-sliding-window-median.js new file mode 100644 index 00000000..7aff7dcf --- /dev/null +++ b/0480-sliding-window-median.js @@ -0,0 +1,47 @@ +/** + * 480. Sliding Window Median + * https://leetcode.com/problems/sliding-window-median/ + * Difficulty: Hard + * + * The median is the middle value in an ordered integer list. If the size of the list is even, + * there is no middle value. So the median is the mean of the two middle values. + * + * - For examples, if arr = [2,3,4], the median is 3. + * - For examples, if arr = [1,2,3,4], the median is (2 + 3) / 2 = 2.5. + * + * You are given an integer array nums and an integer k. There is a sliding window of size k + * which is moving from the very left of the array to the very right. You can only see the k + * numbers in the window. Each time the sliding window moves right by one position. + * + * Return the median array for each window in the original array. Answers within 10-5 of the + * actual value will be accepted. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {number[]} + */ +var medianSlidingWindow = function(nums, k) { + const maxHeap = new MaxPriorityQueue(); + const minHeap = new MinPriorityQueue(); + const result = []; + const map = {}; + + for (let i = 0; i < k; i++) maxHeap.enqueue(nums[i]); + for (let i = 0; i < k >> 1; i++) minHeap.enqueue(maxHeap.dequeue()); + for (let i = k; i <= nums.length; i++) { + result.push(k & 1 ? maxHeap.front() : (maxHeap.front() + minHeap.front()) / 2); + if (i === nums.length) break; + map[nums[i - k]] = (map[nums[i - k]] || 0) + 1; + const balance = (nums[i - k] <= maxHeap.front() ? -1 : 1) + + (nums[i] <= maxHeap.front() ? 1 : -1); + nums[i] <= maxHeap.front() ? maxHeap.enqueue(nums[i]) : minHeap.enqueue(nums[i]); + balance < 0 && minHeap.size() && maxHeap.enqueue(minHeap.dequeue()); + balance > 0 && maxHeap.size() && minHeap.enqueue(maxHeap.dequeue()); + while (maxHeap.size() && map[maxHeap.front()]) map[maxHeap.dequeue()]--; + while (minHeap.size() && map[minHeap.front()]) map[minHeap.dequeue()]--; + } + + return result; +}; diff --git a/README.md b/README.md index c478f7a8..0b1d9ec2 100644 --- a/README.md +++ b/README.md @@ -385,6 +385,7 @@ 477|[Total Hamming Distance](./0477-total-hamming-distance.js)|Medium| 478|[Generate Random Point in a Circle](./0478-generate-random-point-in-a-circle.js)|Medium| 479|[Largest Palindrome Product](./0479-largest-palindrome-product.js)|Hard| +480|[Sliding Window Median](./0480-sliding-window-median.js)|Hard| 482|[License Key Formatting](./0482-license-key-formatting.js)|Easy| 485|[Max Consecutive Ones](./0485-max-consecutive-ones.js)|Easy| 486|[Predict the Winner](./0486-predict-the-winner.js)|Medium| From c05139103ec2c595a5d7ce19ab5e792336c3cb0d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 2 Mar 2025 22:11:51 -0600 Subject: [PATCH 779/919] Add solution #481 --- 0481-magical-string.js | 39 +++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 40 insertions(+) create mode 100644 0481-magical-string.js diff --git a/0481-magical-string.js b/0481-magical-string.js new file mode 100644 index 00000000..6e0896c4 --- /dev/null +++ b/0481-magical-string.js @@ -0,0 +1,39 @@ +/** + * 481. Magical String + * https://leetcode.com/problems/magical-string/ + * Difficulty: Medium + * + * A magical string s consists of only '1' and '2' and obeys the following rules: + * - The string s is magical because concatenating the number of contiguous occurrences of + * characters '1' and '2' generates the string s itself. + * - The first few elements of s is s = "1221121221221121122……". If we group the consecutive + * 1's and 2's in s, it will be "1 22 11 2 1 22 1 22 11 2 11 22 ......" and the occurrences + * of 1's or 2's in each group are "1 2 2 1 1 2 1 2 2 1 2 2 ......". You can see that the + * occurrence sequence is s itself. + * + * Given an integer n, return the number of 1's in the first n number in the magical string s. + */ + +/** + * @param {number} n + * @return {number} + */ +var magicalString = function(n) { + if (n <= 0) return 0; + if (n <= 3) return 1; + + const stack = [1, 2, 2]; + let result = 1; + + for (let i = 2, num = 1; stack.length < n; i++) { + for (let j = 0; j < stack[i]; j++) { + stack.push(num); + if (num === 1 && stack.length <= n) { + result++; + } + } + num = num === 1 ? 2 : 1; + } + + return result; +}; diff --git a/README.md b/README.md index 0b1d9ec2..e6641541 100644 --- a/README.md +++ b/README.md @@ -386,6 +386,7 @@ 478|[Generate Random Point in a Circle](./0478-generate-random-point-in-a-circle.js)|Medium| 479|[Largest Palindrome Product](./0479-largest-palindrome-product.js)|Hard| 480|[Sliding Window Median](./0480-sliding-window-median.js)|Hard| +481|[Magical String](./0481-magical-string.js)|Medium| 482|[License Key Formatting](./0482-license-key-formatting.js)|Easy| 485|[Max Consecutive Ones](./0485-max-consecutive-ones.js)|Easy| 486|[Predict the Winner](./0486-predict-the-winner.js)|Medium| From fa8b66744a1cd92399becf14d3311888215f88b4 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 3 Mar 2025 01:22:25 -0600 Subject: [PATCH 780/919] Add solution #483 --- 0483-smallest-good-base.js | 24 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 0483-smallest-good-base.js diff --git a/0483-smallest-good-base.js b/0483-smallest-good-base.js new file mode 100644 index 00000000..04c37324 --- /dev/null +++ b/0483-smallest-good-base.js @@ -0,0 +1,24 @@ +/** + * 483. Smallest Good Base + * https://leetcode.com/problems/smallest-good-base/ + * Difficulty: Hard + * + * Given an integer n represented as a string, return the smallest good base of n. + * + * We call k >= 2 a good base of n, if all digits of n base k are 1's. + */ + +/** + * @param {string} n + * @return {string} + */ +var smallestGoodBase = function(n) { + const num = BigInt(n); + for (let m = Math.floor(Math.log2(Number(n))); m >= 1; m--) { + const k = BigInt(Math.floor(Number(n) ** (1 / m))); + if (k < 2n) continue; + const sum = (k ** BigInt(m + 1) - 1n) / (k - 1n); + if (sum === num) return k.toString(); + } + return (num - 1n).toString(); +}; diff --git a/README.md b/README.md index e6641541..85a9eab1 100644 --- a/README.md +++ b/README.md @@ -388,6 +388,7 @@ 480|[Sliding Window Median](./0480-sliding-window-median.js)|Hard| 481|[Magical String](./0481-magical-string.js)|Medium| 482|[License Key Formatting](./0482-license-key-formatting.js)|Easy| +483|[Smallest Good Base](./0483-smallest-good-base.js)|Hard| 485|[Max Consecutive Ones](./0485-max-consecutive-ones.js)|Easy| 486|[Predict the Winner](./0486-predict-the-winner.js)|Medium| 491|[Non-decreasing Subsequences](./0491-non-decreasing-subsequences.js)|Medium| From 9b2b448ccc0e4ad69edc2f5a2004ab4db6d25ea7 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 3 Mar 2025 01:27:21 -0600 Subject: [PATCH 781/919] Add solution #488 --- 0488-zuma-game.js | 101 ++++++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 102 insertions(+) create mode 100644 0488-zuma-game.js diff --git a/0488-zuma-game.js b/0488-zuma-game.js new file mode 100644 index 00000000..5d0dd7df --- /dev/null +++ b/0488-zuma-game.js @@ -0,0 +1,101 @@ +/** + * 488. Zuma Game + * https://leetcode.com/problems/zuma-game/ + * Difficulty: Hard + * + * You are playing a variation of the game Zuma. + * + * In this variation of Zuma, there is a single row of colored balls on a board, where each ball + * can be colored red 'R', yellow 'Y', blue 'B', green 'G', or white 'W'. You also have several + * colored balls in your hand. + * + * Your goal is to clear all of the balls from the board. On each turn: + * - Pick any ball from your hand and insert it in between two balls in the row or on either end + * of the row. + * - If there is a group of three or more consecutive balls of the same color, remove the group of + * balls from the board. + * - If this removal causes more groups of three or more of the same color to form, then continue + * removing each group until there are none left. + * - If there are no more balls on the board, then you win the game. + * - Repeat this process until you either win or do not have any more balls in your hand. + * + * Given a string board, representing the row of balls on the board, and a string hand, representing + * the balls in your hand, return the minimum number of balls you have to insert to clear all the + * balls from the board. If you cannot clear all the balls from the board using the balls in your + * hand, return -1. + */ + +/** + * @param {string} board + * @param {string} hand + * @return {number} + */ +var findMinStep = function(board, hand) { + const handCount = {}; + for (const ball of hand) { + handCount[ball] = (handCount[ball] || 0) + 1; + } + + const memo = new Map(); + + function dfs(board, hand) { + if (board.length === 0) return 0; + if (Object.values(hand).every(count => count === 0)) return -1; + const key = board + getHandString(hand); + if (memo.has(key)) return memo.get(key); + let minSteps = Infinity; + + for (const color in hand) { + if (hand[color] <= 0) continue; + hand[color]--; + for (let i = 0; i <= board.length; i++) { + if (i > 0 && i < board.length) { + const left = board[i-1]; + const right = board[i]; + if (left !== color && right !== color && left !== right) continue; + } + const newBoard = board.slice(0, i) + color + board.slice(i); + const afterRemove = removeConsecutive(newBoard); + const steps = dfs(afterRemove, hand); + if (steps !== -1) { + minSteps = Math.min(minSteps, steps + 1); + } + } + hand[color]++; + } + const result = minSteps === Infinity ? -1 : minSteps; + memo.set(key, result); + return result; + }; + + return dfs(board, handCount); +}; + +function getHandString(hand) { + return Object.entries(hand) + .filter(([_, count]) => count > 0) + .sort(([a], [b]) => a.localeCompare(b)) + .map(([color, count]) => color + count) + .join(''); +} + +function removeConsecutive(board) { + let changed = true; + while (changed) { + changed = false; + for (let i = 0; i < board.length;) { + let j = i; + while (j < board.length && board[j] === board[i]) { + j++; + } + if (j - i >= 3) { + board = board.substring(0, i) + board.substring(j); + changed = true; + i = 0; + } else { + i++; + } + } + } + return board; +} diff --git a/README.md b/README.md index 85a9eab1..73f00cc2 100644 --- a/README.md +++ b/README.md @@ -391,6 +391,7 @@ 483|[Smallest Good Base](./0483-smallest-good-base.js)|Hard| 485|[Max Consecutive Ones](./0485-max-consecutive-ones.js)|Easy| 486|[Predict the Winner](./0486-predict-the-winner.js)|Medium| +488|[Zuma Game](./0488-zuma-game.js)|Hard| 491|[Non-decreasing Subsequences](./0491-non-decreasing-subsequences.js)|Medium| 492|[Construct the Rectangle](./0492-construct-the-rectangle.js)|Easy| 496|[Next Greater Element I](./0496-next-greater-element-i.js)|Easy| From 1b3d6418a83dd5b5af641d83345138d09e758b74 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 3 Mar 2025 01:28:20 -0600 Subject: [PATCH 782/919] Add solution #493 --- 0493-reverse-pairs.js | 59 +++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 60 insertions(+) create mode 100644 0493-reverse-pairs.js diff --git a/0493-reverse-pairs.js b/0493-reverse-pairs.js new file mode 100644 index 00000000..998877b1 --- /dev/null +++ b/0493-reverse-pairs.js @@ -0,0 +1,59 @@ +/** + * 493. Reverse Pairs + * https://leetcode.com/problems/reverse-pairs/ + * Difficulty: Hard + * + * Given an integer array nums, return the number of reverse pairs in the array. + * + * A reverse pair is a pair (i, j) where: + * - 0 <= i < j < nums.length and + * - nums[i] > 2 * nums[j]. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var reversePairs = function(nums) { + let count = 0; + mergeSort(nums, 0, nums.length - 1); + return count; + + function mergeSort(input, left, right) { + if (left >= right) return; + const middle = Math.floor((left + right) / 2); + mergeSort(input, left, middle); + mergeSort(input, middle + 1, right); + merge(input, left, middle, right); + } + + function merge(input, left, middle, right) { + let j = middle + 1; + for (let i = left; i <= middle; i++) { + while (j <= right && input[i] > 2 * input[j]) { + j++; + } + count += j - (middle + 1); + } + + const order = []; + let i = left; + j = middle + 1; + while (i <= middle && j <= right) { + if (input[i] <= input[j]) { + order.push(input[i++]); + } else { + order.push(input[j++]); + } + } + while (i <= middle) { + order.push(input[i++]); + } + while (j <= right) { + order.push(input[j++]); + } + for (let k = 0; k < order.length; k++) { + input[left + k] = order[k]; + } + } +}; diff --git a/README.md b/README.md index 73f00cc2..d009d5d6 100644 --- a/README.md +++ b/README.md @@ -394,6 +394,7 @@ 488|[Zuma Game](./0488-zuma-game.js)|Hard| 491|[Non-decreasing Subsequences](./0491-non-decreasing-subsequences.js)|Medium| 492|[Construct the Rectangle](./0492-construct-the-rectangle.js)|Easy| +493|[Reverse Pairs](./0493-reverse-pairs.js)|Hard| 496|[Next Greater Element I](./0496-next-greater-element-i.js)|Easy| 500|[Keyboard Row](./0500-keyboard-row.js)|Easy| 501|[Find Mode in Binary Search Tree](./0501-find-mode-in-binary-search-tree.js)|Easy| From 9f470181f44937a592047c3b27922a205da3bb08 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 3 Mar 2025 01:32:01 -0600 Subject: [PATCH 783/919] Add solution #494 --- 0494-target-sum.js | 39 +++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 40 insertions(+) create mode 100644 0494-target-sum.js diff --git a/0494-target-sum.js b/0494-target-sum.js new file mode 100644 index 00000000..ef381b88 --- /dev/null +++ b/0494-target-sum.js @@ -0,0 +1,39 @@ +/** + * 494. Target Sum + * https://leetcode.com/problems/target-sum/ + * Difficulty: Medium + * + * You are given an integer array nums and an integer target. + * + * You want to build an expression out of nums by adding one of the symbols '+' and '-' before + * each integer in nums and then concatenate all the integers. + * + * For example, if nums = [2, 1], you can add a '+' before 2 and a '-' before 1 and concatenate + * them to build the expression "+2-1". + * + * Return the number of different expressions that you can build, which evaluates to target. + */ + +/** + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +var findTargetSumWays = function(nums, target) { + const map = new Map(); + + function dp(index, sum) { + if (index === nums.length) { + return sum === target ? 1 : 0; + } + const key = `${index},${sum}`; + if (map.has(key)) { + return map.get(key); + } + const r = dp(index + 1, sum + nums[index]) + dp(index + 1, sum - nums[index]); + map.set(key, r); + return r; + } + + return dp(0, 0); +}; diff --git a/README.md b/README.md index d009d5d6..6f860edb 100644 --- a/README.md +++ b/README.md @@ -395,6 +395,7 @@ 491|[Non-decreasing Subsequences](./0491-non-decreasing-subsequences.js)|Medium| 492|[Construct the Rectangle](./0492-construct-the-rectangle.js)|Easy| 493|[Reverse Pairs](./0493-reverse-pairs.js)|Hard| +494|[Target Sum](./0494-target-sum.js)|Medium| 496|[Next Greater Element I](./0496-next-greater-element-i.js)|Easy| 500|[Keyboard Row](./0500-keyboard-row.js)|Easy| 501|[Find Mode in Binary Search Tree](./0501-find-mode-in-binary-search-tree.js)|Easy| From 3be32194da568b18e32b0ad67ce446a444af27d7 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 3 Mar 2025 01:33:02 -0600 Subject: [PATCH 784/919] Add solution #495 --- 0495-teemo-attacking.js | 27 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 28 insertions(+) create mode 100644 0495-teemo-attacking.js diff --git a/0495-teemo-attacking.js b/0495-teemo-attacking.js new file mode 100644 index 00000000..a8d8d579 --- /dev/null +++ b/0495-teemo-attacking.js @@ -0,0 +1,27 @@ +/** + * 495. Teemo Attacking + * https://leetcode.com/problems/teemo-attacking/ + * Difficulty: Easy + * + * Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets + * poisoned for a exactly duration seconds. More formally, an attack at second t will mean Ashe is + * poisoned during the inclusive time interval [t, t + duration - 1]. If Teemo attacks again before + * the poison effect ends, the timer for it is reset, and the poison effect will end duration + * seconds after the new attack. + * + * You are given a non-decreasing integer array timeSeries, where timeSeries[i] denotes that Teemo + * attacks Ashe at second timeSeries[i], and an integer duration. + * + * Return the total number of seconds that Ashe is poisoned. + */ + +/** + * @param {number[]} timeSeries + * @param {number} duration + * @return {number} + */ +var findPoisonedDuration = function(timeSeries, duration) { + return timeSeries.reduce((sum, n, i) => { + return sum + Math.min(duration, (timeSeries[i + 1] ?? n + duration) - n); + }, 0); +}; diff --git a/README.md b/README.md index 6f860edb..42d8c1dd 100644 --- a/README.md +++ b/README.md @@ -396,6 +396,7 @@ 492|[Construct the Rectangle](./0492-construct-the-rectangle.js)|Easy| 493|[Reverse Pairs](./0493-reverse-pairs.js)|Hard| 494|[Target Sum](./0494-target-sum.js)|Medium| +495|[Teemo Attacking](./0495-teemo-attacking.js)|Easy| 496|[Next Greater Element I](./0496-next-greater-element-i.js)|Easy| 500|[Keyboard Row](./0500-keyboard-row.js)|Easy| 501|[Find Mode in Binary Search Tree](./0501-find-mode-in-binary-search-tree.js)|Easy| From 6ad32b35c6e8455e121d7342774a1fe10c649a08 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 3 Mar 2025 01:43:29 -0600 Subject: [PATCH 785/919] Add solution #497 --- ...dom-point-in-non-overlapping-rectangles.js | 47 +++++++++++++++++++ README.md | 1 + 2 files changed, 48 insertions(+) create mode 100644 0497-random-point-in-non-overlapping-rectangles.js diff --git a/0497-random-point-in-non-overlapping-rectangles.js b/0497-random-point-in-non-overlapping-rectangles.js new file mode 100644 index 00000000..ceefac34 --- /dev/null +++ b/0497-random-point-in-non-overlapping-rectangles.js @@ -0,0 +1,47 @@ +/** + * 497. Random Point in Non-overlapping Rectangles + * https://leetcode.com/problems/random-point-in-non-overlapping-rectangles/ + * Difficulty: Medium + * + * You are given an array of non-overlapping axis-aligned rectangles rects where + * rects[i] = [ai, bi, xi, yi] indicates that (ai, bi) is the bottom-left corner point of the + * ith rectangle and (xi, yi) is the top-right corner point of the ith rectangle. Design an + * algorithm to pick a random integer point inside the space covered by one of the given + * rectangles. A point on the perimeter of a rectangle is included in the space covered by + * the rectangle. + * + * Any integer point inside the space covered by one of the given rectangles should be equally + * likely to be returned. + * + * Note that an integer point is a point that has integer coordinates. + * + * Implement the Solution class: + * - Solution(int[][] rects) Initializes the object with the given rectangles rects. + * - int[] pick() Returns a random integer point [u, v] inside the space covered by one of the + * given rectangles. + */ + +/** + * @param {number[][]} rects + */ +var Solution = function(rects) { + this.rects = rects; + this.areas = rects.map(([x1, y1, x2, y2]) => (x2 - x1 + 1) * (y2 - y1 + 1)); + this.totalPoints = this.areas.reduce((sum, area) => sum + area, 0); +}; + +/** + * @return {number[]} + */ +Solution.prototype.pick = function() { + let random = Math.floor(Math.random() * this.totalPoints); + let i = 0; + while (random >= this.areas[i]) { + random -= this.areas[i]; + i++; + } + const [x1, y1, x2, y2] = this.rects[i]; + const x = x1 + Math.floor(Math.random() * (x2 - x1 + 1)); + const y = y1 + Math.floor(Math.random() * (y2 - y1 + 1)); + return [x, y]; +}; diff --git a/README.md b/README.md index 42d8c1dd..caaad7d2 100644 --- a/README.md +++ b/README.md @@ -398,6 +398,7 @@ 494|[Target Sum](./0494-target-sum.js)|Medium| 495|[Teemo Attacking](./0495-teemo-attacking.js)|Easy| 496|[Next Greater Element I](./0496-next-greater-element-i.js)|Easy| +497|[Random Point in Non-overlapping Rectangles](./0497-random-point-in-non-overlapping-rectangles.js)|Medium| 500|[Keyboard Row](./0500-keyboard-row.js)|Easy| 501|[Find Mode in Binary Search Tree](./0501-find-mode-in-binary-search-tree.js)|Easy| 502|[IPO](./0502-ipo.js)|Hard| From d0707b06812edabc39479a8d142d0cfaf1efd705 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 3 Mar 2025 01:44:18 -0600 Subject: [PATCH 786/919] Add solution #498 --- 0498-diagonal-traverse.js | 45 +++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 46 insertions(+) create mode 100644 0498-diagonal-traverse.js diff --git a/0498-diagonal-traverse.js b/0498-diagonal-traverse.js new file mode 100644 index 00000000..b9ac7445 --- /dev/null +++ b/0498-diagonal-traverse.js @@ -0,0 +1,45 @@ +/** + * 498. Diagonal Traverse + * https://leetcode.com/problems/diagonal-traverse/ + * Difficulty: Medium + * + * Given an m x n matrix mat, return an array of all the elements of the array in a diagonal order. + */ + +/** + * @param {number[][]} mat + * @return {number[]} + */ +var findDiagonalOrder = function(mat) { + const result = new Array(mat.length * mat[0].length); + + for (let r = 0, c = 0, d = 1, i = 0; i < mat.length * mat[0].length;) { + result[i++] = mat[r][c]; + + if (d === 1) { + if (c === mat[0].length - 1) { + r++; + d = -1; + } else if (r === 0) { + c++; + d = -1; + } else { + r--; + c++; + } + } else { + if (r === mat.length - 1) { + c++; + d = 1; + } else if (c === 0) { + r++; + d = 1; + } else { + r++; + c--; + } + } + } + + return result; +}; diff --git a/README.md b/README.md index caaad7d2..b923415a 100644 --- a/README.md +++ b/README.md @@ -399,6 +399,7 @@ 495|[Teemo Attacking](./0495-teemo-attacking.js)|Easy| 496|[Next Greater Element I](./0496-next-greater-element-i.js)|Easy| 497|[Random Point in Non-overlapping Rectangles](./0497-random-point-in-non-overlapping-rectangles.js)|Medium| +498|[Diagonal Traverse](./0498-diagonal-traverse.js)|Medium| 500|[Keyboard Row](./0500-keyboard-row.js)|Easy| 501|[Find Mode in Binary Search Tree](./0501-find-mode-in-binary-search-tree.js)|Easy| 502|[IPO](./0502-ipo.js)|Hard| From 5428b339bc75be8adc37923256eb1a4418320e6b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 3 Mar 2025 01:45:17 -0600 Subject: [PATCH 787/919] Add solution #508 --- 0508-most-frequent-subtree-sum.js | 51 +++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 52 insertions(+) create mode 100644 0508-most-frequent-subtree-sum.js diff --git a/0508-most-frequent-subtree-sum.js b/0508-most-frequent-subtree-sum.js new file mode 100644 index 00000000..b2b2e64e --- /dev/null +++ b/0508-most-frequent-subtree-sum.js @@ -0,0 +1,51 @@ +/** + * 508. Most Frequent Subtree Sum + * https://leetcode.com/problems/most-frequent-subtree-sum/ + * Difficulty: Medium + * + * Given the root of a binary tree, return the most frequent subtree sum. If there is a tie, return + * all the values with the highest frequency in any order. + * + * The subtree sum of a node is defined as the sum of all the node values formed by the subtree + * rooted at that node (including the node itself). + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number[]} + */ +var findFrequentTreeSum = function(root) { + if (!root) return []; + + const map = new Map(); + let result = []; + let max = 0; + + traverse(root); + + for (const [sum, freq] of map) { + if (freq > max) { + max = freq; + result = [sum]; + } else if (freq === max) { + result.push(sum); + } + } + + return result; + + function traverse(node) { + if (!node) return 0; + const sum = node.val + traverse(node.left) + traverse(node.right); + map.set(sum, (map.get(sum) || 0) + 1); + return sum; + } +}; diff --git a/README.md b/README.md index b923415a..6cf688f5 100644 --- a/README.md +++ b/README.md @@ -407,6 +407,7 @@ 504|[Base 7](./0504-base-7.js)|Easy| 506|[Relative Ranks](./0506-relative-ranks.js)|Easy| 507|[Perfect Number](./0507-perfect-number.js)|Easy| +508|[Most Frequent Subtree Sum](./0508-most-frequent-subtree-sum.js)|Medium| 509|[Fibonacci Number](./0509-fibonacci-number.js)|Easy| 520|[Detect Capital](./0520-detect-capital.js)|Easy| 521|[Longest Uncommon Subsequence I](./0521-longest-uncommon-subsequence-i.js)|Easy| From ada1f0775c984269a34c142ec3bd2aee21eae0b9 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 3 Mar 2025 01:45:59 -0600 Subject: [PATCH 788/919] Add solution #513 --- 0513-find-bottom-left-tree-value.js | 36 +++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 37 insertions(+) create mode 100644 0513-find-bottom-left-tree-value.js diff --git a/0513-find-bottom-left-tree-value.js b/0513-find-bottom-left-tree-value.js new file mode 100644 index 00000000..e8163b61 --- /dev/null +++ b/0513-find-bottom-left-tree-value.js @@ -0,0 +1,36 @@ +/** + * 513. Find Bottom Left Tree Value + * https://leetcode.com/problems/find-bottom-left-tree-value/ + * Difficulty: Medium + * + * Given the root of a binary tree, return the leftmost value in the last row of the 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) + * } + */ +/** + * @param {TreeNode} root + * @return {number} + */ +var findBottomLeftValue = function(root) { + const queue = [root]; + let result = root.val; + + while (queue.length) { + const size = queue.length; + result = queue[0].val; + for (let i = 0; i < size; i++) { + const node = queue.shift(); + if (node.left) queue.push(node.left); + if (node.right) queue.push(node.right); + } + } + + return result; +}; diff --git a/README.md b/README.md index 6cf688f5..07a0ae51 100644 --- a/README.md +++ b/README.md @@ -409,6 +409,7 @@ 507|[Perfect Number](./0507-perfect-number.js)|Easy| 508|[Most Frequent Subtree Sum](./0508-most-frequent-subtree-sum.js)|Medium| 509|[Fibonacci Number](./0509-fibonacci-number.js)|Easy| +513|[Find Bottom Left Tree Value](./0513-find-bottom-left-tree-value.js)|Medium| 520|[Detect Capital](./0520-detect-capital.js)|Easy| 521|[Longest Uncommon Subsequence I](./0521-longest-uncommon-subsequence-i.js)|Easy| 530|[Minimum Absolute Difference in BST](./0530-minimum-absolute-difference-in-bst.js)|Easy| From 210bda3b7d638532d493a942c14c81190a410e76 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 3 Mar 2025 01:48:58 -0600 Subject: [PATCH 789/919] Add solution #514 --- 0514-freedom-trail.js | 51 +++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 52 insertions(+) create mode 100644 0514-freedom-trail.js diff --git a/0514-freedom-trail.js b/0514-freedom-trail.js new file mode 100644 index 00000000..97cb3a38 --- /dev/null +++ b/0514-freedom-trail.js @@ -0,0 +1,51 @@ +/** + * 514. Freedom Trail + * https://leetcode.com/problems/freedom-trail/ + * Difficulty: Hard + * + * In the video game Fallout 4, the quest "Road to Freedom" requires players to reach a metal dial + * called the "Freedom Trail Ring" and use the dial to spell a specific keyword to open the door. + * + * Given a string ring that represents the code engraved on the outer ring and another string key + * that represents the keyword that needs to be spelled, return the minimum number of steps to spell + * all the characters in the keyword. + * + * Initially, the first character of the ring is aligned at the "12:00" direction. You should spell + * all the characters in key one by one by rotating ring clockwise or anticlockwise to make each + * character of the string key aligned at the "12:00" direction and then by pressing the center + * button. + * + * At the stage of rotating the ring to spell the key character key[i]: + * - You can rotate the ring clockwise or anticlockwise by one place, which counts as one step. + * The final purpose of the rotation is to align one of ring's characters at the "12:00" + * direction, where this character must equal key[i]. + * - If the character key[i] has been aligned at the "12:00" direction, press the center button + * to spell, which also counts as one step. After the pressing, you could begin to spell the + * next character in the key (next stage). Otherwise, you have finished all the spelling. + */ + +/** + * @param {string} ring + * @param {string} key + * @return {number} + */ +var findRotateSteps = function(ring, key) { + const map = new Map(); + return dp(0, 0); + + function dp(ringIndex, keyIndex) { + if (keyIndex === key.length) return 0; + const state = `${ringIndex},${keyIndex}`; + if (map.has(state)) return map.get(state); + let minSteps = Infinity; + for (let i = 0; i < ring.length; i++) { + if (ring[i] === key[keyIndex]) { + const distance = Math.abs(i - ringIndex); + const steps = Math.min(distance, ring.length - distance); + minSteps = Math.min(minSteps, steps + 1 + dp(i, keyIndex + 1)); + } + } + map.set(state, minSteps); + return minSteps; + } +}; diff --git a/README.md b/README.md index 07a0ae51..c6aa5c7c 100644 --- a/README.md +++ b/README.md @@ -410,6 +410,7 @@ 508|[Most Frequent Subtree Sum](./0508-most-frequent-subtree-sum.js)|Medium| 509|[Fibonacci Number](./0509-fibonacci-number.js)|Easy| 513|[Find Bottom Left Tree Value](./0513-find-bottom-left-tree-value.js)|Medium| +514|[Freedom Trail](./0514-freedom-trail.js)|Hard| 520|[Detect Capital](./0520-detect-capital.js)|Easy| 521|[Longest Uncommon Subsequence I](./0521-longest-uncommon-subsequence-i.js)|Easy| 530|[Minimum Absolute Difference in BST](./0530-minimum-absolute-difference-in-bst.js)|Easy| From be68c533889222e478719523780fee99ba61b1e1 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 4 Mar 2025 17:52:17 -0600 Subject: [PATCH 790/919] Add solution #515 --- 0515-find-largest-value-in-each-tree-row.js | 40 +++++++++++++++++++++ README.md | 1 + 2 files changed, 41 insertions(+) create mode 100644 0515-find-largest-value-in-each-tree-row.js diff --git a/0515-find-largest-value-in-each-tree-row.js b/0515-find-largest-value-in-each-tree-row.js new file mode 100644 index 00000000..7c20a6e7 --- /dev/null +++ b/0515-find-largest-value-in-each-tree-row.js @@ -0,0 +1,40 @@ +/** + * 515. Find Largest Value in Each Tree Row + * https://leetcode.com/problems/find-largest-value-in-each-tree-row/ + * Difficulty: Medium + * + * Given the root of a binary tree, return an array of the largest value in each row + * of the tree (0-indexed). + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number[]} + */ +var largestValues = function(root) { + if (!root) return []; + const result = []; + const queue = [root]; + + while (queue.length) { + const level = queue.length; + let max = -Infinity; + for (let i = 0; i < level; i++) { + const node = queue.shift(); + max = Math.max(max, node.val); + if (node.left) queue.push(node.left); + if (node.right) queue.push(node.right); + } + result.push(max); + } + + return result; +}; diff --git a/README.md b/README.md index c6aa5c7c..e93bf224 100644 --- a/README.md +++ b/README.md @@ -411,6 +411,7 @@ 509|[Fibonacci Number](./0509-fibonacci-number.js)|Easy| 513|[Find Bottom Left Tree Value](./0513-find-bottom-left-tree-value.js)|Medium| 514|[Freedom Trail](./0514-freedom-trail.js)|Hard| +515|[Find Largest Value in Each Tree Row](./0515-find-largest-value-in-each-tree-row.js)|Medium| 520|[Detect Capital](./0520-detect-capital.js)|Easy| 521|[Longest Uncommon Subsequence I](./0521-longest-uncommon-subsequence-i.js)|Easy| 530|[Minimum Absolute Difference in BST](./0530-minimum-absolute-difference-in-bst.js)|Easy| From 6f205a174633acdf87ba1c2123410c612f62ab8f Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 4 Mar 2025 17:53:42 -0600 Subject: [PATCH 791/919] Add solution #516 --- 0516-longest-palindromic-subsequence.js | 36 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 37 insertions(+) create mode 100644 0516-longest-palindromic-subsequence.js diff --git a/0516-longest-palindromic-subsequence.js b/0516-longest-palindromic-subsequence.js new file mode 100644 index 00000000..5541b2ec --- /dev/null +++ b/0516-longest-palindromic-subsequence.js @@ -0,0 +1,36 @@ +/** + * 516. Longest Palindromic Subsequence + * https://leetcode.com/problems/longest-palindromic-subsequence/ + * Difficulty: Medium + * + * Given a string s, find the longest palindromic subsequence's length in s. + * + * A subsequence is a sequence that can be derived from another sequence by deleting some + * or no elements without changing the order of the remaining elements. + */ + +/** + * @param {string} s + * @return {number} + */ +/** + * @param {string} s + * @return {number} + */ +var longestPalindromeSubseq = function(s) { + const dp = new Array(s.length).fill(0); + + for (let i = s.length - 1, previous; i >= 0; i--) { + previous = dp.slice(); + dp[i] = 1; + for (let j = i + 1; j < s.length; j++) { + if (s[i] === s[j]) { + dp[j] = (previous[j - 1] || 0) + 2; + } else { + dp[j] = Math.max(dp[j - 1], previous[j]); + } + } + } + + return dp[s.length - 1]; +}; diff --git a/README.md b/README.md index e93bf224..c84dbfce 100644 --- a/README.md +++ b/README.md @@ -412,6 +412,7 @@ 513|[Find Bottom Left Tree Value](./0513-find-bottom-left-tree-value.js)|Medium| 514|[Freedom Trail](./0514-freedom-trail.js)|Hard| 515|[Find Largest Value in Each Tree Row](./0515-find-largest-value-in-each-tree-row.js)|Medium| +516|[Longest Palindromic Subsequence](./0516-longest-palindromic-subsequence.js)|Medium| 520|[Detect Capital](./0520-detect-capital.js)|Easy| 521|[Longest Uncommon Subsequence I](./0521-longest-uncommon-subsequence-i.js)|Easy| 530|[Minimum Absolute Difference in BST](./0530-minimum-absolute-difference-in-bst.js)|Easy| From c9570d3dddfe05793cf0f95719f7296eb7218357 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 4 Mar 2025 17:56:28 -0600 Subject: [PATCH 792/919] Add solution #517 --- 0517-super-washing-machines.js | 32 ++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 0517-super-washing-machines.js diff --git a/0517-super-washing-machines.js b/0517-super-washing-machines.js new file mode 100644 index 00000000..399565ba --- /dev/null +++ b/0517-super-washing-machines.js @@ -0,0 +1,32 @@ +/** + * 517. Super Washing Machines + * https://leetcode.com/problems/super-washing-machines/ + * Difficulty: Hard + * + * You have n super washing machines on a line. Initially, each washing machine has some + * dresses or is empty. + * + * For each move, you could choose any m (1 <= m <= n) washing machines, and pass one dress + * of each washing machine to one of its adjacent washing machines at the same time. + * + * Given an integer array machines representing the number of dresses in each washing machine + * from left to right on the line, return the minimum number of moves to make all the washing + * machines have the same number of dresses. If it is not possible to do it, return -1. + */ + +/** + * @param {number[]} machines + * @return {number} + */ +var findMinMoves = function(machines) { + const total = machines.reduce((sum, num) => sum + num, 0); + const target = total / machines.length; + if (total % machines.length !== 0) return -1; + + let result = 0; + for (let i = 0, balance = 0; i < machines.length; i++) { + balance += machines[i] - target; + result = Math.max(result, Math.abs(balance), machines[i] - target); + } + return result; +}; diff --git a/README.md b/README.md index c84dbfce..8bab3049 100644 --- a/README.md +++ b/README.md @@ -413,6 +413,7 @@ 514|[Freedom Trail](./0514-freedom-trail.js)|Hard| 515|[Find Largest Value in Each Tree Row](./0515-find-largest-value-in-each-tree-row.js)|Medium| 516|[Longest Palindromic Subsequence](./0516-longest-palindromic-subsequence.js)|Medium| +517|[Super Washing Machines](./0517-super-washing-machines.js)|Hard| 520|[Detect Capital](./0520-detect-capital.js)|Easy| 521|[Longest Uncommon Subsequence I](./0521-longest-uncommon-subsequence-i.js)|Easy| 530|[Minimum Absolute Difference in BST](./0530-minimum-absolute-difference-in-bst.js)|Easy| From e3f4da0022db3fdeb6cd5b7a41df0beaa561210c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 4 Mar 2025 17:57:40 -0600 Subject: [PATCH 793/919] Add solution #518 --- 0518-coin-change-ii.js | 33 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 0518-coin-change-ii.js diff --git a/0518-coin-change-ii.js b/0518-coin-change-ii.js new file mode 100644 index 00000000..4b93fd9f --- /dev/null +++ b/0518-coin-change-ii.js @@ -0,0 +1,33 @@ +/** + * 518. Coin Change II + * https://leetcode.com/problems/coin-change-ii/ + * Difficulty: Medium + * + * You are given an integer array coins representing coins of different denominations and + * an integer amount representing a total amount of money. + * + * Return the number of combinations that make up that amount. If that amount of money + * cannot be made up by any combination of the coins, return 0. + * + * You may assume that you have an infinite number of each kind of coin. + * + * The answer is guaranteed to fit into a signed 32-bit integer. + */ + +/** + * @param {number} amount + * @param {number[]} coins + * @return {number} + */ +var change = function(amount, coins) { + const dp = new Array(amount + 1).fill(0); + dp[0] = 1; + + for (const coin of coins) { + for (let i = coin; i <= amount; i++) { + dp[i] += dp[i - coin]; + } + } + + return dp[amount]; +}; diff --git a/README.md b/README.md index 8bab3049..e11869e4 100644 --- a/README.md +++ b/README.md @@ -414,6 +414,7 @@ 515|[Find Largest Value in Each Tree Row](./0515-find-largest-value-in-each-tree-row.js)|Medium| 516|[Longest Palindromic Subsequence](./0516-longest-palindromic-subsequence.js)|Medium| 517|[Super Washing Machines](./0517-super-washing-machines.js)|Hard| +518|[Coin Change II](./0518-coin-change-ii.js)|Medium| 520|[Detect Capital](./0520-detect-capital.js)|Easy| 521|[Longest Uncommon Subsequence I](./0521-longest-uncommon-subsequence-i.js)|Easy| 530|[Minimum Absolute Difference in BST](./0530-minimum-absolute-difference-in-bst.js)|Easy| From 2e5497278cd7216c230b3241e3c5420075dedc4a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 4 Mar 2025 17:59:38 -0600 Subject: [PATCH 794/919] Add solution #519 --- 0519-random-flip-matrix.js | 47 ++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 48 insertions(+) create mode 100644 0519-random-flip-matrix.js diff --git a/0519-random-flip-matrix.js b/0519-random-flip-matrix.js new file mode 100644 index 00000000..03edb7e7 --- /dev/null +++ b/0519-random-flip-matrix.js @@ -0,0 +1,47 @@ +/** + * 519. Random Flip Matrix + * https://leetcode.com/problems/random-flip-matrix/ + * Difficulty: Medium + * + * There is an m x n binary grid matrix with all the values set 0 initially. Design an algorithm + * to randomly pick an index (i, j) where matrix[i][j] == 0 and flips it to 1. All the indices + * (i, j) where matrix[i][j] == 0 should be equally likely to be returned. + * + * Optimize your algorithm to minimize the number of calls made to the built-in random function + * of your language and optimize the time and space complexity. + * + * Implement the Solution class: + * - Solution(int m, int n) Initializes the object with the size of the binary matrix m and n. + * - int[] flip() Returns a random index [i, j] of the matrix where matrix[i][j] == 0 and flips + * it to 1. + * - void reset() Resets all the values of the matrix to be 0. + */ + +/** + * @param {number} m + * @param {number} n + */ +var Solution = function(m, n) { + this.m = m; + this.n = n; + this.total = m * n; + this.flipped = new Map(); +}; + +/** + * @return {number[]} + */ +Solution.prototype.flip = function() { + const index = Math.floor(Math.random() * this.total--); + const result = this.flipped.get(index) ?? index; + this.flipped.set(index, this.flipped.get(this.total) ?? this.total); + return [Math.floor(result / this.n), result % this.n]; +}; + +/** + * @return {void} + */ +Solution.prototype.reset = function() { + this.total = this.m * this.n; + this.flipped.clear(); +}; diff --git a/README.md b/README.md index e11869e4..63ba7db6 100644 --- a/README.md +++ b/README.md @@ -415,6 +415,7 @@ 516|[Longest Palindromic Subsequence](./0516-longest-palindromic-subsequence.js)|Medium| 517|[Super Washing Machines](./0517-super-washing-machines.js)|Hard| 518|[Coin Change II](./0518-coin-change-ii.js)|Medium| +519|[Random Flip Matrix](./0519-random-flip-matrix.js)|Medium| 520|[Detect Capital](./0520-detect-capital.js)|Easy| 521|[Longest Uncommon Subsequence I](./0521-longest-uncommon-subsequence-i.js)|Easy| 530|[Minimum Absolute Difference in BST](./0530-minimum-absolute-difference-in-bst.js)|Easy| From 18d49f8e54248300d98c89dc0ea52334941e23db Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 5 Mar 2025 00:41:34 -0600 Subject: [PATCH 795/919] Add solution #2579 --- 2579-count-total-number-of-colored-cells.js | 21 +++++++++++++++++++++ README.md | 1 + 2 files changed, 22 insertions(+) create mode 100644 2579-count-total-number-of-colored-cells.js diff --git a/2579-count-total-number-of-colored-cells.js b/2579-count-total-number-of-colored-cells.js new file mode 100644 index 00000000..6727bfb3 --- /dev/null +++ b/2579-count-total-number-of-colored-cells.js @@ -0,0 +1,21 @@ +/** + * 2579. Count Total Number of Colored Cells + * https://leetcode.com/problems/count-total-number-of-colored-cells/ + * Difficulty: Medium + * + * There exists an infinitely large two-dimensional grid of uncolored unit cells. + * You are given a positive integer n, indicating that you must do the following + * routine for n minutes: + * - At the first minute, color any arbitrary unit cell blue. + * - Every minute thereafter, color blue every uncolored cell that touches a blue cell. + * + * Below is a pictorial representation of the state of the grid after minutes 1, 2, and 3. + */ + +/** + * @param {number} n + * @return {number} + */ +var coloredCells = function(n) { + return 1 + 2 * n * (n - 1); +}; diff --git a/README.md b/README.md index 63ba7db6..b60f12d7 100644 --- a/README.md +++ b/README.md @@ -711,6 +711,7 @@ 2535|[Difference Between Element Sum and Digit Sum of an Array](./2535-difference-between-element-sum-and-digit-sum-of-an-array.js)|Easy| 2542|[Maximum Subsequence Score](./2542-maximum-subsequence-score.js)|Medium| 2570|[Merge Two 2D Arrays by Summing Values](./2570-merge-two-2d-arrays-by-summing-values.js)|Easy| +2579|[Count Total Number of Colored Cells](./2579-count-total-number-of-colored-cells.js)|Medium| 2618|[Check if Object Instance of Class](./2618-check-if-object-instance-of-class.js)|Medium| 2619|[Array Prototype Last](./2619-array-prototype-last.js)|Easy| 2620|[Counter](./2620-counter.js)|Easy| From 9166260d3a13ebb01ae9eda13c6f18e81ded53bf Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 5 Mar 2025 00:42:35 -0600 Subject: [PATCH 796/919] Add solution #522 --- 0522-longest-uncommon-subsequence-ii.js | 50 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 51 insertions(+) create mode 100644 0522-longest-uncommon-subsequence-ii.js diff --git a/0522-longest-uncommon-subsequence-ii.js b/0522-longest-uncommon-subsequence-ii.js new file mode 100644 index 00000000..0dd63297 --- /dev/null +++ b/0522-longest-uncommon-subsequence-ii.js @@ -0,0 +1,50 @@ +/** + * 522. Longest Uncommon Subsequence II + * https://leetcode.com/problems/longest-uncommon-subsequence-ii/ + * Difficulty: Medium + * + * Given an array of strings strs, return the length of the longest uncommon subsequence + * between them. If the longest uncommon subsequence does not exist, return -1. + * + * An uncommon subsequence between an array of strings is a string that is a subsequence + * of one string but not the others. + * + * A subsequence of a string s is a string that can be obtained after deleting any number + * of characters from s. + * + * For example, "abc" is a subsequence of "aebdc" because you can delete the underlined + * characters in "aebdc" to get "abc". Other subsequences of "aebdc" include "aebdc", + * "aeb", and "" (empty string). + */ + +/** + * @param {string[]} strs + * @return {number} + */ +var findLUSlength = function(strs) { + strs.sort((a, b) => b.length - a.length); + + for (let i = 0; i < strs.length; i++) { + let isUnique = true; + for (let j = 0; j < strs.length; j++) { + if (i !== j && isSubsequence(strs[i], strs[j])) { + isUnique = false; + break; + } + } + if (isUnique) { + return strs[i].length; + } + } + + return -1; + + function isSubsequence(s1, s2) { + let index = 0; + for (const char of s2) { + if (char === s1[index]) index++; + if (index === s1.length) return true; + } + return false; + } +}; diff --git a/README.md b/README.md index b60f12d7..6db15431 100644 --- a/README.md +++ b/README.md @@ -418,6 +418,7 @@ 519|[Random Flip Matrix](./0519-random-flip-matrix.js)|Medium| 520|[Detect Capital](./0520-detect-capital.js)|Easy| 521|[Longest Uncommon Subsequence I](./0521-longest-uncommon-subsequence-i.js)|Easy| +522|[Longest Uncommon Subsequence II](./0522-longest-uncommon-subsequence-ii.js)|Medium| 530|[Minimum Absolute Difference in BST](./0530-minimum-absolute-difference-in-bst.js)|Easy| 541|[Reverse String II](./0541-reverse-string-ii.js)|Easy| 542|[01 Matrix](./0542-01-matrix.js)|Medium| From 733d76e190e9e2b2a10e63efe595d205ede22592 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 5 Mar 2025 00:43:52 -0600 Subject: [PATCH 797/919] Add solution #523 --- 0523-continuous-subarray-sum.js | 43 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 44 insertions(+) create mode 100644 0523-continuous-subarray-sum.js diff --git a/0523-continuous-subarray-sum.js b/0523-continuous-subarray-sum.js new file mode 100644 index 00000000..21b57dc2 --- /dev/null +++ b/0523-continuous-subarray-sum.js @@ -0,0 +1,43 @@ +/** + * 523. Continuous Subarray Sum + * https://leetcode.com/problems/continuous-subarray-sum/ + * Difficulty: Medium + * + * Given an integer array nums and an integer k, return true if nums has a good subarray + * or false otherwise. + * + * A good subarray is a subarray where: + * - its length is at least two, and + * - the sum of the elements of the subarray is a multiple of k. + * + * Note that: + * - A subarray is a contiguous part of the array. + * - An integer x is a multiple of k if there exists an integer n such that x = n * k. + * 0 is always a multiple of k. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {boolean} + */ +var checkSubarraySum = function(nums, k) { + const map = new Map([[0, -1]]); + + for (let i = 0, sum = 0; i < nums.length; i++) { + sum += nums[i]; + if (k !== 0) { + sum = sum % k; + } + + if (map.has(sum)) { + if (i - map.get(sum) >= 2) { + return true; + } + } else { + map.set(sum, i); + } + } + + return false; +}; diff --git a/README.md b/README.md index 6db15431..d6bb9ae9 100644 --- a/README.md +++ b/README.md @@ -419,6 +419,7 @@ 520|[Detect Capital](./0520-detect-capital.js)|Easy| 521|[Longest Uncommon Subsequence I](./0521-longest-uncommon-subsequence-i.js)|Easy| 522|[Longest Uncommon Subsequence II](./0522-longest-uncommon-subsequence-ii.js)|Medium| +523|[Continuous Subarray Sum](./0523-continuous-subarray-sum.js)|Medium| 530|[Minimum Absolute Difference in BST](./0530-minimum-absolute-difference-in-bst.js)|Easy| 541|[Reverse String II](./0541-reverse-string-ii.js)|Easy| 542|[01 Matrix](./0542-01-matrix.js)|Medium| From d27c5ce1b42144dcb589bc04e914c692e6f9a0d8 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 5 Mar 2025 00:44:38 -0600 Subject: [PATCH 798/919] Add solution #524 --- ...est-word-in-dictionary-through-deleting.js | 28 +++++++++++++++++++ README.md | 1 + 2 files changed, 29 insertions(+) create mode 100644 0524-longest-word-in-dictionary-through-deleting.js diff --git a/0524-longest-word-in-dictionary-through-deleting.js b/0524-longest-word-in-dictionary-through-deleting.js new file mode 100644 index 00000000..ee0dee1e --- /dev/null +++ b/0524-longest-word-in-dictionary-through-deleting.js @@ -0,0 +1,28 @@ +/** + * 524. Longest Word in Dictionary through Deleting + * https://leetcode.com/problems/longest-word-in-dictionary-through-deleting/ + * Difficulty: Medium + * + * Given a string s and a string array dictionary, return the longest string in the dictionary + * that can be formed by deleting some of the given string characters. If there is more than + * one possible result, return the longest word with the smallest lexicographical order. + * If there is no possible result, return the empty string. + */ + +/** + * @param {string} s + * @param {string[]} dictionary + * @return {string} + */ +var findLongestWord = function(s, dictionary) { + return dictionary + .sort((a, b) => a.length === b.length ? a.localeCompare(b) : b.length - a.length) + .find(word => { + let i = 0; + for (const character of s) { + if (character === word[i]) i++; + if (i === word.length) return true; + } + return false; + }) || ''; +}; diff --git a/README.md b/README.md index d6bb9ae9..b2a3940b 100644 --- a/README.md +++ b/README.md @@ -420,6 +420,7 @@ 521|[Longest Uncommon Subsequence I](./0521-longest-uncommon-subsequence-i.js)|Easy| 522|[Longest Uncommon Subsequence II](./0522-longest-uncommon-subsequence-ii.js)|Medium| 523|[Continuous Subarray Sum](./0523-continuous-subarray-sum.js)|Medium| +524|[Longest Word in Dictionary through Deleting](./0524-longest-word-in-dictionary-through-deleting.js)|Medium| 530|[Minimum Absolute Difference in BST](./0530-minimum-absolute-difference-in-bst.js)|Easy| 541|[Reverse String II](./0541-reverse-string-ii.js)|Easy| 542|[01 Matrix](./0542-01-matrix.js)|Medium| From 7fe444cfc9ff6e90ebaa4318f2bc4ef5cd95b09c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 5 Mar 2025 00:45:11 -0600 Subject: [PATCH 799/919] Add solution #525 --- 0525-contiguous-array.js | 28 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 29 insertions(+) create mode 100644 0525-contiguous-array.js diff --git a/0525-contiguous-array.js b/0525-contiguous-array.js new file mode 100644 index 00000000..eef44899 --- /dev/null +++ b/0525-contiguous-array.js @@ -0,0 +1,28 @@ +/** + * 525. Contiguous Array + * https://leetcode.com/problems/contiguous-array/ + * Difficulty: Medium + * + * Given a binary array nums, return the maximum length of a contiguous subarray + * with an equal number of 0 and 1. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var findMaxLength = function(nums) { + const map = new Map([[0, -1]]); + let result = 0; + + for (let i = 0, count = 0; i < nums.length; i++) { + count += nums[i] === 1 ? 1 : -1; + if (map.has(count)) { + result = Math.max(result, i - map.get(count)); + } else { + map.set(count, i); + } + } + + return result; +}; diff --git a/README.md b/README.md index b2a3940b..8c8a3487 100644 --- a/README.md +++ b/README.md @@ -421,6 +421,7 @@ 522|[Longest Uncommon Subsequence II](./0522-longest-uncommon-subsequence-ii.js)|Medium| 523|[Continuous Subarray Sum](./0523-continuous-subarray-sum.js)|Medium| 524|[Longest Word in Dictionary through Deleting](./0524-longest-word-in-dictionary-through-deleting.js)|Medium| +525|[Contiguous Array](./0525-contiguous-array.js)|Medium| 530|[Minimum Absolute Difference in BST](./0530-minimum-absolute-difference-in-bst.js)|Easy| 541|[Reverse String II](./0541-reverse-string-ii.js)|Easy| 542|[01 Matrix](./0542-01-matrix.js)|Medium| From 1461289a3f5bd0923edd2cabe377e1bc51cef1be Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 5 Mar 2025 00:54:46 -0600 Subject: [PATCH 800/919] Add solution #526 --- 0526-beautiful-arrangement.js | 35 +++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 36 insertions(+) create mode 100644 0526-beautiful-arrangement.js diff --git a/0526-beautiful-arrangement.js b/0526-beautiful-arrangement.js new file mode 100644 index 00000000..0fd536f7 --- /dev/null +++ b/0526-beautiful-arrangement.js @@ -0,0 +1,35 @@ +/** + * 526. Beautiful Arrangement + * https://leetcode.com/problems/beautiful-arrangement/ + * Difficulty: Medium + * + * Suppose you have n integers labeled 1 through n. A permutation of those n integers perm + * (1-indexed) is considered a beautiful arrangement if for every i (1 <= i <= n), either + * of the following is true: + * - perm[i] is divisible by i. + * - i is divisible by perm[i]. + * + * Given an integer n, return the number of the beautiful arrangements that you can construct. + */ + +/** + * @param {number} n + * @return {number} + */ +var countArrangement = function(n) { + let count = 0; + backtrack(1, 0); + return count; + + function backtrack(offset, used) { + if (offset > n) { + count++; + return; + } + for (let i = 1; i <= n; i++) { + if (!(used & (1 << i)) && (i % offset === 0 || offset % i === 0)) { + backtrack(offset + 1, used | (1 << i)); + } + } + } +}; diff --git a/README.md b/README.md index 8c8a3487..838863d6 100644 --- a/README.md +++ b/README.md @@ -422,6 +422,7 @@ 523|[Continuous Subarray Sum](./0523-continuous-subarray-sum.js)|Medium| 524|[Longest Word in Dictionary through Deleting](./0524-longest-word-in-dictionary-through-deleting.js)|Medium| 525|[Contiguous Array](./0525-contiguous-array.js)|Medium| +526|[Beautiful Arrangement](./0526-beautiful-arrangement.js)|Medium| 530|[Minimum Absolute Difference in BST](./0530-minimum-absolute-difference-in-bst.js)|Easy| 541|[Reverse String II](./0541-reverse-string-ii.js)|Easy| 542|[01 Matrix](./0542-01-matrix.js)|Medium| From 0f4f470e2fb92565a7b175f26da18772fb6a4170 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 5 Mar 2025 00:55:42 -0600 Subject: [PATCH 801/919] Add solution #528 --- 0528-random-pick-with-weight.js | 46 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 47 insertions(+) create mode 100644 0528-random-pick-with-weight.js diff --git a/0528-random-pick-with-weight.js b/0528-random-pick-with-weight.js new file mode 100644 index 00000000..26555599 --- /dev/null +++ b/0528-random-pick-with-weight.js @@ -0,0 +1,46 @@ +/** + * 528. Random Pick with Weight + * https://leetcode.com/problems/random-pick-with-weight/ + * Difficulty: Medium + * + * You are given a 0-indexed array of positive integers w where w[i] describes the + * weight of the ith index. + * + * You need to implement the function pickIndex(), which randomly picks an index in + * the range [0, w.length - 1] (inclusive) and returns it. The probability of picking + * an index i is w[i] / sum(w). + * + * For example, if w = [1, 3], the probability of picking index 0 is 1 / (1 + 3) = 0.25 + * (i.e., 25%), and the probability of picking index 1 is 3 / (1 + 3) = 0.75 (i.e., 75%). + */ + +/** + * @param {number[]} w + */ +var Solution = function(w) { + this.sums = []; + let sum = 0; + for (const weight of w) { + sum += weight; + this.sums.push(sum); + } + this.total = sum; +}; + +/** + * @return {number} + */ +Solution.prototype.pickIndex = function() { + const target = Math.random() * this.total; + let left = 0; + let right = this.sums.length - 1; + while (left < right) { + const mid = Math.floor((left + right) / 2); + if (this.sums[mid] <= target) { + left = mid + 1; + } else { + right = mid; + } + } + return left; +}; diff --git a/README.md b/README.md index 838863d6..e6ee9349 100644 --- a/README.md +++ b/README.md @@ -423,6 +423,7 @@ 524|[Longest Word in Dictionary through Deleting](./0524-longest-word-in-dictionary-through-deleting.js)|Medium| 525|[Contiguous Array](./0525-contiguous-array.js)|Medium| 526|[Beautiful Arrangement](./0526-beautiful-arrangement.js)|Medium| +528|[Random Pick with Weight](./0528-random-pick-with-weight.js)|Medium| 530|[Minimum Absolute Difference in BST](./0530-minimum-absolute-difference-in-bst.js)|Easy| 541|[Reverse String II](./0541-reverse-string-ii.js)|Easy| 542|[01 Matrix](./0542-01-matrix.js)|Medium| From ebbd6dd19682c39748a2afcb9d28d4abed9d6525 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 5 Mar 2025 00:57:59 -0600 Subject: [PATCH 802/919] Add solution #529 --- 0529-minesweeper.js | 68 +++++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 69 insertions(+) create mode 100644 0529-minesweeper.js diff --git a/0529-minesweeper.js b/0529-minesweeper.js new file mode 100644 index 00000000..15d5e851 --- /dev/null +++ b/0529-minesweeper.js @@ -0,0 +1,68 @@ +/** + * 529. Minesweeper + * https://leetcode.com/problems/minesweeper/ + * Difficulty: Medium + * + * Let's play the minesweeper game (Wikipedia, online game)! + * + * You are given an m x n char matrix board representing the game board where: + * - 'M' represents an unrevealed mine, + * - 'E' represents an unrevealed empty square, + * - 'B' represents a revealed blank square that has no adjacent mines (i.e., above, below, + * left, right, and all 4 diagonals), + * - digit ('1' to '8') represents how many mines are adjacent to this revealed square, and + * - 'X' represents a revealed mine. + * + * You are also given an integer array click where click = [clickr, clickc] represents the + * next click position among all the unrevealed squares ('M' or 'E'). + * + * Return the board after revealing this position according to the following rules: + * 1. If a mine 'M' is revealed, then the game is over. You should change it to 'X'. + * 2. If an empty square 'E' with no adjacent mines is revealed, then change it to a revealed + * blank 'B' and all of its adjacent unrevealed squares should be revealed recursively. + * 3. If an empty square 'E' with at least one adjacent mine is revealed, then change it to a + * digit ('1' to '8') representing the number of adjacent mines. + * 4. Return the board when no more squares will be revealed. + */ + +/** + * @param {character[][]} board + * @param {number[]} click + * @return {character[][]} + */ +var updateBoard = function(board, click) { + const [row, col] = click; + const rows = board.length; + const cols = board[0].length; + const directions = [ + [-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1] + ]; + + if (board[row][col] === 'M') { + board[row][col] = 'X'; + return board; + } + + dfs(row, col); + return board; + + function dfs(r, c) { + if (r < 0 || r >= rows || c < 0 || c >= cols || board[r][c] !== 'E') return; + + let mines = 0; + for (const [dr, dc] of directions) { + const nr = r + dr; + const nc = c + dc; + if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && board[nr][nc] === 'M') { + mines++; + } + } + + board[r][c] = mines > 0 ? mines.toString() : 'B'; + if (mines === 0) { + for (const [dr, dc] of directions) { + dfs(r + dr, c + dc); + } + } + } +}; diff --git a/README.md b/README.md index e6ee9349..e8c8ee3c 100644 --- a/README.md +++ b/README.md @@ -424,6 +424,7 @@ 525|[Contiguous Array](./0525-contiguous-array.js)|Medium| 526|[Beautiful Arrangement](./0526-beautiful-arrangement.js)|Medium| 528|[Random Pick with Weight](./0528-random-pick-with-weight.js)|Medium| +529|[Minesweeper](./0529-minesweeper.js)|Medium| 530|[Minimum Absolute Difference in BST](./0530-minimum-absolute-difference-in-bst.js)|Easy| 541|[Reverse String II](./0541-reverse-string-ii.js)|Easy| 542|[01 Matrix](./0542-01-matrix.js)|Medium| From e14190884b598e9511cfb23647f2db388f05863a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 5 Mar 2025 00:59:39 -0600 Subject: [PATCH 803/919] Add solution #532 --- 0532-k-diff-pairs-in-an-array.js | 42 ++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 43 insertions(+) create mode 100644 0532-k-diff-pairs-in-an-array.js diff --git a/0532-k-diff-pairs-in-an-array.js b/0532-k-diff-pairs-in-an-array.js new file mode 100644 index 00000000..769ca6f8 --- /dev/null +++ b/0532-k-diff-pairs-in-an-array.js @@ -0,0 +1,42 @@ +/** + * 532. K-diff Pairs in an Array + * https://leetcode.com/problems/k-diff-pairs-in-an-array/ + * Difficulty: Medium + * + * Given an array of integers nums and an integer k, return the number of unique k-diff + * pairs in the array. + * + * A k-diff pair is an integer pair (nums[i], nums[j]), where the following are true: + * - 0 <= i, j < nums.length + * - i != j + * - |nums[i] - nums[j]| == k + * + * Notice that |val| denotes the absolute value of val. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var findPairs = function(nums, k) { + const map = new Map(); + let result = 0; + + for (const num of nums) { + if (!map.has(num)) { + if (!k) { + map.set(num, 1); + } else { + if (map.has(num - k)) result++; + if (map.has(num + k)) result++; + map.set(num, 1); + } + } else if (!k && map.get(num) === 1) { + result++; + map.set(num, 2); + } + } + + return result; +}; diff --git a/README.md b/README.md index e8c8ee3c..53630d05 100644 --- a/README.md +++ b/README.md @@ -426,6 +426,7 @@ 528|[Random Pick with Weight](./0528-random-pick-with-weight.js)|Medium| 529|[Minesweeper](./0529-minesweeper.js)|Medium| 530|[Minimum Absolute Difference in BST](./0530-minimum-absolute-difference-in-bst.js)|Easy| +532|[K-diff Pairs in an Array](./0532-k-diff-pairs-in-an-array.js)|Medium| 541|[Reverse String II](./0541-reverse-string-ii.js)|Easy| 542|[01 Matrix](./0542-01-matrix.js)|Medium| 543|[Diameter of Binary Tree](./0543-diameter-of-binary-tree.js)|Easy| From 982a000b0d7d8590d8a608a471ec9f69b6c024d1 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 5 Mar 2025 01:00:13 -0600 Subject: [PATCH 804/919] Add solution #537 --- 0537-complex-number-multiplication.js | 24 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 0537-complex-number-multiplication.js diff --git a/0537-complex-number-multiplication.js b/0537-complex-number-multiplication.js new file mode 100644 index 00000000..ad2697f6 --- /dev/null +++ b/0537-complex-number-multiplication.js @@ -0,0 +1,24 @@ +/** + * 537. Complex Number Multiplication + * https://leetcode.com/problems/complex-number-multiplication/ + * Difficulty: Medium + * + * A complex number can be represented as a string on the form "real+imaginaryi" where: + * - real is the real part and is an integer in the range [-100, 100]. + * - imaginary is the imaginary part and is an integer in the range [-100, 100]. + * - i2 == -1. + * + * Given two complex numbers num1 and num2 as strings, return a string of the complex number + * that represents their multiplications. + */ + +/** + * @param {string} num1 + * @param {string} num2 + * @return {string} + */ +var complexNumberMultiply = function(num1, num2) { + const [r1, i1] = num1.split('+').map(n => parseInt(n.replace('i', ''))); + const [r2, i2] = num2.split('+').map(n => parseInt(n.replace('i', ''))); + return `${r1 * r2 - i1 * i2}+${r1 * i2 + r2 * i1}i`; +}; diff --git a/README.md b/README.md index 53630d05..6cbffbce 100644 --- a/README.md +++ b/README.md @@ -427,6 +427,7 @@ 529|[Minesweeper](./0529-minesweeper.js)|Medium| 530|[Minimum Absolute Difference in BST](./0530-minimum-absolute-difference-in-bst.js)|Easy| 532|[K-diff Pairs in an Array](./0532-k-diff-pairs-in-an-array.js)|Medium| +537|[Complex Number Multiplication](./0537-complex-number-multiplication.js)|Medium| 541|[Reverse String II](./0541-reverse-string-ii.js)|Easy| 542|[01 Matrix](./0542-01-matrix.js)|Medium| 543|[Diameter of Binary Tree](./0543-diameter-of-binary-tree.js)|Easy| From 42579a80c0c92bb21f99d869618b14c72259cd15 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 5 Mar 2025 01:09:51 -0600 Subject: [PATCH 805/919] Add solution #1038 --- ...-binary-search-tree-to-greater-sum-tree.js | 40 +++++++++++++++++++ README.md | 1 + 2 files changed, 41 insertions(+) create mode 100644 1038-binary-search-tree-to-greater-sum-tree.js diff --git a/1038-binary-search-tree-to-greater-sum-tree.js b/1038-binary-search-tree-to-greater-sum-tree.js new file mode 100644 index 00000000..0617d146 --- /dev/null +++ b/1038-binary-search-tree-to-greater-sum-tree.js @@ -0,0 +1,40 @@ +/** + * 1038. Binary Search Tree to Greater Sum Tree + * https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/ + * Difficulty: Medium + * + * Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every + * key of the original BST is changed to the original key plus the sum of all keys greater + * than the original key in BST. + * + * As a reminder, a binary search tree is a tree that satisfies these constraints: + * - The left subtree of a node contains only nodes with keys less than the node's key. + * - The right subtree of a node contains only nodes with keys greater than the node's key. + * - Both the left and right subtrees must also be binary search trees. + */ + +/** + * 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 bstToGst = function(root) { + let sum = 0; + traverse(root); + return root; + + function traverse(node) { + if (!node) return; + traverse(node.right); + sum += node.val; + node.val = sum; + traverse(node.left); + } +}; diff --git a/README.md b/README.md index 6cbffbce..d46fc341 100644 --- a/README.md +++ b/README.md @@ -540,6 +540,7 @@ 1023|[Camelcase Matching](./1023-camelcase-matching.js)|Medium| 1028|[Recover a Tree From Preorder Traversal](./1028-recover-a-tree-from-preorder-traversal.js)|Hard| 1037|[Valid Boomerang](./1037-valid-boomerang.js)|Easy| +1038|[Binary Search Tree to Greater Sum Tree](./1038-binary-search-tree-to-greater-sum-tree.js)|Medium| 1041|[Robot Bounded In Circle](./1041-robot-bounded-in-circle.js)|Medium| 1047|[Remove All Adjacent Duplicates In String](./1047-remove-all-adjacent-duplicates-in-string.js)|Easy| 1051|[Height Checker](./1051-height-checker.js)|Easy| From 56e5193d4b44e7baa0d0be93564dc896c24735cb Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 5 Mar 2025 01:10:50 -0600 Subject: [PATCH 806/919] Add solution #538 --- 0538-convert-bst-to-greater-tree.js | 40 +++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 41 insertions(+) create mode 100644 0538-convert-bst-to-greater-tree.js diff --git a/0538-convert-bst-to-greater-tree.js b/0538-convert-bst-to-greater-tree.js new file mode 100644 index 00000000..ce8499f8 --- /dev/null +++ b/0538-convert-bst-to-greater-tree.js @@ -0,0 +1,40 @@ +/** + * 538. Convert BST to Greater Tree + * https://leetcode.com/problems/convert-bst-to-greater-tree/ + * Difficulty: Medium + * + * Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every + * key of the original BST is changed to the original key plus the sum of all keys greater + * than the original key in BST. + * + * As a reminder, a binary search tree is a tree that satisfies these constraints: + * - The left subtree of a node contains only nodes with keys less than the node's key. + * - The right subtree of a node contains only nodes with keys greater than the node's key. + * - Both the left and right subtrees must also be binary search trees. + */ + +/** + * 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 convertBST = function(root) { + let sum = 0; + traverse(root); + return root; + + function traverse(node) { + if (!node) return; + traverse(node.right); + sum += node.val; + node.val = sum; + traverse(node.left); + } +}; diff --git a/README.md b/README.md index d46fc341..6ee66921 100644 --- a/README.md +++ b/README.md @@ -428,6 +428,7 @@ 530|[Minimum Absolute Difference in BST](./0530-minimum-absolute-difference-in-bst.js)|Easy| 532|[K-diff Pairs in an Array](./0532-k-diff-pairs-in-an-array.js)|Medium| 537|[Complex Number Multiplication](./0537-complex-number-multiplication.js)|Medium| +538|[Convert BST to Greater Tree](./0538-convert-bst-to-greater-tree.js)|Medium| 541|[Reverse String II](./0541-reverse-string-ii.js)|Easy| 542|[01 Matrix](./0542-01-matrix.js)|Medium| 543|[Diameter of Binary Tree](./0543-diameter-of-binary-tree.js)|Easy| From 28b185148d7bda63a5024faab21d6244640ecfcd Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 5 Mar 2025 01:11:26 -0600 Subject: [PATCH 807/919] Add solution #539 --- 0539-minimum-time-difference.js | 26 ++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 27 insertions(+) create mode 100644 0539-minimum-time-difference.js diff --git a/0539-minimum-time-difference.js b/0539-minimum-time-difference.js new file mode 100644 index 00000000..717c9a73 --- /dev/null +++ b/0539-minimum-time-difference.js @@ -0,0 +1,26 @@ +/** + * 539. Minimum Time Difference + * https://leetcode.com/problems/minimum-time-difference/ + * Difficulty: Medium + * + * Given a list of 24-hour clock time points in "HH:MM" format, return the minimum minutes + * difference between any two time-points in the list. + */ + +/** + * @param {string[]} timePoints + * @return {number} + */ +var findMinDifference = function(timePoints) { + const minutes = timePoints.map(time => { + const [h, m] = time.split(':').map(Number); + return h * 60 + m; + }).sort((a, b) => a - b); + let diff = Infinity; + + for (let i = 1; i < minutes.length; i++) { + diff = Math.min(diff, minutes[i] - minutes[i - 1]); + } + + return Math.min(diff, 1440 - minutes[minutes.length - 1] + minutes[0]); +}; diff --git a/README.md b/README.md index 6ee66921..9186920f 100644 --- a/README.md +++ b/README.md @@ -429,6 +429,7 @@ 532|[K-diff Pairs in an Array](./0532-k-diff-pairs-in-an-array.js)|Medium| 537|[Complex Number Multiplication](./0537-complex-number-multiplication.js)|Medium| 538|[Convert BST to Greater Tree](./0538-convert-bst-to-greater-tree.js)|Medium| +539|[Minimum Time Difference](./0539-minimum-time-difference.js)|Medium| 541|[Reverse String II](./0541-reverse-string-ii.js)|Easy| 542|[01 Matrix](./0542-01-matrix.js)|Medium| 543|[Diameter of Binary Tree](./0543-diameter-of-binary-tree.js)|Easy| From 51489ba190e3c5b2bbfbf7c68c8a206c43208a83 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 5 Mar 2025 01:12:11 -0600 Subject: [PATCH 808/919] Add solution #540 --- 0540-single-element-in-a-sorted-array.js | 33 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 0540-single-element-in-a-sorted-array.js diff --git a/0540-single-element-in-a-sorted-array.js b/0540-single-element-in-a-sorted-array.js new file mode 100644 index 00000000..f3996dca --- /dev/null +++ b/0540-single-element-in-a-sorted-array.js @@ -0,0 +1,33 @@ +/** + * 540. Single Element in a Sorted Array + * https://leetcode.com/problems/single-element-in-a-sorted-array/ + * Difficulty: Medium + * + * You are given a sorted array consisting of only integers where every element appears + * exactly twice, except for one element which appears exactly once. + * + * Return the single element that appears only once. + * + * Your solution must run in O(log n) time and O(1) space. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var singleNonDuplicate = function(nums) { + let left = 0; + let right = nums.length - 1; + + while (left < right) { + let middle = left + Math.floor((right - left) / 2); + middle = middle - (middle % 2); + if (nums[middle] === nums[middle + 1]) { + left = middle + 2; + } else { + right = middle; + } + } + + return nums[left]; +}; diff --git a/README.md b/README.md index 9186920f..547cce46 100644 --- a/README.md +++ b/README.md @@ -430,6 +430,7 @@ 537|[Complex Number Multiplication](./0537-complex-number-multiplication.js)|Medium| 538|[Convert BST to Greater Tree](./0538-convert-bst-to-greater-tree.js)|Medium| 539|[Minimum Time Difference](./0539-minimum-time-difference.js)|Medium| +540|[Single Element in a Sorted Array](./0540-single-element-in-a-sorted-array.js)|Medium| 541|[Reverse String II](./0541-reverse-string-ii.js)|Easy| 542|[01 Matrix](./0542-01-matrix.js)|Medium| 543|[Diameter of Binary Tree](./0543-diameter-of-binary-tree.js)|Easy| From b525dfd9d330103c01053682f5cdd53cb59219bc Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 5 Mar 2025 01:13:09 -0600 Subject: [PATCH 809/919] Add solution #546 --- 0546-remove-boxes.js | 42 ++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 43 insertions(+) create mode 100644 0546-remove-boxes.js diff --git a/0546-remove-boxes.js b/0546-remove-boxes.js new file mode 100644 index 00000000..c13f21eb --- /dev/null +++ b/0546-remove-boxes.js @@ -0,0 +1,42 @@ +/** + * 546. Remove Boxes + * https://leetcode.com/problems/remove-boxes/ + * Difficulty: Hard + * + * You are given several boxes with different colors represented by different positive numbers. + * + * You may experience several rounds to remove boxes until there is no box left. Each time you + * can choose some continuous boxes with the same color (i.e., composed of k boxes, k >= 1), + * remove them and get k * k points. + * + * Return the maximum points you can get. + */ + +/** + * @param {number[]} boxes + * @return {number} + */ +var removeBoxes = function(boxes) { + const dp = new Array(boxes.length).fill().map(() => { + return new Array(boxes.length).fill().map(() => new Array(boxes.length + 1).fill(0)); + }); + return dfs(0, boxes.length - 1, 0); + + function dfs(l, r, k) { + if (l > r) return 0; + if (dp[l][r][k]) return dp[l][r][k]; + let i = l; + let count = k + 1; + while (i < r && boxes[i] === boxes[i + 1]) { + i++; + count++; + } + let max = count * count + dfs(i + 1, r, 0); + for (let m = i + 1; m <= r; m++) { + if (boxes[l] === boxes[m]) { + max = Math.max(max, dfs(i + 1, m - 1, 0) + dfs(m, r, count)); + } + } + return dp[l][r][k] = max; + } +}; diff --git a/README.md b/README.md index 547cce46..b58ec19a 100644 --- a/README.md +++ b/README.md @@ -434,6 +434,7 @@ 541|[Reverse String II](./0541-reverse-string-ii.js)|Easy| 542|[01 Matrix](./0542-01-matrix.js)|Medium| 543|[Diameter of Binary Tree](./0543-diameter-of-binary-tree.js)|Easy| +546|[Remove Boxes](./0546-remove-boxes.js)|Hard| 547|[Number of Provinces](./0547-number-of-provinces.js)|Medium| 551|[Student Attendance Record I](./0551-student-attendance-record-i.js)|Easy| 557|[Reverse Words in a String III](./0557-reverse-words-in-a-string-iii.js)|Easy| From 2308cc451fb321abd782891b1e0d3f051512b984 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 5 Mar 2025 20:19:47 -0600 Subject: [PATCH 810/919] Add solution #2965 --- 2965-find-missing-and-repeated-values.js | 22 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 2965-find-missing-and-repeated-values.js diff --git a/2965-find-missing-and-repeated-values.js b/2965-find-missing-and-repeated-values.js new file mode 100644 index 00000000..c45f7c09 --- /dev/null +++ b/2965-find-missing-and-repeated-values.js @@ -0,0 +1,22 @@ +/** + * 2965. Find Missing and Repeated Values + * https://leetcode.com/problems/find-missing-and-repeated-values/ + * Difficulty: Easy + * + * You are given a 0-indexed 2D integer matrix grid of size n * n with values in the range [1, n2]. + * Each integer appears exactly once except a which appears twice and b which is missing. The task + * is to find the repeating and missing numbers a and b. + * + * Return a 0-indexed integer array ans of size 2 where ans[0] equals to a and ans[1] equals to b. + */ + +/** + * @param {number[][]} grid + * @return {number[]} + */ +var findMissingAndRepeatedValues = function(grid) { + const sum = grid.flat().reduce((a, b) => a + b, 0); + const expectedSum = (grid.length * grid.length * (grid.length * grid.length + 1)) / 2; + const repeated = sum - [...new Set(grid.flat())].reduce((a, b) => a + b, 0); + return [repeated, expectedSum - sum + repeated]; +}; diff --git a/README.md b/README.md index b58ec19a..3f914509 100644 --- a/README.md +++ b/README.md @@ -768,6 +768,7 @@ 2726|[Calculator with Method Chaining](./2726-calculator-with-method-chaining.js)|Easy| 2727|[Is Object Empty](./2727-is-object-empty.js)|Easy| 2948|[Make Lexicographically Smallest Array by Swapping Elements](./2948-make-lexicographically-smallest-array-by-swapping-elements.js)|Medium| +2965|[Find Missing and Repeated Values](./2965-find-missing-and-repeated-values.js)|Easy| 3042|[Count Prefix and Suffix Pairs I](./3042-count-prefix-and-suffix-pairs-i.js)|Easy| 3066|[Minimum Operations to Exceed Threshold Value II](./3066-minimum-operations-to-exceed-threshold-value-ii.js)|Medium| 3105|[Longest Strictly Increasing or Strictly Decreasing Subarray](./3105-longest-strictly-increasing-or-strictly-decreasing-subarray.js)|Easy| From 691cb8dd7d272743a08c90469e30f7b6b7b9db52 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 5 Mar 2025 20:21:04 -0600 Subject: [PATCH 811/919] Add solution #552 --- 0552-student-attendance-record-ii.js | 42 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 43 insertions(+) create mode 100644 0552-student-attendance-record-ii.js diff --git a/0552-student-attendance-record-ii.js b/0552-student-attendance-record-ii.js new file mode 100644 index 00000000..49e65abe --- /dev/null +++ b/0552-student-attendance-record-ii.js @@ -0,0 +1,42 @@ +/** + * 552. Student Attendance Record II + * https://leetcode.com/problems/student-attendance-record-ii/ + * Difficulty: Hard + * + * An attendance record for a student can be represented as a string where each character + * signifies whether the student was absent, late, or present on that day. The record only + * contains the following three characters: + * - 'A': Absent. + * - 'L': Late. + * - 'P': Present. + * + * Any student is eligible for an attendance award if they meet both of the following + * criteria: + * - The student was absent ('A') for strictly fewer than 2 days total. + * - The student was never late ('L') for 3 or more consecutive days. + * + * Given an integer n, return the number of possible attendance records of length n that make + * a student eligible for an attendance award. The answer may be very large, so return it + * modulo 109 + 7. + */ + +/** + * @param {number} n + * @return {number} + */ +var checkRecord = function(n) { + const MOD = 1e9 + 7; + const dp = [[1, 0, 0], [0, 0, 0]]; + + for (let i = 0; i < n; i++) { + const m = dp.map(row => [...row]); + dp[0][0] = (m[0][0] + m[0][1] + m[0][2]) % MOD; + dp[0][1] = m[0][0]; + dp[0][2] = m[0][1]; + dp[1][0] = (m[0][0] + m[0][1] + m[0][2] + m[1][0] + m[1][1] + m[1][2]) % MOD; + dp[1][1] = m[1][0]; + dp[1][2] = m[1][1]; + } + + return (dp[0][0] + dp[0][1] + dp[0][2] + dp[1][0] + dp[1][1] + dp[1][2]) % MOD; +}; diff --git a/README.md b/README.md index 3f914509..18e7c00d 100644 --- a/README.md +++ b/README.md @@ -437,6 +437,7 @@ 546|[Remove Boxes](./0546-remove-boxes.js)|Hard| 547|[Number of Provinces](./0547-number-of-provinces.js)|Medium| 551|[Student Attendance Record I](./0551-student-attendance-record-i.js)|Easy| +552|[Student Attendance Record II](./0552-student-attendance-record-ii.js)|Hard| 557|[Reverse Words in a String III](./0557-reverse-words-in-a-string-iii.js)|Easy| 560|[Subarray Sum Equals K](./0560-subarray-sum-equals-k.js)|Medium| 563|[Binary Tree Tilt](./0563-binary-tree-tilt.js)|Easy| From b08d89a5a920f9255fc1bb24b96d778cd7196e26 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 5 Mar 2025 20:22:41 -0600 Subject: [PATCH 812/919] Add solution #553 --- 0553-optimal-division.js | 27 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 28 insertions(+) create mode 100644 0553-optimal-division.js diff --git a/0553-optimal-division.js b/0553-optimal-division.js new file mode 100644 index 00000000..50c89bb9 --- /dev/null +++ b/0553-optimal-division.js @@ -0,0 +1,27 @@ +/** + * 553. Optimal Division + * https://leetcode.com/problems/optimal-division/ + * Difficulty: Medium + * + * You are given an integer array nums. The adjacent integers in nums will perform + * the float division. + * - For example, for nums = [2,3,4], we will evaluate the expression "2/3/4". + * + * However, you can add any number of parenthesis at any position to change the priority + * of operations. You want to add these parentheses such the value of the expression after + * the evaluation is maximum. + * + * Return the corresponding expression that has the maximum value in string format. + * + * Note: your expression should not contain redundant parenthesis. + */ + +/** + * @param {number[]} nums + * @return {string} + */ +var optimalDivision = function(nums) { + if (nums.length === 1) return nums[0].toString(); + if (nums.length === 2) return `${nums[0]}/${nums[1]}`; + return `${nums[0]}/(${nums.slice(1).join('/')})`; +}; diff --git a/README.md b/README.md index 18e7c00d..7645c993 100644 --- a/README.md +++ b/README.md @@ -438,6 +438,7 @@ 547|[Number of Provinces](./0547-number-of-provinces.js)|Medium| 551|[Student Attendance Record I](./0551-student-attendance-record-i.js)|Easy| 552|[Student Attendance Record II](./0552-student-attendance-record-ii.js)|Hard| +553|[Optimal Division](./0553-optimal-division.js)|Medium| 557|[Reverse Words in a String III](./0557-reverse-words-in-a-string-iii.js)|Easy| 560|[Subarray Sum Equals K](./0560-subarray-sum-equals-k.js)|Medium| 563|[Binary Tree Tilt](./0563-binary-tree-tilt.js)|Easy| From 6ce1c5178abf71847da501be34b26e798f78b0d2 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 5 Mar 2025 20:25:29 -0600 Subject: [PATCH 813/919] Add solution #554 --- 0554-brick-wall.js | 36 ++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 37 insertions(+) create mode 100644 0554-brick-wall.js diff --git a/0554-brick-wall.js b/0554-brick-wall.js new file mode 100644 index 00000000..114c386e --- /dev/null +++ b/0554-brick-wall.js @@ -0,0 +1,36 @@ +/** + * 554. Brick Wall + * https://leetcode.com/problems/brick-wall/ + * Difficulty: Medium + * + * There is a rectangular brick wall in front of you with n rows of bricks. The ith row has + * some number of bricks each of the same height (i.e., one unit) but they can be of different + * widths. The total width of each row is the same. + * + * Draw a vertical line from the top to the bottom and cross the least bricks. If your line + * goes through the edge of a brick, then the brick is not considered as crossed. You cannot + * draw a line just along one of the two vertical edges of the wall, in which case the line + * will obviously cross no bricks. + * + * Given the 2D array wall that contains the information about the wall, return the minimum + * number of crossed bricks after drawing such a vertical line. + */ + +/** + * @param {number[][]} wall + * @return {number} + */ +var leastBricks = function(wall) { + const map = new Map(); + let max = 0; + + for (const row of wall) { + for (let i = 0, sum = 0; i < row.length - 1; i++) { + sum += row[i]; + map.set(sum, (map.get(sum) || 0) + 1); + max = Math.max(max, map.get(sum)); + } + } + + return wall.length - max; +}; diff --git a/README.md b/README.md index 7645c993..603cd7b7 100644 --- a/README.md +++ b/README.md @@ -439,6 +439,7 @@ 551|[Student Attendance Record I](./0551-student-attendance-record-i.js)|Easy| 552|[Student Attendance Record II](./0552-student-attendance-record-ii.js)|Hard| 553|[Optimal Division](./0553-optimal-division.js)|Medium| +554|[Brick Wall](./0554-brick-wall.js)|Medium| 557|[Reverse Words in a String III](./0557-reverse-words-in-a-string-iii.js)|Easy| 560|[Subarray Sum Equals K](./0560-subarray-sum-equals-k.js)|Medium| 563|[Binary Tree Tilt](./0563-binary-tree-tilt.js)|Easy| From 915be554050c3207bc0895d64cc3168ab32f6437 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 5 Mar 2025 20:26:02 -0600 Subject: [PATCH 814/919] Add solution #556 --- 0556-next-greater-element-iii.js | 38 ++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 39 insertions(+) create mode 100644 0556-next-greater-element-iii.js diff --git a/0556-next-greater-element-iii.js b/0556-next-greater-element-iii.js new file mode 100644 index 00000000..f8ee8bc7 --- /dev/null +++ b/0556-next-greater-element-iii.js @@ -0,0 +1,38 @@ +/** + * 556. Next Greater Element III + * https://leetcode.com/problems/next-greater-element-iii/ + * Difficulty: Medium + * + * Given a positive integer n, find the smallest integer which has exactly the same digits existing + * in the integer n and is greater in value than n. If no such positive integer exists, return -1. + * + * Note that the returned integer should fit in 32-bit integer, if there is a valid answer but it + * does not fit in 32-bit integer, return -1. + */ + +/** + * @param {number} n + * @return {number} + */ +var nextGreaterElement = function(n) { + const digits = [...String(n)]; + let i = digits.length - 2; + + while (i >= 0 && digits[i] >= digits[i + 1]) i--; + if (i < 0) return -1; + + let j = digits.length - 1; + while (j >= 0 && digits[j] <= digits[i]) j--; + + [digits[i], digits[j]] = [digits[j], digits[i]]; + let left = i + 1; + let right = digits.length - 1; + while (left < right) { + [digits[left], digits[right]] = [digits[right], digits[left]]; + left++; + right--; + } + + const result = +digits.join(''); + return result > n && result <= 2**31 - 1 ? result : -1; +}; diff --git a/README.md b/README.md index 603cd7b7..ac0ab48f 100644 --- a/README.md +++ b/README.md @@ -440,6 +440,7 @@ 552|[Student Attendance Record II](./0552-student-attendance-record-ii.js)|Hard| 553|[Optimal Division](./0553-optimal-division.js)|Medium| 554|[Brick Wall](./0554-brick-wall.js)|Medium| +556|[Next Greater Element III](./0556-next-greater-element-iii.js)|Medium| 557|[Reverse Words in a String III](./0557-reverse-words-in-a-string-iii.js)|Easy| 560|[Subarray Sum Equals K](./0560-subarray-sum-equals-k.js)|Medium| 563|[Binary Tree Tilt](./0563-binary-tree-tilt.js)|Easy| From 29e53a46388168b7593d7df0cfc8d7ddc543ff2c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 6 Mar 2025 00:00:55 -0600 Subject: [PATCH 815/919] Add solution #2270 --- 2270-number-of-ways-to-split-array.js | 32 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 2270-number-of-ways-to-split-array.js diff --git a/2270-number-of-ways-to-split-array.js b/2270-number-of-ways-to-split-array.js new file mode 100644 index 00000000..f7ac5451 --- /dev/null +++ b/2270-number-of-ways-to-split-array.js @@ -0,0 +1,32 @@ +/** + * 2270. Number of Ways to Split Array + * https://leetcode.com/problems/number-of-ways-to-split-array/ + * Difficulty: Medium + * + * You are given a 0-indexed integer array nums of length n. + * + * nums contains a valid split at index i if the following are true: + * - The sum of the first i + 1 elements is greater than or equal to the sum of the + * last n - i - 1 elements. + * - There is at least one element to the right of i. That is, 0 <= i < n - 1. + * + * Return the number of valid splits in nums. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var waysToSplitArray = function(nums) { + const total = nums.reduce((a, b) => a + b); + let result = 0; + + for (let i = 0, sum = 0; i < nums.length - 1; i++) { + sum += nums[i]; + if (sum >= total - sum) { + result++; + } + } + + return result; +}; diff --git a/README.md b/README.md index ac0ab48f..aad51f71 100644 --- a/README.md +++ b/README.md @@ -704,6 +704,7 @@ 2215|[Find the Difference of Two Arrays](./2215-find-the-difference-of-two-arrays.js)|Easy| 2235|[Add Two Integers](./2235-add-two-integers.js)|Easy| 2244|[Minimum Rounds to Complete All Tasks](./2244-minimum-rounds-to-complete-all-tasks.js)|Medium| +2270|[Number of Ways to Split Array](./2270-number-of-ways-to-split-array.js)|Medium| 2300|[Successful Pairs of Spells and Potions](./2300-successful-pairs-of-spells-and-potions.js)|Medium| 2336|[Smallest Number in Infinite Set](./2336-smallest-number-in-infinite-set.js)|Medium| 2342|[Max Sum of a Pair With Equal Sum of Digits](./2342-max-sum-of-a-pair-with-equal-sum-of-digits.js)|Medium| From 7eff50eff36046bc17a99346a64a261b53d78501 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 6 Mar 2025 00:03:25 -0600 Subject: [PATCH 816/919] Add solution #558 --- ...-binary-grids-represented-as-quad-trees.js | 71 +++++++++++++++++++ README.md | 1 + 2 files changed, 72 insertions(+) create mode 100644 0558-logical-or-of-two-binary-grids-represented-as-quad-trees.js diff --git a/0558-logical-or-of-two-binary-grids-represented-as-quad-trees.js b/0558-logical-or-of-two-binary-grids-represented-as-quad-trees.js new file mode 100644 index 00000000..7dc99724 --- /dev/null +++ b/0558-logical-or-of-two-binary-grids-represented-as-quad-trees.js @@ -0,0 +1,71 @@ +/** + * 558. Logical OR of Two Binary Grids Represented as Quad-Trees + * https://leetcode.com/problems/logical-or-of-two-binary-grids-represented-as-quad-trees/ + * Difficulty: Medium + * + * A Binary Matrix is a matrix in which all the elements are either 0 or 1. + * + * Given quadTree1 and quadTree2. quadTree1 represents a n * n binary matrix and quadTree2 + * represents another n * n binary matrix. + * + * Return a Quad-Tree representing the n * n binary matrix which is the result of logical + * bitwise OR of the two binary matrixes represented by quadTree1 and quadTree2. + * + * Notice that you can assign the value of a node to True or False when isLeaf is False, and + * both are accepted in the answer. + * + * A Quad-Tree is a tree data structure in which each internal node has exactly four children. + * Besides, each node has two attributes: + * - val: True if the node represents a grid of 1's or False if the node represents a grid of 0's. + * - isLeaf: True if the node is leaf node on the tree or False if the node has the four children. + * class Node { + * public boolean val; + * public boolean isLeaf; + * public Node topLeft; + * public Node topRight; + * public Node bottomLeft; + * public Node bottomRight; + * }. + * + * We can construct a Quad-Tree from a two-dimensional area using the following steps: + * 1. If the current grid has the same value (i.e all 1's or all 0's) set isLeaf True and set val to + * the value of the grid and set the four children to Null and stop. + * 2. If the current grid has different values, set isLeaf to False and set val to any value and + * divide the current grid into four sub-grids as shown in the photo. + * 3. Recurse for each of the children with the proper sub-grid. + */ + +/** + * // Definition for a QuadTree node. + * function _Node(val,isLeaf,topLeft,topRight,bottomLeft,bottomRight) { + * this.val = val; + * this.isLeaf = isLeaf; + * this.topLeft = topLeft; + * this.topRight = topRight; + * this.bottomLeft = bottomLeft; + * this.bottomRight = bottomRight; + * }; + */ + +/** + * @param {_Node} quadTree1 + * @param {_Node} quadTree2 + * @return {_Node} + */ +var intersect = function(quadTree1, quadTree2) { + if (quadTree1.isLeaf) return quadTree1.val ? quadTree1 : quadTree2; + if (quadTree2.isLeaf) return quadTree2.val ? quadTree2 : quadTree1; + + const topLeft = intersect(quadTree1.topLeft, quadTree2.topLeft); + const topRight = intersect(quadTree1.topRight, quadTree2.topRight); + const bottomLeft = intersect(quadTree1.bottomLeft, quadTree2.bottomLeft); + const bottomRight = intersect(quadTree1.bottomRight, quadTree2.bottomRight); + + if (topLeft.isLeaf && topRight.isLeaf && bottomLeft.isLeaf && bottomRight.isLeaf + && topLeft.val === topRight.val && topRight.val === bottomLeft.val + && bottomLeft.val === bottomRight.val) { + return new _Node(topLeft.val, true, null, null, null, null); + } + + return new _Node(false, false, topLeft, topRight, bottomLeft, bottomRight); +}; diff --git a/README.md b/README.md index aad51f71..131e8e78 100644 --- a/README.md +++ b/README.md @@ -442,6 +442,7 @@ 554|[Brick Wall](./0554-brick-wall.js)|Medium| 556|[Next Greater Element III](./0556-next-greater-element-iii.js)|Medium| 557|[Reverse Words in a String III](./0557-reverse-words-in-a-string-iii.js)|Easy| +558|[Logical OR of Two Binary Grids Represented as Quad-Trees](./0558-logical-or-of-two-binary-grids-represented-as-quad-trees.js)|Medium| 560|[Subarray Sum Equals K](./0560-subarray-sum-equals-k.js)|Medium| 563|[Binary Tree Tilt](./0563-binary-tree-tilt.js)|Easy| 565|[Array Nesting](./0565-array-nesting.js)|Medium| From c428eb7ad68dac284125b5d88dd2313f43fe6828 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 6 Mar 2025 00:05:57 -0600 Subject: [PATCH 817/919] Add solution #559 --- 0559-maximum-depth-of-n-ary-tree.js | 31 +++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 0559-maximum-depth-of-n-ary-tree.js diff --git a/0559-maximum-depth-of-n-ary-tree.js b/0559-maximum-depth-of-n-ary-tree.js new file mode 100644 index 00000000..0d83dd59 --- /dev/null +++ b/0559-maximum-depth-of-n-ary-tree.js @@ -0,0 +1,31 @@ +/** + * 559. Maximum Depth of N-ary Tree + * https://leetcode.com/problems/maximum-depth-of-n-ary-tree/ + * Difficulty: Easy + * + * Given a n-ary tree, find its maximum depth. + * + * The maximum depth is the number of nodes along the longest path from the root node down to + * the farthest leaf node. + * + * Nary-Tree input serialization is represented in their level order traversal, each group of + * children is separated by the null value (See examples). + */ + +/** + * // Definition for a _Node. + * function _Node(val,children) { + * this.val = val === undefined ? null : val; + * this.children = children === undefined ? null : children; + * }; + */ + +/** + * @param {_Node|null} root + * @return {number} + */ +var maxDepth = function(root) { + if (!root) return 0; + if (!root.children || !root.children.length) return 1; + return Math.max(...root.children.map(child => maxDepth(child))) + 1; +}; diff --git a/README.md b/README.md index 131e8e78..0719d7fd 100644 --- a/README.md +++ b/README.md @@ -443,6 +443,7 @@ 556|[Next Greater Element III](./0556-next-greater-element-iii.js)|Medium| 557|[Reverse Words in a String III](./0557-reverse-words-in-a-string-iii.js)|Easy| 558|[Logical OR of Two Binary Grids Represented as Quad-Trees](./0558-logical-or-of-two-binary-grids-represented-as-quad-trees.js)|Medium| +559|[Maximum Depth of N-ary Tree](./0559-maximum-depth-of-n-ary-tree.js)|Easy| 560|[Subarray Sum Equals K](./0560-subarray-sum-equals-k.js)|Medium| 563|[Binary Tree Tilt](./0563-binary-tree-tilt.js)|Easy| 565|[Array Nesting](./0565-array-nesting.js)|Medium| From ddae865e1ab48969cf19bb6d044ffda69d9c7c1c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 6 Mar 2025 00:06:38 -0600 Subject: [PATCH 818/919] Add solution #564 --- 0564-find-the-closest-palindrome.js | 50 +++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 51 insertions(+) create mode 100644 0564-find-the-closest-palindrome.js diff --git a/0564-find-the-closest-palindrome.js b/0564-find-the-closest-palindrome.js new file mode 100644 index 00000000..d67ea4fc --- /dev/null +++ b/0564-find-the-closest-palindrome.js @@ -0,0 +1,50 @@ +/** + * 564. Find the Closest Palindrome + * https://leetcode.com/problems/find-the-closest-palindrome/ + * Difficulty: Hard + * + * Given a string n representing an integer, return the closest integer (not including itself), + * which is a palindrome. If there is a tie, return the smaller one. + * + * The closest is defined as the absolute difference minimized between two integers. + */ + +/** + * @param {string} n + * @return {string} + */ +var nearestPalindromic = function(n) { + const num = BigInt(n); + + if (num <= 10n) return String(num - 1n); + if (num === 11n) return '9'; + if (n === '1' + '0'.repeat(n.length - 1)) return String(num - 1n); + if (n === '9'.repeat(n.length)) return String(num + 2n); + + const leftHalf = n.slice(0, Math.ceil(n.length / 2)); + const leftNum = BigInt(leftHalf); + const candidates = [ + String(10n ** BigInt(n.length - 1) - 1n), + createPalindrome(leftNum - 1n, n.length), + createPalindrome(leftNum, n.length), + createPalindrome(leftNum + 1n, n.length), + String(10n ** BigInt(n.length) + 1n) + ].filter(x => x !== n); + + return candidates.reduce((min, curr) => { + const currDiff = BigInt(curr) > num ? BigInt(curr) - num : num - BigInt(curr); + const minDiff = BigInt(min) > num ? BigInt(min) - num : num - BigInt(min); + return currDiff < minDiff + ? curr + : currDiff === minDiff + ? (curr < min ? curr : min) + : min; + }); + + function createPalindrome(left, length) { + const s = String(left); + return length % 2 === 0 + ? s + s.split('').reverse().join('') + : s + s.slice(0, -1).split('').reverse().join(''); + } +}; diff --git a/README.md b/README.md index 0719d7fd..6d112e5b 100644 --- a/README.md +++ b/README.md @@ -446,6 +446,7 @@ 559|[Maximum Depth of N-ary Tree](./0559-maximum-depth-of-n-ary-tree.js)|Easy| 560|[Subarray Sum Equals K](./0560-subarray-sum-equals-k.js)|Medium| 563|[Binary Tree Tilt](./0563-binary-tree-tilt.js)|Easy| +564|[Find the Closest Palindrome](./0564-find-the-closest-palindrome.js)|Hard| 565|[Array Nesting](./0565-array-nesting.js)|Medium| 566|[Reshape the Matrix](./0566-reshape-the-matrix.js)|Easy| 567|[Permutation in String](./0567-permutation-in-string.js)|Medium| From 5f40eab4a3f2a4923b819407e9228c668a252b47 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 6 Mar 2025 00:07:10 -0600 Subject: [PATCH 819/919] Add solution #572 --- 0572-subtree-of-another-tree.js | 31 +++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 0572-subtree-of-another-tree.js diff --git a/0572-subtree-of-another-tree.js b/0572-subtree-of-another-tree.js new file mode 100644 index 00000000..cd204e3f --- /dev/null +++ b/0572-subtree-of-another-tree.js @@ -0,0 +1,31 @@ +/** + * 572. Subtree of Another Tree + * https://leetcode.com/problems/subtree-of-another-tree/ + * Difficulty: Easy + * + * Given the roots of two binary trees root and subRoot, return true if there is a subtree of + * root with the same structure and node values of subRoot and false otherwise. + * + * A subtree of a binary tree tree is a tree that consists of a node in tree and all of this + * node's descendants. The tree tree could also be considered as a subtree of itself. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @param {TreeNode} subRoot + * @return {boolean} + */ +var isSubtree = function(root, subRoot) { + return traverse(root).includes(traverse(subRoot)); + function traverse(node) { + return !node ? '#' : `,${node.val},${traverse(node.left)},${traverse(node.right)}`; + } +}; diff --git a/README.md b/README.md index 6d112e5b..00422cb0 100644 --- a/README.md +++ b/README.md @@ -450,6 +450,7 @@ 565|[Array Nesting](./0565-array-nesting.js)|Medium| 566|[Reshape the Matrix](./0566-reshape-the-matrix.js)|Easy| 567|[Permutation in String](./0567-permutation-in-string.js)|Medium| +572|[Subtree of Another Tree](./0572-subtree-of-another-tree.js)|Easy| 575|[Distribute Candies](./0575-distribute-candies.js)|Easy| 589|[N-ary Tree Preorder Traversal](./0589-n-ary-tree-preorder-traversal.js)|Easy| 594|[Longest Harmonious Subsequence](./0594-longest-harmonious-subsequence.js)|Easy| From 6c34c1b6ce432216d60985c96b73859fabb44c01 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 6 Mar 2025 00:08:13 -0600 Subject: [PATCH 820/919] Add solution #576 --- 0576-out-of-boundary-paths.js | 44 +++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 45 insertions(+) create mode 100644 0576-out-of-boundary-paths.js diff --git a/0576-out-of-boundary-paths.js b/0576-out-of-boundary-paths.js new file mode 100644 index 00000000..ee1c8acc --- /dev/null +++ b/0576-out-of-boundary-paths.js @@ -0,0 +1,44 @@ +/** + * 576. Out of Boundary Paths + * https://leetcode.com/problems/out-of-boundary-paths/ + * Difficulty: Medium + * + * There is an m x n grid with a ball. The ball is initially at the position [startRow, + * startColumn]. You are allowed to move the ball to one of the four adjacent cells in + * the grid (possibly out of the grid crossing the grid boundary). You can apply at most + * maxMove moves to the ball. + * + * Given the five integers m, n, maxMove, startRow, startColumn, return the number of + * paths to move the ball out of the grid boundary. Since the answer can be very large, + * return it modulo 109 + 7. + */ + +/** + * @param {number} m + * @param {number} n + * @param {number} maxMove + * @param {number} startRow + * @param {number} startColumn + * @return {number} + */ +var findPaths = function(m, n, maxMove, startRow, startColumn) { + const MOD = 1e9 + 7; + const directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]; + const dp = new Array(maxMove + 1).fill().map(() => { + return new Array(m).fill().map(() => new Array(n).fill(-1)); + }); + + return solve(maxMove, startRow, startColumn); + + function solve(moves, row, col) { + if (row < 0 || row >= m || col < 0 || col >= n) return 1; + if (moves === 0) return 0; + if (dp[moves][row][col] !== -1) return dp[moves][row][col]; + + let paths = 0; + for (const [dr, dc] of directions) { + paths = (paths + solve(moves - 1, row + dr, col + dc)) % MOD; + } + return dp[moves][row][col] = paths; + } +}; diff --git a/README.md b/README.md index 00422cb0..00f9f17d 100644 --- a/README.md +++ b/README.md @@ -452,6 +452,7 @@ 567|[Permutation in String](./0567-permutation-in-string.js)|Medium| 572|[Subtree of Another Tree](./0572-subtree-of-another-tree.js)|Easy| 575|[Distribute Candies](./0575-distribute-candies.js)|Easy| +576|[Out of Boundary Paths](./0576-out-of-boundary-paths.js)|Medium| 589|[N-ary Tree Preorder Traversal](./0589-n-ary-tree-preorder-traversal.js)|Easy| 594|[Longest Harmonious Subsequence](./0594-longest-harmonious-subsequence.js)|Easy| 599|[Minimum Index Sum of Two Lists](./0599-minimum-index-sum-of-two-lists.js)|Easy| From 218d5d26b8992c9bbc2181f0902f31ea6b185faf Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 6 Mar 2025 00:08:47 -0600 Subject: [PATCH 821/919] Add solution #581 --- 0581-shortest-unsorted-continuous-subarray.js | 33 +++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 0581-shortest-unsorted-continuous-subarray.js diff --git a/0581-shortest-unsorted-continuous-subarray.js b/0581-shortest-unsorted-continuous-subarray.js new file mode 100644 index 00000000..ab1dca43 --- /dev/null +++ b/0581-shortest-unsorted-continuous-subarray.js @@ -0,0 +1,33 @@ +/** + * 581. Shortest Unsorted Continuous Subarray + * https://leetcode.com/problems/shortest-unsorted-continuous-subarray/ + * Difficulty: Medium + * + * Given an integer array nums, you need to find one continuous subarray such that if you + * only sort this subarray in non-decreasing order, then the whole array will be sorted + * in non-decreasing order. + * + * Return the shortest such subarray and output its length. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var findUnsortedSubarray = function(nums) { + let start = -1; + let end = -2; + + for (let i = 1, min = nums[nums.length - 1], max = nums[0]; i < nums.length; i++) { + max = Math.max(max, nums[i]); + min = Math.min(min, nums[nums.length - 1 - i]); + if (nums[i] < max) { + end = i; + } + if (nums[nums.length - 1 - i] > min) { + start = nums.length - 1 - i; + } + } + + return end - start + 1; +}; diff --git a/README.md b/README.md index 00f9f17d..2f82fd70 100644 --- a/README.md +++ b/README.md @@ -453,6 +453,7 @@ 572|[Subtree of Another Tree](./0572-subtree-of-another-tree.js)|Easy| 575|[Distribute Candies](./0575-distribute-candies.js)|Easy| 576|[Out of Boundary Paths](./0576-out-of-boundary-paths.js)|Medium| +581|[Shortest Unsorted Continuous Subarray](./0581-shortest-unsorted-continuous-subarray.js)|Medium| 589|[N-ary Tree Preorder Traversal](./0589-n-ary-tree-preorder-traversal.js)|Easy| 594|[Longest Harmonious Subsequence](./0594-longest-harmonious-subsequence.js)|Easy| 599|[Minimum Index Sum of Two Lists](./0599-minimum-index-sum-of-two-lists.js)|Easy| From 799d1d8b28119bad856b551cbf1235ed891acd5e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 6 Mar 2025 00:09:20 -0600 Subject: [PATCH 822/919] Add solution #583 --- 0583-delete-operation-for-two-strings.js | 37 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 38 insertions(+) create mode 100644 0583-delete-operation-for-two-strings.js diff --git a/0583-delete-operation-for-two-strings.js b/0583-delete-operation-for-two-strings.js new file mode 100644 index 00000000..ab547889 --- /dev/null +++ b/0583-delete-operation-for-two-strings.js @@ -0,0 +1,37 @@ +/** + * 583. Delete Operation for Two Strings + * https://leetcode.com/problems/delete-operation-for-two-strings/ + * Difficulty: Medium + * + * Given two strings word1 and word2, return the minimum number of steps required to + * make word1 and word2 the same. + * + * In one step, you can delete exactly one character in either string. + */ + +/** + * @param {string} word1 + * @param {string} word2 + * @return {number} + */ +var minDistance = function(word1, word2) { + const dp = new Array(word1.length + 1).fill().map(() => { + return new Array(word2.length + 1).fill(0); + }); + + for (let i = 1; i <= word1.length; i++) { + dp[i][0] = i; + } + for (let j = 1; j <= word2.length; j++) { + dp[0][j] = j; + } + for (let i = 1; i <= word1.length; i++) { + for (let j = 1; j <= word2.length; j++) { + dp[i][j] = word1[i - 1] === word2[j - 1] + ? dp[i - 1][j - 1] + : Math.min(dp[i - 1][j], dp[i][j - 1]) + 1; + } + } + + return dp[word1.length][word2.length]; +}; diff --git a/README.md b/README.md index 2f82fd70..0cd815df 100644 --- a/README.md +++ b/README.md @@ -454,6 +454,7 @@ 575|[Distribute Candies](./0575-distribute-candies.js)|Easy| 576|[Out of Boundary Paths](./0576-out-of-boundary-paths.js)|Medium| 581|[Shortest Unsorted Continuous Subarray](./0581-shortest-unsorted-continuous-subarray.js)|Medium| +583|[Delete Operation for Two Strings](./0583-delete-operation-for-two-strings.js)|Medium| 589|[N-ary Tree Preorder Traversal](./0589-n-ary-tree-preorder-traversal.js)|Easy| 594|[Longest Harmonious Subsequence](./0594-longest-harmonious-subsequence.js)|Easy| 599|[Minimum Index Sum of Two Lists](./0599-minimum-index-sum-of-two-lists.js)|Easy| From b6b622a8999462b8362be8c0ae4a57f91493fe40 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 6 Mar 2025 00:10:03 -0600 Subject: [PATCH 823/919] Add solution #587 --- 0587-erect-the-fence.js | 41 +++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 42 insertions(+) create mode 100644 0587-erect-the-fence.js diff --git a/0587-erect-the-fence.js b/0587-erect-the-fence.js new file mode 100644 index 00000000..6df622fa --- /dev/null +++ b/0587-erect-the-fence.js @@ -0,0 +1,41 @@ +/** + * 587. Erect the Fence + * https://leetcode.com/problems/erect-the-fence/ + * Difficulty: Hard + * + * You are given an array trees where trees[i] = [xi, yi] represents the location of + * a tree in the garden. + * + * Fence the entire garden using the minimum length of rope, as it is expensive. The + * garden is well-fenced only if all the trees are enclosed. + * + * Return the coordinates of trees that are exactly located on the fence perimeter. + * You may return the answer in any order. + */ + +/** + * @param {number[][]} trees + * @return {number[][]} + */ +var outerTrees = function(trees) { + const a = []; + const b = []; + + trees.sort(([x1, y1], [x2, y2]) => x1 === x2 ? y1 - y2 : x1 - x2); + for (const point of trees) { + while (a.length >= 2 && cross(a[a.length - 2], a[a.length - 1], point) < 0) { + a.pop(); + } + a.push(point); + while (b.length >= 2 && cross(b[b.length - 2], b[b.length - 1], point) > 0) { + b.pop(); + } + b.push(point); + } + + return [...new Set([...a, ...b].map(p => JSON.stringify(p)))].map(p => JSON.parse(p)); + + function cross(p, q, r) { + return (q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0]); + } +}; diff --git a/README.md b/README.md index 0cd815df..9d87637a 100644 --- a/README.md +++ b/README.md @@ -455,6 +455,7 @@ 576|[Out of Boundary Paths](./0576-out-of-boundary-paths.js)|Medium| 581|[Shortest Unsorted Continuous Subarray](./0581-shortest-unsorted-continuous-subarray.js)|Medium| 583|[Delete Operation for Two Strings](./0583-delete-operation-for-two-strings.js)|Medium| +587|[Erect the Fence](./0587-erect-the-fence.js)|Hard| 589|[N-ary Tree Preorder Traversal](./0589-n-ary-tree-preorder-traversal.js)|Easy| 594|[Longest Harmonious Subsequence](./0594-longest-harmonious-subsequence.js)|Easy| 599|[Minimum Index Sum of Two Lists](./0599-minimum-index-sum-of-two-lists.js)|Easy| From c43b7d1fbf2787ecba2a0d1ef1e7bba087e44eb8 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 6 Mar 2025 00:10:32 -0600 Subject: [PATCH 824/919] Add solution #590 --- 0590-n-ary-tree-postorder-traversal.js | 34 ++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 0590-n-ary-tree-postorder-traversal.js diff --git a/0590-n-ary-tree-postorder-traversal.js b/0590-n-ary-tree-postorder-traversal.js new file mode 100644 index 00000000..32e39913 --- /dev/null +++ b/0590-n-ary-tree-postorder-traversal.js @@ -0,0 +1,34 @@ +/** + * 590. N-ary Tree Postorder Traversal + * https://leetcode.com/problems/n-ary-tree-postorder-traversal/ + * Difficulty: Easy + * + * Given the root of an n-ary tree, return the postorder traversal of its nodes' values. + * + * Nary-Tree input serialization is represented in their level order traversal. Each group + * of children is separated by the null value (See examples) + */ + +/** + * // Definition for a _Node. + * function _Node(val,children) { + * this.val = val; + * this.children = children; + * }; + */ + +/** + * @param {_Node|null} root + * @return {number[]} + */ +var postorder = function(root) { + const result = []; + traverse(root); + return result; + + function traverse(node) { + if (!node) return; + node.children.forEach(child => traverse(child)); + result.push(node.val); + } +}; diff --git a/README.md b/README.md index 9d87637a..8be92143 100644 --- a/README.md +++ b/README.md @@ -457,6 +457,7 @@ 583|[Delete Operation for Two Strings](./0583-delete-operation-for-two-strings.js)|Medium| 587|[Erect the Fence](./0587-erect-the-fence.js)|Hard| 589|[N-ary Tree Preorder Traversal](./0589-n-ary-tree-preorder-traversal.js)|Easy| +590|[N-ary Tree Postorder Traversal](./0590-n-ary-tree-postorder-traversal.js)|Easy| 594|[Longest Harmonious Subsequence](./0594-longest-harmonious-subsequence.js)|Easy| 599|[Minimum Index Sum of Two Lists](./0599-minimum-index-sum-of-two-lists.js)|Easy| 605|[Can Place Flowers](./0605-can-place-flowers.js)|Easy| From 7e031e31f8d80123d1cc869061e364e95142552c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 6 Mar 2025 20:24:04 -0600 Subject: [PATCH 825/919] Add solution #591 --- 0591-tag-validator.js | 79 +++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 80 insertions(+) create mode 100644 0591-tag-validator.js diff --git a/0591-tag-validator.js b/0591-tag-validator.js new file mode 100644 index 00000000..2fef8784 --- /dev/null +++ b/0591-tag-validator.js @@ -0,0 +1,79 @@ +/** + * 591. Tag Validator + * https://leetcode.com/problems/tag-validator/ + * Difficulty: Hard + * + * Given a string representing a code snippet, implement a tag validator to parse the code and + * return whether it is valid. + * + * A code snippet is valid if all the following rules hold: + * 1. The code must be wrapped in a valid closed tag. Otherwise, the code is invalid. + * 2. A closed tag (not necessarily valid) has exactly the following format: + * TAG_CONTENT. Among them, is the start tag, and + * is the end tag. The TAG_NAME in start and end tags should be the same. A closed tag is valid + * if and only if the TAG_NAME and TAG_CONTENT are valid. + * 3. A valid TAG_NAME only contain upper-case letters, and has length in range [1,9]. Otherwise, + * the TAG_NAME is invalid. + * 4. A valid TAG_CONTENT may contain other valid closed tags, cdata and any characters (see + * note1) EXCEPT unmatched <, unmatched start and end tag, and unmatched or closed tags with + * invalid TAG_NAME. Otherwise, the TAG_CONTENT is invalid. + * 5. A start tag is unmatched if no end tag exists with the same TAG_NAME, and vice versa. + * However, you also need to consider the issue of unbalanced when tags are nested. + * 6. A < is unmatched if you cannot find a subsequent >. And when you find a < or should be parsed as TAG_NAME (not necessarily + * valid). + * 7. The cdata has the following format : . The range of CDATA_CONTENT + * is defined as the characters between . + * 8. CDATA_CONTENT may contain any characters. The function of cdata is to forbid the validator + * to parse CDATA_CONTENT, so even it has some characters that can be parsed as tag (no matter + * valid or invalid), you should treat it as regular characters. + */ + +/** + * @param {string} code + * @return {boolean} + */ +var isValid = function(code) { + const stack = []; + + for (let i = 0; i < code.length;) { + if (i > 0 && !stack.length) { + return false; + } + if (code.startsWith('', j); + if (i === -1) { + return false; + } + i += 3; + } else if (code.startsWith('', j); + if (i === -1) { + return false; + } + const tag = code.slice(j, i); + if (!stack.length || stack.pop() !== tag || !/^[A-Z]{1,9}$/.test(tag)) { + return false; + } + i++; + } else if (code[i] === '<') { + const j = i + 1; + i = code.indexOf('>', j); + if (i === -1) { + return false; + } + const tag = code.slice(j, i); + if (!/^[A-Z]{1,9}$/.test(tag)) { + return false; + } + stack.push(tag); + i++; + } else { + i++; + } + } + + return !stack.length; +}; diff --git a/README.md b/README.md index 8be92143..f05e908e 100644 --- a/README.md +++ b/README.md @@ -458,6 +458,7 @@ 587|[Erect the Fence](./0587-erect-the-fence.js)|Hard| 589|[N-ary Tree Preorder Traversal](./0589-n-ary-tree-preorder-traversal.js)|Easy| 590|[N-ary Tree Postorder Traversal](./0590-n-ary-tree-postorder-traversal.js)|Easy| +591|[Tag Validator](./0591-tag-validator.js)|Hard| 594|[Longest Harmonious Subsequence](./0594-longest-harmonious-subsequence.js)|Easy| 599|[Minimum Index Sum of Two Lists](./0599-minimum-index-sum-of-two-lists.js)|Easy| 605|[Can Place Flowers](./0605-can-place-flowers.js)|Easy| From 3837c772a6f74b729579067a15602abeb5788fd9 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 6 Mar 2025 20:25:55 -0600 Subject: [PATCH 826/919] Add solution #592 --- 0592-fraction-addition-and-subtraction.js | 34 +++++++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 0592-fraction-addition-and-subtraction.js diff --git a/0592-fraction-addition-and-subtraction.js b/0592-fraction-addition-and-subtraction.js new file mode 100644 index 00000000..4078b08f --- /dev/null +++ b/0592-fraction-addition-and-subtraction.js @@ -0,0 +1,34 @@ +/** + * 592. Fraction Addition and Subtraction + * https://leetcode.com/problems/fraction-addition-and-subtraction/ + * Difficulty: Medium + * + * Given a string expression representing an expression of fraction addition and subtraction, + * return the calculation result in string format. + * + * The final result should be an irreducible fraction. If your final result is an integer, + * change it to the format of a fraction that has a denominator 1. So in this case, 2 should + * be converted to 2/1. + */ + +/** + * @param {string} expression + * @return {string} + */ +var fractionAddition = function(expression) { + const gcdCalc = (a, b) => b === 0 ? a : gcdCalc(b, a % b); + const fractions = expression.match(/[+-]?\d+\/\d+/g); + let n = 0; + let d = 1; + + for (const fraction of fractions) { + const [numerator, denominator] = fraction.split('/').map(Number); + n = n * denominator + numerator * d; + d = d * denominator; + const gcd = Math.abs(gcdCalc(n, d)); + n /= gcd; + d /= gcd; + } + + return `${n}/${d}`; +}; diff --git a/README.md b/README.md index f05e908e..96526949 100644 --- a/README.md +++ b/README.md @@ -459,6 +459,7 @@ 589|[N-ary Tree Preorder Traversal](./0589-n-ary-tree-preorder-traversal.js)|Easy| 590|[N-ary Tree Postorder Traversal](./0590-n-ary-tree-postorder-traversal.js)|Easy| 591|[Tag Validator](./0591-tag-validator.js)|Hard| +592|[Fraction Addition and Subtraction](./0592-fraction-addition-and-subtraction.js)|Medium| 594|[Longest Harmonious Subsequence](./0594-longest-harmonious-subsequence.js)|Easy| 599|[Minimum Index Sum of Two Lists](./0599-minimum-index-sum-of-two-lists.js)|Easy| 605|[Can Place Flowers](./0605-can-place-flowers.js)|Easy| From 2d1039582cc4ca0ea22a9c66518199907c601075 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 6 Mar 2025 20:26:37 -0600 Subject: [PATCH 827/919] Add solution #593 --- 0593-valid-square.js | 38 ++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 39 insertions(+) create mode 100644 0593-valid-square.js diff --git a/0593-valid-square.js b/0593-valid-square.js new file mode 100644 index 00000000..df3975d4 --- /dev/null +++ b/0593-valid-square.js @@ -0,0 +1,38 @@ +/** + * 593. Valid Square + * https://leetcode.com/problems/valid-square/ + * Difficulty: Medium + * + * Given the coordinates of four points in 2D space p1, p2, p3 and p4, return true if the + * four points construct a square. + * + * The coordinate of a point pi is represented as [xi, yi]. The input is not given in any order. + * + * A valid square has four equal sides with positive length and four equal angles (90-degree + * angles). + */ + +/** + * @param {number[]} p1 + * @param {number[]} p2 + * @param {number[]} p3 + * @param {number[]} p4 + * @return {boolean} + */ +var validSquare = function(p1, p2, p3, p4) { + const helper = (a, b) => (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2; + const points = [p1, p2, p3, p4]; + const set = new Set(); + + for (let i = 0; i < 4; i++) { + for (let j = i + 1; j < 4; j++) { + const d = helper(points[i], points[j]); + if (!d) { + return false; + } + set.add(d); + } + } + + return set.size === 2; +}; diff --git a/README.md b/README.md index 96526949..bfb5f3ba 100644 --- a/README.md +++ b/README.md @@ -460,6 +460,7 @@ 590|[N-ary Tree Postorder Traversal](./0590-n-ary-tree-postorder-traversal.js)|Easy| 591|[Tag Validator](./0591-tag-validator.js)|Hard| 592|[Fraction Addition and Subtraction](./0592-fraction-addition-and-subtraction.js)|Medium| +593|[Valid Square](./0593-valid-square.js)|Medium| 594|[Longest Harmonious Subsequence](./0594-longest-harmonious-subsequence.js)|Easy| 599|[Minimum Index Sum of Two Lists](./0599-minimum-index-sum-of-two-lists.js)|Easy| 605|[Can Place Flowers](./0605-can-place-flowers.js)|Easy| From d538a31546191286198cedc6486898aebd2c2038 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 6 Mar 2025 20:27:14 -0600 Subject: [PATCH 828/919] Add solution #598 --- 0598-range-addition-ii.js | 30 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 0598-range-addition-ii.js diff --git a/0598-range-addition-ii.js b/0598-range-addition-ii.js new file mode 100644 index 00000000..7a013ccd --- /dev/null +++ b/0598-range-addition-ii.js @@ -0,0 +1,30 @@ +/** + * 598. Range Addition II + * https://leetcode.com/problems/range-addition-ii/ + * Difficulty: Easy + * + * You are given an m x n matrix M initialized with all 0's and an array of operations ops, + * where ops[i] = [ai, bi] means M[x][y] should be incremented by one for all 0 <= x < ai + * and 0 <= y < bi. + * + * Count and return the number of maximum integers in the matrix after performing all the + * operations. + */ + +/** + * @param {number} m + * @param {number} n + * @param {number[][]} ops + * @return {number} + */ +var maxCount = function(m, n, ops) { + let a = m; + let b = n; + + for (const op of ops) { + a = Math.min(a, op[0]); + b = Math.min(b, op[1]); + } + + return a * b; +}; diff --git a/README.md b/README.md index bfb5f3ba..f1ed1410 100644 --- a/README.md +++ b/README.md @@ -462,6 +462,7 @@ 592|[Fraction Addition and Subtraction](./0592-fraction-addition-and-subtraction.js)|Medium| 593|[Valid Square](./0593-valid-square.js)|Medium| 594|[Longest Harmonious Subsequence](./0594-longest-harmonious-subsequence.js)|Easy| +598|[Range Addition II](./0598-range-addition-ii.js)|Easy| 599|[Minimum Index Sum of Two Lists](./0599-minimum-index-sum-of-two-lists.js)|Easy| 605|[Can Place Flowers](./0605-can-place-flowers.js)|Easy| 606|[Construct String from Binary Tree](./0606-construct-string-from-binary-tree.js)|Easy| From d5d67ee232815cdee6f434ea12b5ccf4c2c4da83 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 6 Mar 2025 20:27:46 -0600 Subject: [PATCH 829/919] Add solution #600 --- ...ative-integers-without-consecutive-ones.js | 39 +++++++++++++++++++ README.md | 1 + 2 files changed, 40 insertions(+) create mode 100644 0600-non-negative-integers-without-consecutive-ones.js diff --git a/0600-non-negative-integers-without-consecutive-ones.js b/0600-non-negative-integers-without-consecutive-ones.js new file mode 100644 index 00000000..c352c96a --- /dev/null +++ b/0600-non-negative-integers-without-consecutive-ones.js @@ -0,0 +1,39 @@ +/** + * 600. Non-negative Integers without Consecutive Ones + * https://leetcode.com/problems/non-negative-integers-without-consecutive-ones/ + * Difficulty: Hard + * + * Given a positive integer n, return the number of the integers in the range [0, n] whose + * binary representations do not contain consecutive ones. + */ + +/** + * @param {number} n + * @return {number} + */ +var findIntegers = function(n) { + const binary = n.toString(2); + const dp = new Array(binary.length + 1).fill(0); + let result = 0; + + dp[0] = 1; + dp[1] = 2; + + for (let i = 2; i <= binary.length; i++) { + dp[i] = dp[i - 1] + dp[i - 2]; + } + + for (let i = 0, previous = 0; i < binary.length; i++) { + if (binary[i] === '1') { + result += dp[binary.length - i - 1]; + if (previous === 1) { + return result; + } + previous = 1; + } else { + previous = 0; + } + } + + return result + 1; +}; diff --git a/README.md b/README.md index f1ed1410..9846e06f 100644 --- a/README.md +++ b/README.md @@ -464,6 +464,7 @@ 594|[Longest Harmonious Subsequence](./0594-longest-harmonious-subsequence.js)|Easy| 598|[Range Addition II](./0598-range-addition-ii.js)|Easy| 599|[Minimum Index Sum of Two Lists](./0599-minimum-index-sum-of-two-lists.js)|Easy| +600|[Non-negative Integers without Consecutive Ones](./0600-non-negative-integers-without-consecutive-ones.js)|Hard| 605|[Can Place Flowers](./0605-can-place-flowers.js)|Easy| 606|[Construct String from Binary Tree](./0606-construct-string-from-binary-tree.js)|Easy| 617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy| From 68105db7d0f3ff7e92ed1c54c7ead1da749a1cc8 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 7 Mar 2025 00:11:15 -0600 Subject: [PATCH 830/919] Add solution #609 --- 0609-find-duplicate-file-in-system.js | 43 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 44 insertions(+) create mode 100644 0609-find-duplicate-file-in-system.js diff --git a/0609-find-duplicate-file-in-system.js b/0609-find-duplicate-file-in-system.js new file mode 100644 index 00000000..ce7a151d --- /dev/null +++ b/0609-find-duplicate-file-in-system.js @@ -0,0 +1,43 @@ +/** + * 609. Find Duplicate File in System + * https://leetcode.com/problems/find-duplicate-file-in-system/ + * Difficulty: Medium + * + * Given a list paths of directory info, including the directory path, and all the files with + * contents in this directory, return all the duplicate files in the file system in terms of + * their paths. You may return the answer in any order. + * + * A group of duplicate files consists of at least two files that have the same content. + * + * A single directory info string in the input list has the following format: + * - "root/d1/d2/.../dm f1.txt(f1_content) f2.txt(f2_content) ... fn.txt(fn_content)" + * + * It means there are n files (f1.txt, f2.txt ... fn.txt) with content (f1_content, f2_content + * ... fn_content) respectively in the directory "root/d1/d2/.../dm". Note that n >= 1 and + * m >= 0. If m = 0, it means the directory is just the root directory. + * + * The output is a list of groups of duplicate file paths. For each group, it contains all the + * file paths of the files that have the same content. A file path is a string that has the + * following format: + * - "directory_path/file_name.txt" + */ + +/** + * @param {string[]} paths + * @return {string[][]} + */ +var findDuplicate = function(paths) { + const map = new Map(); + + for (const path of paths) { + const [directory, ...files] = path.split(' '); + for (const file of files) { + const [name, content] = file.split('('); + const fullPath = `${directory}/${name}`; + const fileContent = content.slice(0, -1); + map.set(fileContent, (map.get(fileContent) || []).concat(fullPath)); + } + } + + return Array.from(map.values()).filter(group => group.length > 1); +}; diff --git a/README.md b/README.md index 9846e06f..be4fc8e8 100644 --- a/README.md +++ b/README.md @@ -467,6 +467,7 @@ 600|[Non-negative Integers without Consecutive Ones](./0600-non-negative-integers-without-consecutive-ones.js)|Hard| 605|[Can Place Flowers](./0605-can-place-flowers.js)|Easy| 606|[Construct String from Binary Tree](./0606-construct-string-from-binary-tree.js)|Easy| +609|[Find Duplicate File in System](./0609-find-duplicate-file-in-system.js)|Medium| 617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy| 621|[Task Scheduler](./0621-task-scheduler.js)|Medium| 628|[Maximum Product of Three Numbers](./0628-maximum-product-of-three-numbers.js)|Easy| From 36d1236b031c9dc3d7916d0341e2240c021669f9 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 7 Mar 2025 00:12:16 -0600 Subject: [PATCH 831/919] Add solution #611 --- 0611-valid-triangle-number.js | 31 +++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 0611-valid-triangle-number.js diff --git a/0611-valid-triangle-number.js b/0611-valid-triangle-number.js new file mode 100644 index 00000000..719adc88 --- /dev/null +++ b/0611-valid-triangle-number.js @@ -0,0 +1,31 @@ +/** + * 611. Valid Triangle Number + * https://leetcode.com/problems/valid-triangle-number/ + * Difficulty: Medium + * + * Given an integer array nums, return the number of triplets chosen from the array that + * can make triangles if we take them as side lengths of a triangle. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var triangleNumber = function(nums) { + let count = 0; + + nums.sort((a, b) => a - b); + + for (let k = nums.length - 1; k >= 2; k--) { + for (let i = 0, j = k - 1; i < j;) { + if (nums[i] + nums[j] > nums[k]) { + count += j - i; + j--; + } else { + i++; + } + } + } + + return count; +}; diff --git a/README.md b/README.md index be4fc8e8..1096dd24 100644 --- a/README.md +++ b/README.md @@ -468,6 +468,7 @@ 605|[Can Place Flowers](./0605-can-place-flowers.js)|Easy| 606|[Construct String from Binary Tree](./0606-construct-string-from-binary-tree.js)|Easy| 609|[Find Duplicate File in System](./0609-find-duplicate-file-in-system.js)|Medium| +611|[Valid Triangle Number](./0611-valid-triangle-number.js)|Medium| 617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy| 621|[Task Scheduler](./0621-task-scheduler.js)|Medium| 628|[Maximum Product of Three Numbers](./0628-maximum-product-of-three-numbers.js)|Easy| From 6a1bb7c6f8153ad7bf128e6e8a2880decef8caaa Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 7 Mar 2025 00:13:38 -0600 Subject: [PATCH 832/919] Add solution #622 --- 0622-design-circular-queue.js | 98 +++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 99 insertions(+) create mode 100644 0622-design-circular-queue.js diff --git a/0622-design-circular-queue.js b/0622-design-circular-queue.js new file mode 100644 index 00000000..1f3ab2f6 --- /dev/null +++ b/0622-design-circular-queue.js @@ -0,0 +1,98 @@ +/** + * 622. Design Circular Queue + * https://leetcode.com/problems/design-circular-queue/ + * Difficulty: Medium + * + * Design your implementation of the circular queue. The circular queue is a linear data structure + * in which the operations are performed based on FIFO (First In First Out) principle, and the + * last position is connected back to the first position to make a circle. It is also called + * "Ring Buffer". + * + * One of the benefits of the circular queue is that we can make use of the spaces in front of + * the queue. In a normal queue, once the queue becomes full, we cannot insert the next element + * even if there is a space in front of the queue. But using the circular queue, we can use the + * space to store new values. + * + * Implement the MyCircularQueue class: + * - MyCircularQueue(k) Initializes the object with the size of the queue to be k. + * - int Front() Gets the front item from the queue. If the queue is empty, return -1. + * - int Rear() Gets the last item from the queue. If the queue is empty, return -1. + * - boolean enQueue(int value) Inserts an element into the circular queue. Return true if the + * operation is successful. + * - boolean deQueue() Deletes an element from the circular queue. Return true if the operation + * is successful. + * - boolean isEmpty() Checks whether the circular queue is empty or not. + * - boolean isFull() Checks whether the circular queue is full or not. + * + * You must solve the problem without using the built-in queue data structure in your programming + * language. + */ + +/** + * @param {number} k + */ +var MyCircularQueue = function(k) { + this.queue = new Array(k); + this.size = k; + this.front = -1; + this.rear = -1; +}; + +/** + * @param {number} value + * @return {boolean} + */ +MyCircularQueue.prototype.enQueue = function(value) { + if (this.isFull()) { + return false; + } + if (this.isEmpty()) { + this.front = 0; + } + this.rear = (this.rear + 1) % this.size; + this.queue[this.rear] = value; + return true; +}; + +/** + * @return {boolean} + */ +MyCircularQueue.prototype.deQueue = function() { + if (this.isEmpty()) { + return false; + } else if (this.front === this.rear) { + this.front = -1; + this.rear = -1; + } else { + this.front = (this.front + 1) % this.size; + } + return true; +}; + +/** + * @return {number} + */ +MyCircularQueue.prototype.Front = function() { + return this.isEmpty() ? -1 : this.queue[this.front]; +}; + +/** + * @return {number} + */ +MyCircularQueue.prototype.Rear = function() { + return this.isEmpty() ? -1 : this.queue[this.rear]; +}; + +/** + * @return {boolean} + */ +MyCircularQueue.prototype.isEmpty = function() { + return this.front === -1; +}; + +/** + * @return {boolean} + */ +MyCircularQueue.prototype.isFull = function() { + return (this.rear + 1) % this.size === this.front; +}; diff --git a/README.md b/README.md index 1096dd24..20994283 100644 --- a/README.md +++ b/README.md @@ -471,6 +471,7 @@ 611|[Valid Triangle Number](./0611-valid-triangle-number.js)|Medium| 617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy| 621|[Task Scheduler](./0621-task-scheduler.js)|Medium| +622|[Design Circular Queue](./0622-design-circular-queue.js)|Medium| 628|[Maximum Product of Three Numbers](./0628-maximum-product-of-three-numbers.js)|Easy| 637|[Average of Levels in Binary Tree](./0637-average-of-levels-in-binary-tree.js)|Easy| 643|[Maximum Average Subarray I](./0643-maximum-average-subarray-i.js)|Easy| From 655871b98bc45da85c20fd255f9a02824d5650a7 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 7 Mar 2025 00:15:32 -0600 Subject: [PATCH 833/919] Add solution #623 --- 0623-add-one-row-to-tree.js | 53 +++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 54 insertions(+) create mode 100644 0623-add-one-row-to-tree.js diff --git a/0623-add-one-row-to-tree.js b/0623-add-one-row-to-tree.js new file mode 100644 index 00000000..32ce3c7d --- /dev/null +++ b/0623-add-one-row-to-tree.js @@ -0,0 +1,53 @@ +/** + * 623. Add One Row to Tree + * https://leetcode.com/problems/add-one-row-to-tree/ + * Difficulty: Medium + * + * Given the root of a binary tree and two integers val and depth, add a row of nodes with value + * val at the given depth depth. + * + * Note that the root node is at depth 1. + * + * The adding rule is: + * - Given the integer depth, for each not null tree node cur at the depth depth - 1, create two + * tree nodes with value val as cur's left subtree root and right subtree root. + * - cur's original left subtree should be the left subtree of the new left subtree root. + * - cur's original right subtree should be the right subtree of the new right subtree root. + * - If depth == 1 that means there is no depth depth - 1 at all, then create a tree node with + * value val as the new root of the whole original tree, and the original tree is the new root's + * left subtree. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @param {number} val + * @param {number} depth + * @return {TreeNode} + */ +var addOneRow = function(root, val, depth) { + if (depth === 1) { + return new TreeNode(val, root); + } + dfs(root, 1); + + return root; + + function dfs(node, level) { + if (!node) return; + if (level === depth - 1) { + node.left = new TreeNode(val, node.left); + node.right = new TreeNode(val, null, node.right); + return; + } + dfs(node.left, level + 1); + dfs(node.right, level + 1); + } +}; diff --git a/README.md b/README.md index 20994283..e90be133 100644 --- a/README.md +++ b/README.md @@ -472,6 +472,7 @@ 617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy| 621|[Task Scheduler](./0621-task-scheduler.js)|Medium| 622|[Design Circular Queue](./0622-design-circular-queue.js)|Medium| +623|[Add One Row to Tree](./0623-add-one-row-to-tree.js)|Medium| 628|[Maximum Product of Three Numbers](./0628-maximum-product-of-three-numbers.js)|Easy| 637|[Average of Levels in Binary Tree](./0637-average-of-levels-in-binary-tree.js)|Easy| 643|[Maximum Average Subarray I](./0643-maximum-average-subarray-i.js)|Easy| From 43ab4f3372007b7bbf41f1cd9eac98afc9613a1d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 7 Mar 2025 00:16:25 -0600 Subject: [PATCH 834/919] Add solution #624 --- 0624-maximum-distance-in-arrays.js | 33 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 0624-maximum-distance-in-arrays.js diff --git a/0624-maximum-distance-in-arrays.js b/0624-maximum-distance-in-arrays.js new file mode 100644 index 00000000..a4a79fea --- /dev/null +++ b/0624-maximum-distance-in-arrays.js @@ -0,0 +1,33 @@ +/** + * 624. Maximum Distance in Arrays + * https://leetcode.com/problems/maximum-distance-in-arrays/ + * Difficulty: Medium + * + * You are given m arrays, where each array is sorted in ascending order. + * + * You can pick up two integers from two different arrays (each array picks one) and calculate + * the distance. We define the distance between two integers a and b to be their absolute + * difference |a - b|. + * + * Return the maximum distance. + */ + +/** + * @param {number[][]} arrays + * @return {number} + */ +var maxDistance = function(arrays) { + let result = 0; + let min = arrays[0][0]; + let max = arrays[0][arrays[0].length - 1]; + + for (let i = 1; i < arrays.length; i++) { + const newMin = arrays[i][0]; + const newMax = arrays[i][arrays[i].length - 1]; + result = Math.max(result, Math.abs(newMax - min), Math.abs(max - newMin)); + min = Math.min(min, newMin); + max = Math.max(max, newMax); + } + + return result; +}; diff --git a/README.md b/README.md index e90be133..feb9ec46 100644 --- a/README.md +++ b/README.md @@ -473,6 +473,7 @@ 621|[Task Scheduler](./0621-task-scheduler.js)|Medium| 622|[Design Circular Queue](./0622-design-circular-queue.js)|Medium| 623|[Add One Row to Tree](./0623-add-one-row-to-tree.js)|Medium| +624|[Maximum Distance in Arrays](./0624-maximum-distance-in-arrays.js)|Medium| 628|[Maximum Product of Three Numbers](./0628-maximum-product-of-three-numbers.js)|Easy| 637|[Average of Levels in Binary Tree](./0637-average-of-levels-in-binary-tree.js)|Easy| 643|[Maximum Average Subarray I](./0643-maximum-average-subarray-i.js)|Easy| From 459f90485737e89cb017304f8c54ad8171d8190a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 7 Mar 2025 00:20:01 -0600 Subject: [PATCH 835/919] Add solution #2523 --- 2523-closest-prime-numbers-in-range.js | 44 ++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 45 insertions(+) create mode 100644 2523-closest-prime-numbers-in-range.js diff --git a/2523-closest-prime-numbers-in-range.js b/2523-closest-prime-numbers-in-range.js new file mode 100644 index 00000000..9deec025 --- /dev/null +++ b/2523-closest-prime-numbers-in-range.js @@ -0,0 +1,44 @@ +/** + * 2523. Closest Prime Numbers in Range + * https://leetcode.com/problems/closest-prime-numbers-in-range/ + * Difficulty: Medium + * + * Given two positive integers left and right, find the two integers num1 and num2 such that: + * - left <= num1 < num2 <= right + * - Both num1 and num2 are prime numbers. + * - num2 - num1 is the minimum amongst all other pairs satisfying the above conditions. + * + * Return the positive integer array ans = [num1, num2]. If there are multiple pairs satisfying + * these conditions, return the one with the smallest num1 value. If no such numbers exist, + * return [-1, -1]. + */ + +/** + * @param {number} left + * @param {number} right + * @return {number[]} + */ +var closestPrimes = function(left, right) { + const group = new Uint8Array(right + 1).fill(1); + let result = [-1, -1]; + + group[0] = group[1] = 0; + for (let i = 2; i * i <= right; i++) { + if (group[i]) { + for (let j = i * i; j <= right; j += i) { + group[j] = 0; + } + } + } + for (let i = Math.max(2, left), prev = -1, min = Infinity; i <= right; i++) { + if (group[i]) { + if (prev !== -1 && i - prev < min) { + min = i - prev; + result = [prev, i]; + } + prev = i; + } + } + + return result; +}; diff --git a/README.md b/README.md index feb9ec46..69dab7b7 100644 --- a/README.md +++ b/README.md @@ -745,6 +745,7 @@ 2482|[Difference Between Ones and Zeros in Row and Column](./2482-difference-between-ones-and-zeros-in-row-and-column.js)|Medium| 2490|[Circular Sentence](./2490-circular-sentence.js)|Easy| 2493|[Divide Nodes Into the Maximum Number of Groups](./2493-divide-nodes-into-the-maximum-number-of-groups.js)|Hard| +2523|[Closest Prime Numbers in Range](./2523-closest-prime-numbers-in-range.js)|Medium| 2529|[Maximum Count of Positive Integer and Negative Integer](./2529-maximum-count-of-positive-integer-and-negative-integer.js)|Easy| 2535|[Difference Between Element Sum and Digit Sum of an Array](./2535-difference-between-element-sum-and-digit-sum-of-an-array.js)|Easy| 2542|[Maximum Subsequence Score](./2542-maximum-subsequence-score.js)|Medium| From 0eb265766825748ba471af320948275fdf078a8e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 7 Mar 2025 00:23:09 -0600 Subject: [PATCH 836/919] Add solution #629 --- 0629-k-inverse-pairs-array.js | 34 ++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 0629-k-inverse-pairs-array.js diff --git a/0629-k-inverse-pairs-array.js b/0629-k-inverse-pairs-array.js new file mode 100644 index 00000000..87ad0955 --- /dev/null +++ b/0629-k-inverse-pairs-array.js @@ -0,0 +1,34 @@ +/** + * 629. K Inverse Pairs Array + * https://leetcode.com/problems/k-inverse-pairs-array/ + * Difficulty: Hard + * + * For an integer array nums, an inverse pair is a pair of integers [i, j] where + * 0 <= i < j < nums.length and nums[i] > nums[j]. + * + * Given two integers n and k, return the number of different arrays consisting of numbers from + * 1 to n such that there are exactly k inverse pairs. Since the answer can be huge, return + * it modulo 109 + 7. + */ + +/** + * @param {number} n + * @param {number} k + * @return {number} + */ +var kInversePairs = function(n, k) { + const MOD = 1e9 + 7; + const dp = new Array(k + 1).fill(0); + + dp[0] = 1; + for (let i = 1; i <= n; i++) { + const previous = dp.slice(); + dp[0] = 1; + for (let j = 1; j <= k; j++) { + dp[j] = (previous[j] + dp[j-1]) % MOD; + if (j >= i) dp[j] = (dp[j] - previous[j-i] + MOD) % MOD; + } + } + + return dp[k]; +}; diff --git a/README.md b/README.md index 69dab7b7..1a5138dd 100644 --- a/README.md +++ b/README.md @@ -475,6 +475,7 @@ 623|[Add One Row to Tree](./0623-add-one-row-to-tree.js)|Medium| 624|[Maximum Distance in Arrays](./0624-maximum-distance-in-arrays.js)|Medium| 628|[Maximum Product of Three Numbers](./0628-maximum-product-of-three-numbers.js)|Easy| +629|[K Inverse Pairs Array](./0629-k-inverse-pairs-array.js)|Hard| 637|[Average of Levels in Binary Tree](./0637-average-of-levels-in-binary-tree.js)|Easy| 643|[Maximum Average Subarray I](./0643-maximum-average-subarray-i.js)|Easy| 645|[Set Mismatch](./0645-set-mismatch.js)|Medium| From 7014b52c5e30515505466bb55fb4fa0bd0f77e95 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 7 Mar 2025 00:28:07 -0600 Subject: [PATCH 837/919] Add solution #630 --- 0630-course-schedule-iii.js | 40 +++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 41 insertions(+) create mode 100644 0630-course-schedule-iii.js diff --git a/0630-course-schedule-iii.js b/0630-course-schedule-iii.js new file mode 100644 index 00000000..6fbed1e6 --- /dev/null +++ b/0630-course-schedule-iii.js @@ -0,0 +1,40 @@ +/** + * 630. Course Schedule III + * https://leetcode.com/problems/course-schedule-iii/ + * Difficulty: Hard + * + * There are n different online courses numbered from 1 to n. You are given an array courses + * where courses[i] = [durationi, lastDayi] indicate that the ith course should be taken + * continuously for durationi days and must be finished before or on lastDayi. + * + * You will start on the 1st day and you cannot take two or more courses simultaneously. + * + * Return the maximum number of courses that you can take. + */ + +/** + * @param {number[][]} courses + * @return {number} + */ +var scheduleCourse = function(courses) { + courses.sort((a, b) => a[1] - b[1]); + + const maxHeap = new PriorityQueue({ compare: (a, b) => b - a }); + let value = 0; + + for (const [duration, lastDay] of courses) { + if (value + duration <= lastDay) { + value += duration; + maxHeap.enqueue(duration); + } else { + if (maxHeap.front() > duration) { + var prev = maxHeap.dequeue(); + value -= prev; + value += duration; + maxHeap.enqueue(duration); + } + } + } + + return maxHeap.size(); +}; diff --git a/README.md b/README.md index 1a5138dd..434375e1 100644 --- a/README.md +++ b/README.md @@ -476,6 +476,7 @@ 624|[Maximum Distance in Arrays](./0624-maximum-distance-in-arrays.js)|Medium| 628|[Maximum Product of Three Numbers](./0628-maximum-product-of-three-numbers.js)|Easy| 629|[K Inverse Pairs Array](./0629-k-inverse-pairs-array.js)|Hard| +630|[Course Schedule III](./0630-course-schedule-iii.js)|Hard| 637|[Average of Levels in Binary Tree](./0637-average-of-levels-in-binary-tree.js)|Easy| 643|[Maximum Average Subarray I](./0643-maximum-average-subarray-i.js)|Easy| 645|[Set Mismatch](./0645-set-mismatch.js)|Medium| From 29969fc8ac3066ef20cb68b589d917013f2f2ef8 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 7 Mar 2025 00:31:12 -0600 Subject: [PATCH 838/919] Add solution #633 --- 0633-sum-of-square-numbers.js | 22 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 23 insertions(+) create mode 100644 0633-sum-of-square-numbers.js diff --git a/0633-sum-of-square-numbers.js b/0633-sum-of-square-numbers.js new file mode 100644 index 00000000..42f3dfa7 --- /dev/null +++ b/0633-sum-of-square-numbers.js @@ -0,0 +1,22 @@ +/** + * 633. Sum of Square Numbers + * https://leetcode.com/problems/sum-of-square-numbers/ + * Difficulty: Medium + * + * Given a non-negative integer c, decide whether there're two integers a and b such + * that a2 + b2 = c. + */ + +/** + * @param {number} c + * @return {boolean} + */ +var judgeSquareSum = function(c) { + for (let left = 0, right = Math.floor(Math.sqrt(c)); left <= right;) { + const sum = left * left + right * right; + if (sum === c) return true; + if (sum < c) left++; + else right--; + } + return false; +}; diff --git a/README.md b/README.md index 434375e1..70886e32 100644 --- a/README.md +++ b/README.md @@ -477,6 +477,7 @@ 628|[Maximum Product of Three Numbers](./0628-maximum-product-of-three-numbers.js)|Easy| 629|[K Inverse Pairs Array](./0629-k-inverse-pairs-array.js)|Hard| 630|[Course Schedule III](./0630-course-schedule-iii.js)|Hard| +633|[Sum of Square Numbers](./0633-sum-of-square-numbers.js)|Medium| 637|[Average of Levels in Binary Tree](./0637-average-of-levels-in-binary-tree.js)|Easy| 643|[Maximum Average Subarray I](./0643-maximum-average-subarray-i.js)|Easy| 645|[Set Mismatch](./0645-set-mismatch.js)|Medium| From 2cca88cac9b2d0bad6572857569b88dbf2761c87 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 7 Mar 2025 00:33:51 -0600 Subject: [PATCH 839/919] Add solution #636 --- 0636-exclusive-time-of-functions.js | 56 +++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 57 insertions(+) create mode 100644 0636-exclusive-time-of-functions.js diff --git a/0636-exclusive-time-of-functions.js b/0636-exclusive-time-of-functions.js new file mode 100644 index 00000000..9c745a51 --- /dev/null +++ b/0636-exclusive-time-of-functions.js @@ -0,0 +1,56 @@ +/** + * 636. Exclusive Time of Functions + * https://leetcode.com/problems/exclusive-time-of-functions/ + * Difficulty: Medium + * + * On a single-threaded CPU, we execute a program containing n functions. Each function has a + * unique ID between 0 and n-1. + * + * Function calls are stored in a call stack: when a function call starts, its ID is pushed + * onto the stack, and when a function call ends, its ID is popped off the stack. The function + * whose ID is at the top of the stack is the current function being executed. Each time a + * function starts or ends, we write a log with the ID, whether it started or ended, and the + * timestamp. + * + * You are given a list logs, where logs[i] represents the ith log message formatted as a string + * "{function_id}:{"start" | "end"}:{timestamp}". For example, "0:start:3" means a function call + * with function ID 0 started at the beginning of timestamp 3, and "1:end:2" means a function + * call with function ID 1 ended at the end of timestamp 2. Note that a function can be called + * multiple times, possibly recursively. + * + * A function's exclusive time is the sum of execution times for all function calls in the program. + * For example, if a function is called twice, one call executing for 2 time units and another + * call executing for 1 time unit, the exclusive time is 2 + 1 = 3. + * + * Return the exclusive time of each function in an array, where the value at the ith index + * represents the exclusive time for the function with ID i. + */ + +/** + * @param {number} n + * @param {string[]} logs + * @return {number[]} + */ +var exclusiveTime = function(n, logs) { + const stack = []; + const result = new Array(n).fill(0); + let previousTime = 0; + + for (const log of logs) { + const [id, action, time] = log.split(':'); + const currentTime = +time; + + if (action === 'start') { + if (stack.length) { + result[stack[stack.length - 1]] += currentTime - previousTime; + } + stack.push(+id); + previousTime = currentTime; + } else { + result[stack.pop()] += currentTime - previousTime + 1; + previousTime = currentTime + 1; + } + } + + return result; +}; diff --git a/README.md b/README.md index 70886e32..cdbf8394 100644 --- a/README.md +++ b/README.md @@ -478,6 +478,7 @@ 629|[K Inverse Pairs Array](./0629-k-inverse-pairs-array.js)|Hard| 630|[Course Schedule III](./0630-course-schedule-iii.js)|Hard| 633|[Sum of Square Numbers](./0633-sum-of-square-numbers.js)|Medium| +636|[Exclusive Time of Functions](./0636-exclusive-time-of-functions.js)|Medium| 637|[Average of Levels in Binary Tree](./0637-average-of-levels-in-binary-tree.js)|Easy| 643|[Maximum Average Subarray I](./0643-maximum-average-subarray-i.js)|Easy| 645|[Set Mismatch](./0645-set-mismatch.js)|Medium| From 52951cd2be99c45f7240e43ad25866bfc3875032 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 7 Mar 2025 22:39:44 -0600 Subject: [PATCH 840/919] Add solution #2379 --- ...olors-to-get-k-consecutive-black-blocks.js | 39 +++++++++++++++++++ README.md | 1 + 2 files changed, 40 insertions(+) create mode 100644 2379-minimum-recolors-to-get-k-consecutive-black-blocks.js diff --git a/2379-minimum-recolors-to-get-k-consecutive-black-blocks.js b/2379-minimum-recolors-to-get-k-consecutive-black-blocks.js new file mode 100644 index 00000000..76994936 --- /dev/null +++ b/2379-minimum-recolors-to-get-k-consecutive-black-blocks.js @@ -0,0 +1,39 @@ +/** + * 2379. Minimum Recolors to Get K Consecutive Black Blocks + * https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks/ + * Difficulty: Easy + * + * You are given a 0-indexed string blocks of length n, where blocks[i] is either 'W' or 'B', + * representing the color of the ith block. The characters 'W' and 'B' denote the colors white + * and black, respectively. + * + * You are also given an integer k, which is the desired number of consecutive black blocks. + * + * In one operation, you can recolor a white block such that it becomes a black block. + * + * Return the minimum number of operations needed such that there is at least one occurrence + * of k consecutive black blocks. + */ + +/** + * @param {string} blocks + * @param {number} k + * @return {number} + */ +var minimumRecolors = function(blocks, k) { + let count = 0; + + for (let i = 0; i < k; i++) { + if (blocks[i] === 'W') count++; + } + + let result = count; + + for (let i = k; i < blocks.length; i++) { + if (blocks[i] === 'W') count++; + if (blocks[i - k] === 'W') count--; + result = Math.min(result, count); + } + + return result; +}; diff --git a/README.md b/README.md index cdbf8394..1aefceff 100644 --- a/README.md +++ b/README.md @@ -735,6 +735,7 @@ 2352|[Equal Row and Column Pairs](./2352-equal-row-and-column-pairs.js)|Medium| 2364|[Count Number of Bad Pairs](./2364-count-number-of-bad-pairs.js)|Medium| 2375|[Construct Smallest Number From DI String](./2375-construct-smallest-number-from-di-string.js)|Medium| +2379|[Minimum Recolors to Get K Consecutive Black Blocks](./2379-minimum-recolors-to-get-k-consecutive-black-blocks.js)|Easy| 2381|[Shifting Letters II](./2381-shifting-letters-ii.js)|Medium| 2390|[Removing Stars From a String](./2390-removing-stars-from-a-string.js)|Medium| 2396|[Strictly Palindromic Number](./2396-strictly-palindromic-number.js)|Medium| From 2f1513e0f282097dee8fd481f8db83f940bfc47e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 7 Mar 2025 22:40:40 -0600 Subject: [PATCH 841/919] Add solution #638 --- 0638-shopping-offers.js | 54 +++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 55 insertions(+) create mode 100644 0638-shopping-offers.js diff --git a/0638-shopping-offers.js b/0638-shopping-offers.js new file mode 100644 index 00000000..1b512cb0 --- /dev/null +++ b/0638-shopping-offers.js @@ -0,0 +1,54 @@ +/** + * 638. Shopping Offers + * https://leetcode.com/problems/shopping-offers/ + * Difficulty: Medium + * + * In LeetCode Store, there are n items to sell. Each item has a price. However, there are + * some special offers, and a special offer consists of one or more different kinds of items + * with a sale price. + * + * You are given an integer array price where price[i] is the price of the ith item, and an + * integer array needs where needs[i] is the number of pieces of the ith item you want to buy. + * + * You are also given an array special where special[i] is of size n + 1 where special[i][j] + * is the number of pieces of the jth item in the ith offer and special[i][n] (i.e., the last + * integer in the array) is the price of the ith offer. + * + * Return the lowest price you have to pay for exactly certain items as given, where you could + * make optimal use of the special offers. You are not allowed to buy more items than you want, + * even if that would lower the overall price. You could use any of the special offers as many + * times as you want. + */ + +/** + * @param {number[]} price + * @param {number[][]} special + * @param {number[]} needs + * @return {number} + */ +var shoppingOffers = function(price, special, needs) { + const map = new Map(); + return dp(needs); + + function dp(input) { + const key = input.join(','); + if (map.has(key)) return map.get(key); + let minCost = input.reduce((sum, need, i) => sum + need * price[i], 0); + for (const offer of special) { + const nextNeeds = [...input]; + let valid = true; + for (let i = 0; i < price.length; i++) { + if (nextNeeds[i] < offer[i]) { + valid = false; + break; + } + nextNeeds[i] -= offer[i]; + } + if (valid) { + minCost = Math.min(minCost, offer[price.length] + dp(nextNeeds)); + } + } + map.set(key, minCost); + return minCost; + } +}; diff --git a/README.md b/README.md index 1aefceff..4d926a06 100644 --- a/README.md +++ b/README.md @@ -480,6 +480,7 @@ 633|[Sum of Square Numbers](./0633-sum-of-square-numbers.js)|Medium| 636|[Exclusive Time of Functions](./0636-exclusive-time-of-functions.js)|Medium| 637|[Average of Levels in Binary Tree](./0637-average-of-levels-in-binary-tree.js)|Easy| +638|[Shopping Offers](./0638-shopping-offers.js)|Medium| 643|[Maximum Average Subarray I](./0643-maximum-average-subarray-i.js)|Easy| 645|[Set Mismatch](./0645-set-mismatch.js)|Medium| 648|[Replace Words](./0648-replace-words.js)|Medium| From 9eb499f17c851d0bb62c014a40914eb2618cbe78 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 7 Mar 2025 22:42:17 -0600 Subject: [PATCH 842/919] Add solution #639 --- 0639-decode-ways-ii.js | 52 ++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 53 insertions(+) create mode 100644 0639-decode-ways-ii.js diff --git a/0639-decode-ways-ii.js b/0639-decode-ways-ii.js new file mode 100644 index 00000000..0a336425 --- /dev/null +++ b/0639-decode-ways-ii.js @@ -0,0 +1,52 @@ +/** + * 639. Decode Ways II + * https://leetcode.com/problems/decode-ways-ii/ + * Difficulty: Hard + * + * A message containing letters from A-Z can be encoded into numbers using the following mapping: + * - 'A' -> "1" + * - 'B' -> "2" + * - 'Z' -> "26" + * + * To decode an encoded message, all the digits must be grouped then mapped back into letters using + * the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped + * into: + * - "AAJF" with the grouping (1 1 10 6) + * - "KJF" with the grouping (11 10 6) + * + * Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is + * different from "06". + * + * In addition to the mapping above, an encoded message may contain the '*' character, which can + * represent any digit from '1' to '9' ('0' is excluded). For example, the encoded message "1*" + * may represent any of the encoded messages "11", "12", "13", "14", "15", "16", "17", "18", or + * "19". Decoding "1*" is equivalent to decoding any of the encoded messages it can represent. + * + * Given a string s consisting of digits and '*' characters, return the number of ways to decode it. + * + * Since the answer may be very large, return it modulo 109 + 7. + */ + +/** + * @param {string} s + * @return {number} + */ +var numDecodings = function(s) { + const mod = 1e9 + 7; + let [i0, i1, i2, i3] = [1, 0, 0, 0]; + + for (const c of s) { + if (c == '*') { + i3 = 9 * i0 + 9 * i1 + 6 * i2; + i1 = i0; + i2 = i0; + } else { + i3 = (c > '0') * i0 + i1 + (c <= '6') * i2; + i1 = (c == '1') * i0; + i2 = (c == '2') * i0; + } + i0 = i3 % mod; + } + + return i0; +}; diff --git a/README.md b/README.md index 4d926a06..36ab338e 100644 --- a/README.md +++ b/README.md @@ -481,6 +481,7 @@ 636|[Exclusive Time of Functions](./0636-exclusive-time-of-functions.js)|Medium| 637|[Average of Levels in Binary Tree](./0637-average-of-levels-in-binary-tree.js)|Easy| 638|[Shopping Offers](./0638-shopping-offers.js)|Medium| +639|[Decode Ways II](./0639-decode-ways-ii.js)|Hard| 643|[Maximum Average Subarray I](./0643-maximum-average-subarray-i.js)|Easy| 645|[Set Mismatch](./0645-set-mismatch.js)|Medium| 648|[Replace Words](./0648-replace-words.js)|Medium| From ee4187a88ec26ac44f80f19c6b41c3b070709155 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 7 Mar 2025 22:44:15 -0600 Subject: [PATCH 843/919] Add solution #641 --- 0641-design-circular-deque.js | 106 ++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 107 insertions(+) create mode 100644 0641-design-circular-deque.js diff --git a/0641-design-circular-deque.js b/0641-design-circular-deque.js new file mode 100644 index 00000000..68deaaf9 --- /dev/null +++ b/0641-design-circular-deque.js @@ -0,0 +1,106 @@ +/** + * 641. Design Circular Deque + * https://leetcode.com/problems/design-circular-deque/ + * Difficulty: Medium + * + * Design your implementation of the circular double-ended queue (deque). + * + * Implement the MyCircularDeque class: + * - MyCircularDeque(int k) Initializes the deque with a maximum size of k. + * - boolean insertFront() Adds an item at the front of Deque. Returns true if the operation + * is successful, or false otherwise. + * - boolean insertLast() Adds an item at the rear of Deque. Returns true if the operation + * is successful, or false otherwise. + * - boolean deleteFront() Deletes an item from the front of Deque. Returns true if the + * operation is successful, or false otherwise. + * - boolean deleteLast() Deletes an item from the rear of Deque. Returns true if the operation + * is successful, or false otherwise. + * - int getFront() Returns the front item from the Deque. Returns -1 if the deque is empty. + * - int getRear() Returns the last item from Deque. Returns -1 if the deque is empty. + * - boolean isEmpty() Returns true if the deque is empty, or false otherwise. + * - boolean isFull() Returns true if the deque is full, or false otherwise. + */ + +/** + * @param {number} k + */ +var MyCircularDeque = function(k) { + this.queue = new Array(k); + this.size = k; + this.front = 0; + this.rear = -1; + this.count = 0; +}; + +/** + * @param {number} value + * @return {boolean} + */ +MyCircularDeque.prototype.insertFront = function(value) { + if (this.isFull()) return false; + this.front = (this.front - 1 + this.size) % this.size; + this.queue[this.front] = value; + this.count++; + if (this.count === 1) this.rear = this.front; + return true; +}; + +/** + * @param {number} value + * @return {boolean} + */ +MyCircularDeque.prototype.insertLast = function(value) { + if (this.isFull()) return false; + this.rear = (this.rear + 1) % this.size; + this.queue[this.rear] = value; + this.count++; + return true; +}; + +/** + * @return {boolean} + */ +MyCircularDeque.prototype.deleteFront = function() { + if (this.isEmpty()) return false; + this.front = (this.front + 1) % this.size; + this.count--; + return true; +}; + +/** + * @return {boolean} + */ +MyCircularDeque.prototype.deleteLast = function() { + if (this.isEmpty()) return false; + this.rear = (this.rear - 1 + this.size) % this.size; + this.count--; + return true; +}; + +/** + * @return {number} + */ +MyCircularDeque.prototype.getFront = function() { + return this.isEmpty() ? -1 : this.queue[this.front]; +}; + +/** + * @return {number} + */ +MyCircularDeque.prototype.getRear = function() { + return this.isEmpty() ? -1 : this.queue[this.rear]; +}; + +/** + * @return {boolean} + */ +MyCircularDeque.prototype.isEmpty = function() { + return this.count === 0; +}; + +/** + * @return {boolean} + */ +MyCircularDeque.prototype.isFull = function() { + return this.count === this.size; +}; diff --git a/README.md b/README.md index 36ab338e..4d9099f0 100644 --- a/README.md +++ b/README.md @@ -482,6 +482,7 @@ 637|[Average of Levels in Binary Tree](./0637-average-of-levels-in-binary-tree.js)|Easy| 638|[Shopping Offers](./0638-shopping-offers.js)|Medium| 639|[Decode Ways II](./0639-decode-ways-ii.js)|Hard| +641|[Design Circular Deque](./0641-design-circular-deque.js)|Medium| 643|[Maximum Average Subarray I](./0643-maximum-average-subarray-i.js)|Easy| 645|[Set Mismatch](./0645-set-mismatch.js)|Medium| 648|[Replace Words](./0648-replace-words.js)|Medium| From ca9bf6691302f16cd039e51a5b4acfc96a2fdd01 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Fri, 7 Mar 2025 22:45:11 -0600 Subject: [PATCH 844/919] Add solution #646 --- 0646-maximum-length-of-pair-chain.js | 33 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 0646-maximum-length-of-pair-chain.js diff --git a/0646-maximum-length-of-pair-chain.js b/0646-maximum-length-of-pair-chain.js new file mode 100644 index 00000000..077b2d91 --- /dev/null +++ b/0646-maximum-length-of-pair-chain.js @@ -0,0 +1,33 @@ +/** + * 646. Maximum Length of Pair Chain + * https://leetcode.com/problems/maximum-length-of-pair-chain/ + * Difficulty: Medium + * + * You are given an array of n pairs pairs where pairs[i] = [lefti, righti] and lefti < righti. + * + * A pair p2 = [c, d] follows a pair p1 = [a, b] if b < c. A chain of pairs can be formed in + * this fashion. + * + * Return the length longest chain which can be formed. + * + * You do not need to use up all the given intervals. You can select pairs in any order. + */ + +/** + * @param {number[][]} pairs + * @return {number} + */ +var findLongestChain = function(pairs) { + pairs.sort((a, b) => a[1] - b[1]); + let pointer = -Infinity; + let result = 0; + + for (const [start, end] of pairs) { + if (start > pointer) { + pointer = end; + result++; + } + } + + return result; +}; diff --git a/README.md b/README.md index 4d9099f0..de42e412 100644 --- a/README.md +++ b/README.md @@ -485,6 +485,7 @@ 641|[Design Circular Deque](./0641-design-circular-deque.js)|Medium| 643|[Maximum Average Subarray I](./0643-maximum-average-subarray-i.js)|Easy| 645|[Set Mismatch](./0645-set-mismatch.js)|Medium| +646|[Maximum Length of Pair Chain](./0646-maximum-length-of-pair-chain.js)|Medium| 648|[Replace Words](./0648-replace-words.js)|Medium| 649|[Dota2 Senate](./0649-dota2-senate.js)|Medium| 653|[Two Sum IV - Input is a BST](./0653-two-sum-iv-input-is-a-bst.js)|Easy| From 6beadb92ce5a8cd4e6c55a8e13e502fcac34137e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 8 Mar 2025 11:17:42 -0600 Subject: [PATCH 845/919] Add solution #647 --- 0647-palindromic-substrings.js | 36 ++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 37 insertions(+) create mode 100644 0647-palindromic-substrings.js diff --git a/0647-palindromic-substrings.js b/0647-palindromic-substrings.js new file mode 100644 index 00000000..e7465fc7 --- /dev/null +++ b/0647-palindromic-substrings.js @@ -0,0 +1,36 @@ +/** + * 647. Palindromic Substrings + * https://leetcode.com/problems/palindromic-substrings/ + * Difficulty: Medium + * + * Given a string s, return the number of palindromic substrings in it. + * + * A string is a palindrome when it reads the same backward as forward. + * + * A substring is a contiguous sequence of characters within the string. + */ + +/** + * @param {string} s + * @return {number} + */ +var countSubstrings = function(s) { + let result = 0; + + for (let i = 0; i < s.length; i++) { + result += expand(i, i); + result += expand(i, i + 1); + } + + return result; + + function expand(left, right) { + let count = 0; + while (left >= 0 && right < s.length && s[left] === s[right]) { + count++; + left--; + right++; + } + return count; + } +}; diff --git a/README.md b/README.md index de42e412..98245952 100644 --- a/README.md +++ b/README.md @@ -486,6 +486,7 @@ 643|[Maximum Average Subarray I](./0643-maximum-average-subarray-i.js)|Easy| 645|[Set Mismatch](./0645-set-mismatch.js)|Medium| 646|[Maximum Length of Pair Chain](./0646-maximum-length-of-pair-chain.js)|Medium| +647|[Palindromic Substrings](./0647-palindromic-substrings.js)|Medium| 648|[Replace Words](./0648-replace-words.js)|Medium| 649|[Dota2 Senate](./0649-dota2-senate.js)|Medium| 653|[Two Sum IV - Input is a BST](./0653-two-sum-iv-input-is-a-bst.js)|Easy| From 5b31661bae3f9ad03b9c8d941dae4ad0d4d0dceb Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 8 Mar 2025 11:18:30 -0600 Subject: [PATCH 846/919] Add solution #650 --- 0650-2-keys-keyboard.js | 32 ++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 0650-2-keys-keyboard.js diff --git a/0650-2-keys-keyboard.js b/0650-2-keys-keyboard.js new file mode 100644 index 00000000..d2169c05 --- /dev/null +++ b/0650-2-keys-keyboard.js @@ -0,0 +1,32 @@ +/** + * 650. 2 Keys Keyboard + * https://leetcode.com/problems/2-keys-keyboard/ + * Difficulty: Medium + * + * There is only one character 'A' on the screen of a notepad. You can perform one of two + * operations on this notepad for each step: + * - Copy All: You can copy all the characters present on the screen (a partial copy is + * not allowed). + * - Paste: You can paste the characters which are copied last time. + * + * Given an integer n, return the minimum number of operations to get the character 'A' + * exactly n times on the screen. + */ + +/** + * @param {number} n + * @return {number} + */ +var minSteps = function(n) { + let result = 0; + + for (let factor = 2; n > 1;) { + while (n % factor === 0) { + result += factor; + n /= factor; + } + factor++; + } + + return result; +}; diff --git a/README.md b/README.md index 98245952..4a666507 100644 --- a/README.md +++ b/README.md @@ -489,6 +489,7 @@ 647|[Palindromic Substrings](./0647-palindromic-substrings.js)|Medium| 648|[Replace Words](./0648-replace-words.js)|Medium| 649|[Dota2 Senate](./0649-dota2-senate.js)|Medium| +650|[2 Keys Keyboard](./0650-2-keys-keyboard.js)|Medium| 653|[Two Sum IV - Input is a BST](./0653-two-sum-iv-input-is-a-bst.js)|Easy| 654|[Maximum Binary Tree](./0654-maximum-binary-tree.js)|Medium| 680|[Valid Palindrome II](./0680-valid-palindrome-ii.js)|Easy| From ecb7e5d7a2f4e399147413c7503d81c26dfe79f8 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 8 Mar 2025 11:20:33 -0600 Subject: [PATCH 847/919] Add solution #652 --- 0652-find-duplicate-subtrees.js | 42 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 43 insertions(+) create mode 100644 0652-find-duplicate-subtrees.js diff --git a/0652-find-duplicate-subtrees.js b/0652-find-duplicate-subtrees.js new file mode 100644 index 00000000..dd8640c1 --- /dev/null +++ b/0652-find-duplicate-subtrees.js @@ -0,0 +1,42 @@ +/** + * 652. Find Duplicate Subtrees + * https://leetcode.com/problems/find-duplicate-subtrees/ + * Difficulty: Medium + * + * Given the root of a binary tree, return all duplicate subtrees. + * + * For each kind of duplicate subtrees, you only need to return the root node of any one of them. + * + * Two trees are duplicate if they have the same structure with the same node values. + */ + +/** + * 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 findDuplicateSubtrees = function(root) { + const map = new Map(); + const result = []; + + serialize(root); + + return result; + + function serialize(node) { + if (!node) return '#'; + const key = `${node.val},${serialize(node.left)},${serialize(node.right)}`; + map.set(key, (map.get(key) || 0) + 1); + if (map.get(key) === 2) { + result.push(node); + } + return key; + } +}; diff --git a/README.md b/README.md index 4a666507..0cdcf11c 100644 --- a/README.md +++ b/README.md @@ -490,6 +490,7 @@ 648|[Replace Words](./0648-replace-words.js)|Medium| 649|[Dota2 Senate](./0649-dota2-senate.js)|Medium| 650|[2 Keys Keyboard](./0650-2-keys-keyboard.js)|Medium| +652|[Find Duplicate Subtrees](./0652-find-duplicate-subtrees.js)|Medium| 653|[Two Sum IV - Input is a BST](./0653-two-sum-iv-input-is-a-bst.js)|Easy| 654|[Maximum Binary Tree](./0654-maximum-binary-tree.js)|Medium| 680|[Valid Palindrome II](./0680-valid-palindrome-ii.js)|Easy| From f6c09b398f673c16b1a92776f99aceecbdc70bc4 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 8 Mar 2025 11:21:54 -0600 Subject: [PATCH 848/919] Add solution #655 --- 0655-print-binary-tree.js | 54 +++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 55 insertions(+) create mode 100644 0655-print-binary-tree.js diff --git a/0655-print-binary-tree.js b/0655-print-binary-tree.js new file mode 100644 index 00000000..038e3050 --- /dev/null +++ b/0655-print-binary-tree.js @@ -0,0 +1,54 @@ +/** + * 655. Print Binary Tree + * https://leetcode.com/problems/print-binary-tree/ + * Difficulty: Medium + * + * Given the root of a binary tree, construct a 0-indexed m x n string matrix res that represents + * a formatted layout of the tree. The formatted layout matrix should be constructed using the + * following rules: + * - The height of the tree is height and the number of rows m should be equal to height + 1. + * - The number of columns n should be equal to 2height+1 - 1. + * - Place the root node in the middle of the top row (more formally, at location res[0][(n-1)/2]). + * - For each node that has been placed in the matrix at position res[r][c], place its left child at + * res[r+1][c-2height-r-1] and its right child at res[r+1][c+2height-r-1]. + * - Continue this process until all the nodes in the tree have been placed. + * - Any empty cells should contain the empty string "". + * + * Return the constructed matrix res. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {string[][]} + */ +var printTree = function(root) { + const height = getHeight(root); + const columns = Math.pow(2, height + 1) - 1; + const result = new Array(height + 1).fill().map(() => { + return new Array(columns).fill(''); + }); + + fill(root, 0, Math.floor((columns - 1) / 2), height); + + return result; + + function fill(node, r, c, h) { + if (!node) return; + result[r][c] = node.val.toString(); + fill(node.left, r + 1, c - Math.pow(2, h - r - 1), h); + fill(node.right, r + 1, c + Math.pow(2, h - r - 1), h); + } + + function getHeight(node) { + if (!node) return -1; + return 1 + Math.max(getHeight(node.left), getHeight(node.right)); + } +}; diff --git a/README.md b/README.md index 0cdcf11c..a6acba22 100644 --- a/README.md +++ b/README.md @@ -493,6 +493,7 @@ 652|[Find Duplicate Subtrees](./0652-find-duplicate-subtrees.js)|Medium| 653|[Two Sum IV - Input is a BST](./0653-two-sum-iv-input-is-a-bst.js)|Easy| 654|[Maximum Binary Tree](./0654-maximum-binary-tree.js)|Medium| +655|[Print Binary Tree](./0655-print-binary-tree.js)|Medium| 680|[Valid Palindrome II](./0680-valid-palindrome-ii.js)|Easy| 684|[Redundant Connection](./0684-redundant-connection.js)|Medium| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| From 96fb5694d0fb7f79f55bce1c3893f7de9d5d8a9b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 8 Mar 2025 11:23:05 -0600 Subject: [PATCH 849/919] Add solution #657 --- 0657-robot-return-to-origin.js | 38 ++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 39 insertions(+) create mode 100644 0657-robot-return-to-origin.js diff --git a/0657-robot-return-to-origin.js b/0657-robot-return-to-origin.js new file mode 100644 index 00000000..06c01e35 --- /dev/null +++ b/0657-robot-return-to-origin.js @@ -0,0 +1,38 @@ +/** + * 657. Robot Return to Origin + * https://leetcode.com/problems/robot-return-to-origin/ + * Difficulty: Easy + * + * There is a robot starting at the position (0, 0), the origin, on a 2D plane. Given a sequence + * of its moves, judge if this robot ends up at (0, 0) after it completes its moves. + * + * You are given a string moves that represents the move sequence of the robot where moves[i] + * represents its ith move. Valid moves are 'R' (right), 'L' (left), 'U' (up), and 'D' (down). + * + * Return true if the robot returns to the origin after it finishes all of its moves, or false + * otherwise. + * + * Note: The way that the robot is "facing" is irrelevant. 'R' will always make the robot move + * to the right once, 'L' will always make it move left, etc. Also, assume that the magnitude + * of the robot's movement is the same for each move. + */ + +/** + * @param {string} moves + * @return {boolean} + */ +/** + * @param {string} moves + * @return {boolean} + */ +var judgeCircle = function(moves) { + let x = 0; + let y = 0; + + for (const move of moves) { + x += move === 'R' ? 1 : move === 'L' ? -1 : 0; + y += move === 'U' ? 1 : move === 'D' ? -1 : 0; + } + + return x === 0 && y === 0; +}; diff --git a/README.md b/README.md index a6acba22..75baadb6 100644 --- a/README.md +++ b/README.md @@ -494,6 +494,7 @@ 653|[Two Sum IV - Input is a BST](./0653-two-sum-iv-input-is-a-bst.js)|Easy| 654|[Maximum Binary Tree](./0654-maximum-binary-tree.js)|Medium| 655|[Print Binary Tree](./0655-print-binary-tree.js)|Medium| +657|[Robot Return to Origin](./0657-robot-return-to-origin.js)|Easy| 680|[Valid Palindrome II](./0680-valid-palindrome-ii.js)|Easy| 684|[Redundant Connection](./0684-redundant-connection.js)|Medium| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| From 8f58cd7886a9af581f5fb163071b41a697bba659 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 8 Mar 2025 11:27:38 -0600 Subject: [PATCH 850/919] Add solution #658 --- 0658-find-k-closest-elements.js | 37 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 38 insertions(+) create mode 100644 0658-find-k-closest-elements.js diff --git a/0658-find-k-closest-elements.js b/0658-find-k-closest-elements.js new file mode 100644 index 00000000..390c7b23 --- /dev/null +++ b/0658-find-k-closest-elements.js @@ -0,0 +1,37 @@ +/** + * 658. Find K Closest Elements + * https://leetcode.com/problems/find-k-closest-elements/ + * Difficulty: Medium + * + * Given a sorted integer array arr, two integers k and x, return the k closest integers to x + * in the array. The result should also be sorted in ascending order. + * + * An integer a is closer to x than an integer b if: + * - |a - x| < |b - x|, or + * - |a - x| == |b - x| and a < b + */ + +/** + * @param {number[]} arr + * @param {number} k + * @param {number} x + * @return {number[]} + */ +var findClosestElements = function(arr, k, x) { + let left = 0; + let right = arr.length - k; + + while (left < right) { + const middle = Math.floor((left + right) / 2); + const x1 = arr[middle]; + const x2 = arr[middle + k]; + + if (x - x1 > x2 - x) { + left = middle + 1; + } else { + right = middle; + } + } + + return arr.slice(left, left + k); +}; diff --git a/README.md b/README.md index 75baadb6..66441b7d 100644 --- a/README.md +++ b/README.md @@ -495,6 +495,7 @@ 654|[Maximum Binary Tree](./0654-maximum-binary-tree.js)|Medium| 655|[Print Binary Tree](./0655-print-binary-tree.js)|Medium| 657|[Robot Return to Origin](./0657-robot-return-to-origin.js)|Easy| +658|[Find K Closest Elements](./0658-find-k-closest-elements.js)|Medium| 680|[Valid Palindrome II](./0680-valid-palindrome-ii.js)|Easy| 684|[Redundant Connection](./0684-redundant-connection.js)|Medium| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| From e1120fa1bc488d500ffbb2862f733d13431fb81a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 8 Mar 2025 11:32:38 -0600 Subject: [PATCH 851/919] Add solution #659 --- ...lit-array-into-consecutive-subsequences.js | 51 +++++++++++++++++++ README.md | 1 + 2 files changed, 52 insertions(+) create mode 100644 0659-split-array-into-consecutive-subsequences.js diff --git a/0659-split-array-into-consecutive-subsequences.js b/0659-split-array-into-consecutive-subsequences.js new file mode 100644 index 00000000..002105c8 --- /dev/null +++ b/0659-split-array-into-consecutive-subsequences.js @@ -0,0 +1,51 @@ +/** + * 659. Split Array into Consecutive Subsequences + * https://leetcode.com/problems/split-array-into-consecutive-subsequences/ + * Difficulty: Medium + * + * You are given an integer array nums that is sorted in non-decreasing order. + * + * Determine if it is possible to split nums into one or more subsequences such that both of the + * following conditions are true: + * - Each subsequence is a consecutive increasing sequence (i.e. each integer is exactly one more + * than the previous integer). + * - All subsequences have a length of 3 or more. + * + * Return true if you can split nums according to the above conditions, or false otherwise. + * + * A subsequence of an array is a new array that is formed from the original array by deleting some + * (can be none) of the elements without disturbing the relative positions of the remaining + * elements. (i.e., [1,3,5] is a subsequence of [1,2,3,4,5] while [1,3,2] is not). + */ + +/** + * @param {number[]} nums + * @return {boolean} + */ +var isPossible = function(nums) { + const map = new Map(); + const map2 = new Map(); + + for (const n of nums) { + map.set(n, (map.get(n) || 0) + 1); + } + + for (const n of nums) { + if (map.get(n) === 0) continue; + + if ((map2.get(n) || 0) > 0) { + map2.set(n, map2.get(n) - 1); + map.set(n, map.get(n) - 1); + map2.set(n + 1, (map2.get(n + 1) || 0) + 1); + } else if ((map.get(n) || 0) > 0 && (map.get(n + 1) || 0) > 0 && (map.get(n + 2) || 0) > 0) { + map.set(n, map.get(n) - 1); + map.set(n + 1, map.get(n + 1) - 1); + map.set(n + 2, map.get(n + 2) - 1); + map2.set(n + 3, (map2.get(n + 3) || 0) + 1); + } else { + return false; + } + } + + return true; +}; diff --git a/README.md b/README.md index 66441b7d..89a772ed 100644 --- a/README.md +++ b/README.md @@ -496,6 +496,7 @@ 655|[Print Binary Tree](./0655-print-binary-tree.js)|Medium| 657|[Robot Return to Origin](./0657-robot-return-to-origin.js)|Easy| 658|[Find K Closest Elements](./0658-find-k-closest-elements.js)|Medium| +659|[Split Array into Consecutive Subsequences](./0659-split-array-into-consecutive-subsequences.js)|Medium| 680|[Valid Palindrome II](./0680-valid-palindrome-ii.js)|Easy| 684|[Redundant Connection](./0684-redundant-connection.js)|Medium| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| From 1fcc7d91d2f27dc1035f77d417b9e39bce4f4a44 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 8 Mar 2025 11:35:38 -0600 Subject: [PATCH 852/919] Add solution #661 --- 0661-image-smoother.js | 44 ++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 45 insertions(+) create mode 100644 0661-image-smoother.js diff --git a/0661-image-smoother.js b/0661-image-smoother.js new file mode 100644 index 00000000..61921b33 --- /dev/null +++ b/0661-image-smoother.js @@ -0,0 +1,44 @@ +/** + * 661. Image Smoother + * https://leetcode.com/problems/image-smoother/ + * Difficulty: Easy + * + * An image smoother is a filter of the size 3 x 3 that can be applied to each cell of an image by + * rounding down the average of the cell and the eight surrounding cells (i.e., the average of the + * nine cells in the blue smoother). If one or more of the surrounding cells of a cell is not + * present, we do not consider it in the average (i.e., the average of the four cells in the red + * smoother). + * + * Given an m x n integer matrix img representing the grayscale of an image, return the image after + * applying the smoother on each cell of it. + */ + +/** + * @param {number[][]} img + * @return {number[][]} + */ +var imageSmoother = function(img) { + const result = new Array(img.length).fill().map(() => { + return new Array(img[0].length).fill(0); + }); + + for (let i = 0; i < img.length; i++) { + for (let j = 0; j < img[0].length; j++) { + let sum = 0; + let count = 0; + for (let di = -1; di <= 1; di++) { + for (let dj = -1; dj <= 1; dj++) { + const ni = i + di; + const nj = j + dj; + if (ni >= 0 && ni < img.length && nj >= 0 && nj < img[0].length) { + sum += img[ni][nj]; + count++; + } + } + } + result[i][j] = Math.floor(sum / count); + } + } + + return result; +}; diff --git a/README.md b/README.md index 89a772ed..e743299c 100644 --- a/README.md +++ b/README.md @@ -497,6 +497,7 @@ 657|[Robot Return to Origin](./0657-robot-return-to-origin.js)|Easy| 658|[Find K Closest Elements](./0658-find-k-closest-elements.js)|Medium| 659|[Split Array into Consecutive Subsequences](./0659-split-array-into-consecutive-subsequences.js)|Medium| +661|[Image Smoother](./0661-image-smoother.js)|Easy| 680|[Valid Palindrome II](./0680-valid-palindrome-ii.js)|Easy| 684|[Redundant Connection](./0684-redundant-connection.js)|Medium| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| From 32d55d9e9c6d723fd5b8e674e055e31245e9c3a6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 8 Mar 2025 11:38:35 -0600 Subject: [PATCH 853/919] Add solution #662 --- 0662-maximum-width-of-binary-tree.js | 52 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 53 insertions(+) create mode 100644 0662-maximum-width-of-binary-tree.js diff --git a/0662-maximum-width-of-binary-tree.js b/0662-maximum-width-of-binary-tree.js new file mode 100644 index 00000000..bdc8ccc0 --- /dev/null +++ b/0662-maximum-width-of-binary-tree.js @@ -0,0 +1,52 @@ +/** + * 662. Maximum Width of Binary Tree + * https://leetcode.com/problems/maximum-width-of-binary-tree/ + * Difficulty: Medium + * + * Given the root of a binary tree, return the maximum width of the given tree. + * + * The maximum width of a tree is the maximum width among all levels. + * + * The width of one level is defined as the length between the end-nodes (the leftmost and + * rightmost non-null nodes), where the null nodes between the end-nodes that would be present + * in a complete binary tree extending down to that level are also counted into the length + * calculation. + * + * It is guaranteed that the answer will in the range of a 32-bit signed integer. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number} + */ +var widthOfBinaryTree = function(root) { + const queue = [[root, 0n]]; + let result = 0n; + + while (queue.length) { + const total = queue.length; + const levelStart = queue[0][1]; + let levelEnd; + + for (let i = 0; i < total; i++) { + const [node, index] = queue.shift(); + levelEnd = index; + if (node.left) queue.push([node.left, index * 2n]); + if (node.right) queue.push([node.right, index * 2n + 1n]); + } + + result = result > (levelEnd - levelStart + 1n) + ? result + : (levelEnd - levelStart + 1n); + } + + return Number(result); +}; diff --git a/README.md b/README.md index e743299c..5fd95ba2 100644 --- a/README.md +++ b/README.md @@ -498,6 +498,7 @@ 658|[Find K Closest Elements](./0658-find-k-closest-elements.js)|Medium| 659|[Split Array into Consecutive Subsequences](./0659-split-array-into-consecutive-subsequences.js)|Medium| 661|[Image Smoother](./0661-image-smoother.js)|Easy| +662|[Maximum Width of Binary Tree](./0662-maximum-width-of-binary-tree.js)|Medium| 680|[Valid Palindrome II](./0680-valid-palindrome-ii.js)|Easy| 684|[Redundant Connection](./0684-redundant-connection.js)|Medium| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| From 3a7d1bd62ee430455bd172eef91611c24368aad9 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 8 Mar 2025 11:40:37 -0600 Subject: [PATCH 854/919] Add solution #664 --- 0664-strange-printer.js | 35 +++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 36 insertions(+) create mode 100644 0664-strange-printer.js diff --git a/0664-strange-printer.js b/0664-strange-printer.js new file mode 100644 index 00000000..e1b8af3c --- /dev/null +++ b/0664-strange-printer.js @@ -0,0 +1,35 @@ +/** + * 664. Strange Printer + * https://leetcode.com/problems/strange-printer/ + * Difficulty: Hard + * + * There is a strange printer with the following two special properties: + * - The printer can only print a sequence of the same character each time. + * - At each turn, the printer can print new characters starting from and ending at any place and + * will cover the original existing characters. + * + * Given a string s, return the minimum number of turns the printer needed to print it. + */ + +/** + * @param {string} s + * @return {number} + */ +var strangePrinter = function(s) { + const n = s.length; + const dp = new Array(n).fill().map(() => new Array(n).fill(0)); + + for (let i = n - 1; i >= 0; i--) { + dp[i][i] = 1; + for (let j = i + 1; j < n; j++) { + dp[i][j] = dp[i][j - 1] + 1; + for (let k = i; k < j; k++) { + if (s[k] === s[j]) { + dp[i][j] = Math.min(dp[i][j], dp[i][k] + (k + 1 <= j - 1 ? dp[k + 1][j - 1] : 0)); + } + } + } + } + + return dp[0][n - 1]; +}; diff --git a/README.md b/README.md index 5fd95ba2..1edc0b1a 100644 --- a/README.md +++ b/README.md @@ -499,6 +499,7 @@ 659|[Split Array into Consecutive Subsequences](./0659-split-array-into-consecutive-subsequences.js)|Medium| 661|[Image Smoother](./0661-image-smoother.js)|Easy| 662|[Maximum Width of Binary Tree](./0662-maximum-width-of-binary-tree.js)|Medium| +664|[Strange Printer](./0664-strange-printer.js)|Hard| 680|[Valid Palindrome II](./0680-valid-palindrome-ii.js)|Easy| 684|[Redundant Connection](./0684-redundant-connection.js)|Medium| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| From f323eb6a46700616c40f645b5b022469daf698f2 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 8 Mar 2025 22:58:37 -0600 Subject: [PATCH 855/919] Add solution #3208 --- 3208-alternating-groups-ii.js | 46 +++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 47 insertions(+) create mode 100644 3208-alternating-groups-ii.js diff --git a/3208-alternating-groups-ii.js b/3208-alternating-groups-ii.js new file mode 100644 index 00000000..6d4be0de --- /dev/null +++ b/3208-alternating-groups-ii.js @@ -0,0 +1,46 @@ +/** + * 3208. Alternating Groups II + * https://leetcode.com/problems/alternating-groups-ii/ + * Difficulty: Medium + * + * There is a circle of red and blue tiles. You are given an array of integers colors and + * an integer k. The color of tile i is represented by colors[i]: + * - colors[i] == 0 means that tile i is red. + * -colors[i] == 1 means that tile i is blue. + * + * An alternating group is every k contiguous tiles in the circle with alternating colors + * (each tile in the group except the first and last one has a different color from its + * left and right tiles). + * + * Return the number of alternating groups. + * + * Note that since colors represents a circle, the first and the last tiles are considered + * to be next to each other. + */ + +/** + * @param {number[]} colors + * @param {number} k + * @return {number} + */ +var numberOfAlternatingGroups = function(colors, k) { + const extended = colors.concat(colors.slice(0, k - 1)); + let result = 0; + let invalid = 0; + + for (let i = 1; i < k; i++) { + if (extended[i] === extended[i - 1]) { + invalid++; + } + } + if (invalid === 0) { + result++; + } + for (let i = 1; i < colors.length; i++) { + if (extended[i] === extended[i - 1]) invalid--; + if (extended[i + k - 1] === extended[i + k - 2]) invalid++; + if (invalid === 0) result++; + } + + return result; +}; diff --git a/README.md b/README.md index 1edc0b1a..fb27f78e 100644 --- a/README.md +++ b/README.md @@ -820,6 +820,7 @@ 3151|[Special Array I](./3151-special-array-i.js)|Easy| 3160|[Find the Number of Distinct Colors Among the Balls](./3160-find-the-number-of-distinct-colors-among-the-balls.js)|Medium| 3174|[Clear Digits](./3174-clear-digits.js)|Easy| +3208|[Alternating Groups II](./3208-alternating-groups-ii.js)|Medium| 3223|[Minimum Length of String After Operations](./3223-minimum-length-of-string-after-operations.js)|Medium| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| 3396|[Minimum Number of Operations to Make Elements in Array Distinct](./3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy| From dcba9cf6dadbea14a74dd516211b3fe94724a6f2 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 8 Mar 2025 23:00:43 -0600 Subject: [PATCH 856/919] Add solution #2559 --- 2559-count-vowel-strings-in-ranges.js | 28 +++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 29 insertions(+) create mode 100644 2559-count-vowel-strings-in-ranges.js diff --git a/2559-count-vowel-strings-in-ranges.js b/2559-count-vowel-strings-in-ranges.js new file mode 100644 index 00000000..80d61e6a --- /dev/null +++ b/2559-count-vowel-strings-in-ranges.js @@ -0,0 +1,28 @@ +/** + * 2559. Count Vowel Strings in Ranges + * https://leetcode.com/problems/count-vowel-strings-in-ranges/ + * Difficulty: Medium + * + * You are given a 0-indexed array of strings words and a 2D array of integers queries. + * + * Each query queries[i] = [li, ri] asks us to find the number of strings present at the + * indices ranging from li to ri (both inclusive) of words that start and end with a vowel. + * + * Return an array ans of size queries.length, where ans[i] is the answer to the ith query. + * + * Note that the vowel letters are 'a', 'e', 'i', 'o', and 'u'. + */ + +/** + * @param {string[]} words + * @param {number[][]} queries + * @return {number[]} + */ +var vowelStrings = function(words, queries) { + const vowels = new Set(['a', 'e', 'i', 'o', 'u']); + const prefix = [0]; + for (let i = 0; i < words.length; i++) { + prefix[i + 1] = prefix[i] + (vowels.has(words[i][0]) && vowels.has(words[i].at(-1))); + } + return queries.map(([l, r]) => prefix[r + 1] - prefix[l]); +}; diff --git a/README.md b/README.md index fb27f78e..1c734c73 100644 --- a/README.md +++ b/README.md @@ -768,6 +768,7 @@ 2529|[Maximum Count of Positive Integer and Negative Integer](./2529-maximum-count-of-positive-integer-and-negative-integer.js)|Easy| 2535|[Difference Between Element Sum and Digit Sum of an Array](./2535-difference-between-element-sum-and-digit-sum-of-an-array.js)|Easy| 2542|[Maximum Subsequence Score](./2542-maximum-subsequence-score.js)|Medium| +2559|[Count Vowel Strings in Ranges](./2559-count-vowel-strings-in-ranges.js)|Medium| 2570|[Merge Two 2D Arrays by Summing Values](./2570-merge-two-2d-arrays-by-summing-values.js)|Easy| 2579|[Count Total Number of Colored Cells](./2579-count-total-number-of-colored-cells.js)|Medium| 2618|[Check if Object Instance of Class](./2618-check-if-object-instance-of-class.js)|Medium| From 77d34dbf1f8b2337f60d91f0cc3a0f168d810ee3 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 8 Mar 2025 23:04:17 -0600 Subject: [PATCH 857/919] Add solution #667 --- 0667-beautiful-arrangement-ii.js | 32 ++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 0667-beautiful-arrangement-ii.js diff --git a/0667-beautiful-arrangement-ii.js b/0667-beautiful-arrangement-ii.js new file mode 100644 index 00000000..56883ac1 --- /dev/null +++ b/0667-beautiful-arrangement-ii.js @@ -0,0 +1,32 @@ +/** + * 667. Beautiful Arrangement II + * https://leetcode.com/problems/beautiful-arrangement-ii/ + * Difficulty: Medium + * + * Given two integers n and k, construct a list answer that contains n different positive integers + * ranging from 1 to n and obeys the following requirement: + * - Suppose this list is answer = [a1, a2, a3, ... , an], then the list [|a1 - a2|, |a2 - a3|, + * |a3 - a4|, ... , |an-1 - an|] has exactly k distinct integers. + * + * Return the list answer. If there multiple valid answers, return any of them. + */ + +/** + * @param {number} n + * @param {number} k + * @return {number[]} + */ +var constructArray = function(n, k) { + const result = []; + + for (let i = 0, left = 1, right = n; i < n; i++) { + if (k > 1) { + result.push(k % 2 === 0 ? right-- : left++); + k--; + } else { + result.push(left++); + } + } + + return result; +}; diff --git a/README.md b/README.md index 1c734c73..932d2d46 100644 --- a/README.md +++ b/README.md @@ -500,6 +500,7 @@ 661|[Image Smoother](./0661-image-smoother.js)|Easy| 662|[Maximum Width of Binary Tree](./0662-maximum-width-of-binary-tree.js)|Medium| 664|[Strange Printer](./0664-strange-printer.js)|Hard| +667|[Beautiful Arrangement II](./0667-beautiful-arrangement-ii.js)|Medium| 680|[Valid Palindrome II](./0680-valid-palindrome-ii.js)|Easy| 684|[Redundant Connection](./0684-redundant-connection.js)|Medium| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| From 2947d0cc1c8792ba10f23f9f2b849dab6da97c6c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 8 Mar 2025 23:09:13 -0600 Subject: [PATCH 858/919] Add solution #668 --- ...smallest-number-in-multiplication-table.js | 41 +++++++++++++++++++ README.md | 1 + 2 files changed, 42 insertions(+) create mode 100644 0668-kth-smallest-number-in-multiplication-table.js diff --git a/0668-kth-smallest-number-in-multiplication-table.js b/0668-kth-smallest-number-in-multiplication-table.js new file mode 100644 index 00000000..97313f29 --- /dev/null +++ b/0668-kth-smallest-number-in-multiplication-table.js @@ -0,0 +1,41 @@ +/** + * 668. Kth Smallest Number in Multiplication Table + * https://leetcode.com/problems/kth-smallest-number-in-multiplication-table/ + * Difficulty: Hard + * + * Nearly everyone has used the Multiplication Table. The multiplication table of size m x n is + * an integer matrix mat where mat[i][j] == i * j (1-indexed). + * + * Given three integers m, n, and k, return the kth smallest element in the m x n multiplication + * table. + */ + +/** + * @param {number} m + * @param {number} n + * @param {number} k + * @return {number} + */ +var findKthNumber = function(m, n, k) { + let low = 1; + let high = m * n; + + while (low < high) { + const middle = Math.floor((low + high) / 2); + if (helper(middle) < k) { + low = middle + 1; + } else { + high = middle; + } + } + + return low; + + function helper(x) { + let count = 0; + for (let i = 1; i <= m; i++) { + count += Math.min(Math.floor(x / i), n); + } + return count; + } +}; diff --git a/README.md b/README.md index 932d2d46..f0ceeb09 100644 --- a/README.md +++ b/README.md @@ -501,6 +501,7 @@ 662|[Maximum Width of Binary Tree](./0662-maximum-width-of-binary-tree.js)|Medium| 664|[Strange Printer](./0664-strange-printer.js)|Hard| 667|[Beautiful Arrangement II](./0667-beautiful-arrangement-ii.js)|Medium| +668|[Kth Smallest Number in Multiplication Table](./0668-kth-smallest-number-in-multiplication-table.js)|Hard| 680|[Valid Palindrome II](./0680-valid-palindrome-ii.js)|Easy| 684|[Redundant Connection](./0684-redundant-connection.js)|Medium| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| From a1fff115e57d0921136a8180a520a3081d8ef08e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sat, 8 Mar 2025 23:11:04 -0600 Subject: [PATCH 859/919] Add solution #670 --- 0670-maximum-swap.js | 31 +++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 0670-maximum-swap.js diff --git a/0670-maximum-swap.js b/0670-maximum-swap.js new file mode 100644 index 00000000..d1886730 --- /dev/null +++ b/0670-maximum-swap.js @@ -0,0 +1,31 @@ +/** + * 670. Maximum Swap + * https://leetcode.com/problems/maximum-swap/ + * Difficulty: Medium + * + * You are given an integer num. You can swap two digits at most once to get the maximum + * valued number. + * + * Return the maximum valued number you can get. + */ + +/** + * @param {number} num + * @return {number} + */ +var maximumSwap = function(num) { + const digits = [...(num).toString()]; + const last = new Array(10).fill(-1); + digits.forEach((d, i) => last[d] = i); + + for (let i = 0; i < digits.length; i++) { + for (let d = 9; d > digits[i]; d--) { + if (last[d] > i) { + [digits[i], digits[last[d]]] = [digits[last[d]], digits[i]]; + return +digits.join(''); + } + } + } + + return num; +}; diff --git a/README.md b/README.md index f0ceeb09..0aaa2e7a 100644 --- a/README.md +++ b/README.md @@ -502,6 +502,7 @@ 664|[Strange Printer](./0664-strange-printer.js)|Hard| 667|[Beautiful Arrangement II](./0667-beautiful-arrangement-ii.js)|Medium| 668|[Kth Smallest Number in Multiplication Table](./0668-kth-smallest-number-in-multiplication-table.js)|Hard| +670|[Maximum Swap](./0670-maximum-swap.js)|Medium| 680|[Valid Palindrome II](./0680-valid-palindrome-ii.js)|Easy| 684|[Redundant Connection](./0684-redundant-connection.js)|Medium| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| From dbee10071e8b411ab243fe4aed0094cd3076cf52 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 9 Mar 2025 00:38:17 -0600 Subject: [PATCH 860/919] Add solution #669 --- 0669-trim-a-binary-search-tree.js | 38 +++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 39 insertions(+) create mode 100644 0669-trim-a-binary-search-tree.js diff --git a/0669-trim-a-binary-search-tree.js b/0669-trim-a-binary-search-tree.js new file mode 100644 index 00000000..69eb15c7 --- /dev/null +++ b/0669-trim-a-binary-search-tree.js @@ -0,0 +1,38 @@ +/** + * 669. Trim a Binary Search Tree + * https://leetcode.com/problems/trim-a-binary-search-tree/ + * Difficulty: Medium + * + * Given the root of a binary search tree and the lowest and highest boundaries as low and high, + * trim the tree so that all its elements lies in [low, high]. Trimming the tree should not change + * the relative structure of the elements that will remain in the tree (i.e., any node's descendant + * should remain a descendant). It can be proven that there is a unique answer. + * + * Return the root of the trimmed binary search tree. Note that the root may change depending on + * the given bounds. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @param {number} low + * @param {number} high + * @return {TreeNode} + */ +var trimBST = function(root, low, high) { + if (!root) return null; + + if (root.val < low) return trimBST(root.right, low, high); + if (root.val > high) return trimBST(root.left, low, high); + root.left = trimBST(root.left, low, high); + root.right = trimBST(root.right, low, high); + + return root; +}; diff --git a/README.md b/README.md index 0aaa2e7a..be9878de 100644 --- a/README.md +++ b/README.md @@ -502,6 +502,7 @@ 664|[Strange Printer](./0664-strange-printer.js)|Hard| 667|[Beautiful Arrangement II](./0667-beautiful-arrangement-ii.js)|Medium| 668|[Kth Smallest Number in Multiplication Table](./0668-kth-smallest-number-in-multiplication-table.js)|Hard| +669|[Trim a Binary Search Tree](./0669-trim-a-binary-search-tree.js)|Medium| 670|[Maximum Swap](./0670-maximum-swap.js)|Medium| 680|[Valid Palindrome II](./0680-valid-palindrome-ii.js)|Easy| 684|[Redundant Connection](./0684-redundant-connection.js)|Medium| From 47772622deb279ffb4e1567b2728b20acfb18182 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 9 Mar 2025 00:40:34 -0600 Subject: [PATCH 861/919] Add solution #671 --- 0671-second-minimum-node-in-a-binary-tree.js | 36 ++++++++++++++++++++ README.md | 1 + 2 files changed, 37 insertions(+) create mode 100644 0671-second-minimum-node-in-a-binary-tree.js diff --git a/0671-second-minimum-node-in-a-binary-tree.js b/0671-second-minimum-node-in-a-binary-tree.js new file mode 100644 index 00000000..8f8a3d48 --- /dev/null +++ b/0671-second-minimum-node-in-a-binary-tree.js @@ -0,0 +1,36 @@ +/** + * 671. Second Minimum Node In a Binary Tree + * https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/ + * Difficulty: Easy + * + * Given a non-empty special binary tree consisting of nodes with the non-negative value, + * where each node in this tree has exactly two or zero sub-node. If the node has two + * sub-nodes, then this node's value is the smaller value among its two sub-nodes. More + * formally, the property root.val = min(root.left.val, root.right.val) always holds. + * + * Given such a binary tree, you need to output the second minimum value in the set made + * of all the nodes' value in the whole tree. + * + * If no such second minimum value exists, output -1 instead. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number} + */ +var findSecondMinimumValue = function(root) { + return root ? (n => n === Infinity ? -1 : n)(traverse(root, root.val)) : -1; + function traverse(node, min) { + if (!node) return Infinity; + if (node.val > min) return node.val; + return Math.min(traverse(node.left, min), traverse(node.right, min)); + } +}; diff --git a/README.md b/README.md index be9878de..3cf4812b 100644 --- a/README.md +++ b/README.md @@ -504,6 +504,7 @@ 668|[Kth Smallest Number in Multiplication Table](./0668-kth-smallest-number-in-multiplication-table.js)|Hard| 669|[Trim a Binary Search Tree](./0669-trim-a-binary-search-tree.js)|Medium| 670|[Maximum Swap](./0670-maximum-swap.js)|Medium| +671|[Second Minimum Node In a Binary Tree](./0671-second-minimum-node-in-a-binary-tree.js)|Easy| 680|[Valid Palindrome II](./0680-valid-palindrome-ii.js)|Easy| 684|[Redundant Connection](./0684-redundant-connection.js)|Medium| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| From ba311a72fb87f2cefc2018493ebeed190eb4704e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 9 Mar 2025 00:43:03 -0600 Subject: [PATCH 862/919] Add solution #672 --- 0672-bulb-switcher-ii.js | 32 ++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 0672-bulb-switcher-ii.js diff --git a/0672-bulb-switcher-ii.js b/0672-bulb-switcher-ii.js new file mode 100644 index 00000000..554c9d0a --- /dev/null +++ b/0672-bulb-switcher-ii.js @@ -0,0 +1,32 @@ +/** + * 672. Bulb Switcher II + * https://leetcode.com/problems/bulb-switcher-ii/ + * Difficulty: Medium + * + * There is a room with n bulbs labeled from 1 to n that all are turned on initially, and four + * buttons on the wall. Each of the four buttons has a different functionality where: + * - Button 1: Flips the status of all the bulbs. + * - Button 2: Flips the status of all the bulbs with even labels (i.e., 2, 4, ...). + * - Button 3: Flips the status of all the bulbs with odd labels (i.e., 1, 3, ...). + * - Button 4: Flips the status of all the bulbs with a label j = 3k + 1 where k = 0, 1, 2, ... + * (i.e., 1, 4, 7, 10, ...). + * - You must make exactly presses button presses in total. For each press, you may pick any + * of the four buttons to press. + * + * Given the two integers n and presses, return the number of different possible statuses after + * performing all presses button presses. + */ + +/** + * @param {number} n + * @param {number} presses + * @return {number} + */ +var flipLights = function(n, presses) { + if (presses === 0) return 1; + if (n === 1) return presses >= 1 ? 2 : 1; + if (n === 2) return presses === 1 ? 3 : 4; + if (presses === 1) return 4; + if (presses === 2) return 7; + return 8; +}; diff --git a/README.md b/README.md index 3cf4812b..7d47fbe1 100644 --- a/README.md +++ b/README.md @@ -505,6 +505,7 @@ 669|[Trim a Binary Search Tree](./0669-trim-a-binary-search-tree.js)|Medium| 670|[Maximum Swap](./0670-maximum-swap.js)|Medium| 671|[Second Minimum Node In a Binary Tree](./0671-second-minimum-node-in-a-binary-tree.js)|Easy| +672|[Bulb Switcher II](./0672-bulb-switcher-ii.js)|Medium| 680|[Valid Palindrome II](./0680-valid-palindrome-ii.js)|Easy| 684|[Redundant Connection](./0684-redundant-connection.js)|Medium| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| From f174b61064a5bbf023c97f88f56458e9480c90d3 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 9 Mar 2025 00:46:47 -0600 Subject: [PATCH 863/919] Add solution #673 --- ...umber-of-longest-increasing-subsequence.js | 36 +++++++++++++++++++ README.md | 1 + 2 files changed, 37 insertions(+) create mode 100644 0673-number-of-longest-increasing-subsequence.js diff --git a/0673-number-of-longest-increasing-subsequence.js b/0673-number-of-longest-increasing-subsequence.js new file mode 100644 index 00000000..a7c2adcf --- /dev/null +++ b/0673-number-of-longest-increasing-subsequence.js @@ -0,0 +1,36 @@ +/** + * 673. Number of Longest Increasing Subsequence + * https://leetcode.com/problems/number-of-longest-increasing-subsequence/ + * Difficulty: Medium + * + * Given an integer array nums, return the number of longest increasing subsequences. + * + * Notice that the sequence has to be strictly increasing. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var findNumberOfLIS = function(nums) { + const lengths = new Array(nums.length).fill(1); + const counts = new Array(nums.length).fill(1); + + for (let i = 1; i < nums.length; i++) { + for (let j = 0; j < i; j++) { + if (nums[i] > nums[j]) { + if (lengths[j] + 1 > lengths[i]) { + lengths[i] = lengths[j] + 1; + counts[i] = counts[j]; + } else if (lengths[j] + 1 === lengths[i]) { + counts[i] += counts[j]; + } + } + } + } + + const max = Math.max(...lengths); + return lengths.reduce((sum, l, i) => { + return sum + (l === max ? counts[i] : 0); + }, 0); +}; diff --git a/README.md b/README.md index 7d47fbe1..72f3ac69 100644 --- a/README.md +++ b/README.md @@ -506,6 +506,7 @@ 670|[Maximum Swap](./0670-maximum-swap.js)|Medium| 671|[Second Minimum Node In a Binary Tree](./0671-second-minimum-node-in-a-binary-tree.js)|Easy| 672|[Bulb Switcher II](./0672-bulb-switcher-ii.js)|Medium| +673|[Number of Longest Increasing Subsequence](./0673-number-of-longest-increasing-subsequence.js)|Medium| 680|[Valid Palindrome II](./0680-valid-palindrome-ii.js)|Easy| 684|[Redundant Connection](./0684-redundant-connection.js)|Medium| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| From bb1fb2ceee4b121ee16b52d91f21bfaa4f05bb1f Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 9 Mar 2025 00:48:21 -0600 Subject: [PATCH 864/919] Add solution #674 --- ...ngest-continuous-increasing-subsequence.js | 26 +++++++++++++++++++ README.md | 1 + 2 files changed, 27 insertions(+) create mode 100644 0674-longest-continuous-increasing-subsequence.js diff --git a/0674-longest-continuous-increasing-subsequence.js b/0674-longest-continuous-increasing-subsequence.js new file mode 100644 index 00000000..09057b94 --- /dev/null +++ b/0674-longest-continuous-increasing-subsequence.js @@ -0,0 +1,26 @@ +/** + * 674. Longest Continuous Increasing Subsequence + * https://leetcode.com/problems/longest-continuous-increasing-subsequence/ + * Difficulty: Easy + * + * Given an unsorted array of integers nums, return the length of the longest continuous increasing + * subsequence (i.e. subarray). The subsequence must be strictly increasing. + * + * A continuous increasing subsequence is defined by two indices l and r (l < r) such that it is + * [nums[l], nums[l + 1], ..., nums[r - 1], nums[r]] and for each l <= i < r, nums[i] < nums[i + 1]. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var findLengthOfLCIS = function(nums) { + let result = 1; + + for (let i = 1, v = 1; i < nums.length; i++) { + v = nums[i] > nums[i-1] ? v + 1 : 1; + result = Math.max(result, v); + } + + return result; +}; diff --git a/README.md b/README.md index 72f3ac69..a567e691 100644 --- a/README.md +++ b/README.md @@ -507,6 +507,7 @@ 671|[Second Minimum Node In a Binary Tree](./0671-second-minimum-node-in-a-binary-tree.js)|Easy| 672|[Bulb Switcher II](./0672-bulb-switcher-ii.js)|Medium| 673|[Number of Longest Increasing Subsequence](./0673-number-of-longest-increasing-subsequence.js)|Medium| +674|[Longest Continuous Increasing Subsequence](./0674-longest-continuous-increasing-subsequence.js)|Easy| 680|[Valid Palindrome II](./0680-valid-palindrome-ii.js)|Easy| 684|[Redundant Connection](./0684-redundant-connection.js)|Medium| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| From f6ecd5bc57c56068e9c92e951af57e227da94924 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 9 Mar 2025 00:57:59 -0600 Subject: [PATCH 865/919] Add solution #675 --- 0675-cut-off-trees-for-golf-event.js | 74 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 75 insertions(+) create mode 100644 0675-cut-off-trees-for-golf-event.js diff --git a/0675-cut-off-trees-for-golf-event.js b/0675-cut-off-trees-for-golf-event.js new file mode 100644 index 00000000..fb6b8f1c --- /dev/null +++ b/0675-cut-off-trees-for-golf-event.js @@ -0,0 +1,74 @@ +/** + * 675. Cut Off Trees for Golf Event + * https://leetcode.com/problems/cut-off-trees-for-golf-event/ + * Difficulty: Hard + * + * You are asked to cut off all the trees in a forest for a golf event. The forest is represented + * as an m x n matrix. In this matrix: + * - 0 means the cell cannot be walked through. + * - 1 represents an empty cell that can be walked through. + * - A number greater than 1 represents a tree in a cell that can be walked through, and this number + * is the tree's height. + * + * In one step, you can walk in any of the four directions: north, east, south, and west. If you are + * standing in a cell with a tree, you can choose whether to cut it off. + * + * You must cut off the trees in order from shortest to tallest. When you cut off a tree, the value + * at its cell becomes 1 (an empty cell). + * + * Starting from the point (0, 0), return the minimum steps you need to walk to cut off all the + * trees. If you cannot cut off all the trees, return -1. + * + * Note: The input is generated such that no two trees have the same height, and there is at least + * one tree needs to be cut off. + */ + +/** + * @param {number[][]} forest + * @return {number} + */ +const cutOffTree = (forest) => { + const treeHeights = forest.flat().filter((height) => height > 1).sort((a, b) => a - b); + let currentPosition = [0, 0]; + let totalDistance = 0; + + while (treeHeights.length) { + const gridCopy = forest.map((row) => [...row]); + const result = findDistance(currentPosition, treeHeights.shift(), gridCopy); + if (result === null) return -1; + const [nextPosition, distance] = result; + currentPosition = nextPosition; + totalDistance += distance; + } + return totalDistance; + + function findDistance(startPosition, targetHeight, grid) { + const directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]; + let queue = [startPosition]; + let distance = 0; + + while (queue.length) { + const nextLevel = []; + + for (const [row, col] of queue) { + if (grid[row][col] === targetHeight) return [[row, col], distance]; + if (!grid[row][col]) continue; + + for (const [deltaRow, deltaCol] of directions) { + const newRow = row + deltaRow; + const newCol = col + deltaCol; + if ( + newRow >= 0 && newRow < grid.length && newCol >= 0 + && newCol < grid[0].length && grid[newRow][newCol] + ) { + nextLevel.push([newRow, newCol]); + } + } + grid[row][col] = 0; + } + distance += 1; + queue = nextLevel; + } + return null; + } +}; diff --git a/README.md b/README.md index a567e691..b80bb18f 100644 --- a/README.md +++ b/README.md @@ -508,6 +508,7 @@ 672|[Bulb Switcher II](./0672-bulb-switcher-ii.js)|Medium| 673|[Number of Longest Increasing Subsequence](./0673-number-of-longest-increasing-subsequence.js)|Medium| 674|[Longest Continuous Increasing Subsequence](./0674-longest-continuous-increasing-subsequence.js)|Easy| +675|[Cut Off Trees for Golf Event](./0675-cut-off-trees-for-golf-event.js)|Hard| 680|[Valid Palindrome II](./0680-valid-palindrome-ii.js)|Easy| 684|[Redundant Connection](./0684-redundant-connection.js)|Medium| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| From bde6d5a7cfc903bfcaa9962bdb42d5d6921d8cca Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 9 Mar 2025 01:03:18 -0600 Subject: [PATCH 866/919] Add solution #676 --- 0676-implement-magic-dictionary.js | 45 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 46 insertions(+) create mode 100644 0676-implement-magic-dictionary.js diff --git a/0676-implement-magic-dictionary.js b/0676-implement-magic-dictionary.js new file mode 100644 index 00000000..d470c460 --- /dev/null +++ b/0676-implement-magic-dictionary.js @@ -0,0 +1,45 @@ +/** + * 676. Implement Magic Dictionary + * https://leetcode.com/problems/implement-magic-dictionary/ + * Difficulty: Medium + * + * Design a data structure that is initialized with a list of different words. Provided a string, + * you should determine if you can change exactly one character in this string to match any word + * in the data structure. + * + * Implement the MagicDictionary class: + * - MagicDictionary() Initializes the object. + * - void buildDict(String[] dictionary) Sets the data structure with an array of distinct + * strings dictionary. + * - bool search(String searchWord) Returns true if you can change exactly one character in + * searchWord to match any string in the data structure, otherwise returns false. + */ + +var MagicDictionary = function() { + this.words = new Set(); +}; + +/** + * @param {string[]} dictionary + * @return {void} + */ +MagicDictionary.prototype.buildDict = function(dictionary) { + this.words = new Set(dictionary); +}; + +/** + * @param {string} searchWord + * @return {boolean} + */ +MagicDictionary.prototype.search = function(searchWord) { + const words = searchWord.split(''); + return Array.from(this.words).some(word => { + if (word.length !== searchWord.length) return false; + let diff = 0; + for (let i = 0; i < word.length; i++) { + if (word[i] !== words[i]) diff++; + if (diff > 1) return false; + } + return diff === 1; + }); +}; diff --git a/README.md b/README.md index b80bb18f..2dadaf03 100644 --- a/README.md +++ b/README.md @@ -509,6 +509,7 @@ 673|[Number of Longest Increasing Subsequence](./0673-number-of-longest-increasing-subsequence.js)|Medium| 674|[Longest Continuous Increasing Subsequence](./0674-longest-continuous-increasing-subsequence.js)|Easy| 675|[Cut Off Trees for Golf Event](./0675-cut-off-trees-for-golf-event.js)|Hard| +676|[Implement Magic Dictionary](./0676-implement-magic-dictionary.js)|Medium| 680|[Valid Palindrome II](./0680-valid-palindrome-ii.js)|Easy| 684|[Redundant Connection](./0684-redundant-connection.js)|Medium| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| From 2d0252b69b53f3c0e0ea6341235da28d97521bbb Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 9 Mar 2025 01:06:21 -0600 Subject: [PATCH 867/919] Add solution #677 --- 0677-map-sum-pairs.js | 39 +++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 40 insertions(+) create mode 100644 0677-map-sum-pairs.js diff --git a/0677-map-sum-pairs.js b/0677-map-sum-pairs.js new file mode 100644 index 00000000..4e66ad3f --- /dev/null +++ b/0677-map-sum-pairs.js @@ -0,0 +1,39 @@ +/** + * 677. Map Sum Pairs + * https://leetcode.com/problems/map-sum-pairs/ + * Difficulty: Medium + * + * Design a map that allows you to do the following: + * - Maps a string key to a given value. + * - Returns the sum of the values that have a key with a prefix equal to a given string. + * + * Implement the MapSum class: + * - MapSum() Initializes the MapSum object. + * - void insert(String key, int val) Inserts the key-val pair into the map. If the key + * already existed, the original key-value pair will be overridden to the new one. + * - int sum(string prefix) Returns the sum of all the pairs' value whose key starts + * with the prefix. + */ + +var MapSum = function() { + this.map = new Map(); +}; + +/** + * @param {string} key + * @param {number} val + * @return {void} + */ +MapSum.prototype.insert = function(key, val) { + this.map.set(key, val); +}; + +/** + * @param {string} prefix + * @return {number} + */ +MapSum.prototype.sum = function(prefix) { + return [...this.map.entries()].reduce((total, [key, val]) => { + return key.startsWith(prefix) ? total + val : total; + }, 0); +}; diff --git a/README.md b/README.md index 2dadaf03..222bc447 100644 --- a/README.md +++ b/README.md @@ -510,6 +510,7 @@ 674|[Longest Continuous Increasing Subsequence](./0674-longest-continuous-increasing-subsequence.js)|Easy| 675|[Cut Off Trees for Golf Event](./0675-cut-off-trees-for-golf-event.js)|Hard| 676|[Implement Magic Dictionary](./0676-implement-magic-dictionary.js)|Medium| +677|[Map Sum Pairs](./0677-map-sum-pairs.js)|Medium| 680|[Valid Palindrome II](./0680-valid-palindrome-ii.js)|Easy| 684|[Redundant Connection](./0684-redundant-connection.js)|Medium| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| From 0e843b69f5f6901b15737adc0721d3e8386da0a0 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 9 Mar 2025 01:08:19 -0600 Subject: [PATCH 868/919] Add solution #678 --- 0678-valid-parenthesis-string.js | 33 ++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 0678-valid-parenthesis-string.js diff --git a/0678-valid-parenthesis-string.js b/0678-valid-parenthesis-string.js new file mode 100644 index 00000000..e148d6db --- /dev/null +++ b/0678-valid-parenthesis-string.js @@ -0,0 +1,33 @@ +/** + * 678. Valid Parenthesis String + * https://leetcode.com/problems/valid-parenthesis-string/ + * Difficulty: Medium + * + * Given a string s containing only three types of characters: '(', ')' and '*', return + * true if s is valid. + * + * The following rules define a valid string: + * - Any left parenthesis '(' must have a corresponding right parenthesis ')'. + * - Any right parenthesis ')' must have a corresponding left parenthesis '('. + * - Left parenthesis '(' must go before the corresponding right parenthesis ')'. + * - '*' could be treated as a single right parenthesis ')' or a single left parenthesis + * '(' or an empty string "". + */ + +/** + * @param {string} s + * @return {boolean} + */ +var checkValidString = function(s) { + let result = 0; + let offset = 0; + + for (const character of s) { + result += character === '(' ? 1 : -1; + offset += character !== ')' ? 1 : -1; + if (offset < 0) return false; + result = Math.max(0, result); + } + + return !result; +}; diff --git a/README.md b/README.md index 222bc447..82ceb70c 100644 --- a/README.md +++ b/README.md @@ -511,6 +511,7 @@ 675|[Cut Off Trees for Golf Event](./0675-cut-off-trees-for-golf-event.js)|Hard| 676|[Implement Magic Dictionary](./0676-implement-magic-dictionary.js)|Medium| 677|[Map Sum Pairs](./0677-map-sum-pairs.js)|Medium| +678|[Valid Parenthesis String](./0678-valid-parenthesis-string.js)|Medium| 680|[Valid Palindrome II](./0680-valid-palindrome-ii.js)|Easy| 684|[Redundant Connection](./0684-redundant-connection.js)|Medium| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| From b2f7bffcff8342dd56781d452dad74d37f3680f1 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 9 Mar 2025 01:15:07 -0600 Subject: [PATCH 869/919] Add solution #679 --- 0679-24-game.js | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 49 insertions(+) create mode 100644 0679-24-game.js diff --git a/0679-24-game.js b/0679-24-game.js new file mode 100644 index 00000000..ac6bac86 --- /dev/null +++ b/0679-24-game.js @@ -0,0 +1,48 @@ +/** + * 679. 24 Game + * https://leetcode.com/problems/24-game/ + * Difficulty: Hard + * + * You are given an integer array cards of length 4. You have four cards, each containing a number + * in the range [1, 9]. You should arrange the numbers on these cards in a mathematical expression + * using the operators ['+', '-', '*', '/'] and the parentheses '(' and ')' to get the value 24. + * + * You are restricted with the following rules: + * - The division operator '/' represents real division, not integer division. + * - For example, 4 / (1 - 2 / 3) = 4 / (1 / 3) = 12. + * - Every operation done is between two numbers. In particular, we cannot use '-' as a + * unary operator. + * - For example, if cards = [1, 1, 1, 1], the expression "-1 - 1 - 1 - 1" is not allowed. + * - You cannot concatenate numbers together + * - For example, if cards = [1, 2, 1, 2], the expression "12 + 12" is not valid. + * + * Return true if you can get such expression that evaluates to 24, and false otherwise. + */ + +/** + * @param {number[]} cards + * @return {boolean} + */ +const judgePoint24 = function(cards) { + if (cards.length === 1) return Math.abs(cards[0] - 24) < 0.1; + + for (let i = 0; i < cards.length; i++) { + for (let j = i + 1; j < cards.length; j++) { + const remaining = new Array(cards.length - 1); + for (let index = 0, current = 0; current < cards.length; current++) { + if (i === current || j === current) continue; + remaining[index++] = cards[current]; + } + const a = cards[i]; + const b = cards[j]; + const operations = [a + b, a - b, b - a, a * b, a / b, b / a]; + for (const result of operations) { + if (result === 0) continue; + remaining[cards.length - 2] = result; + if (judgePoint24(remaining)) return true; + } + } + } + + return false; +}; diff --git a/README.md b/README.md index 82ceb70c..58015099 100644 --- a/README.md +++ b/README.md @@ -512,6 +512,7 @@ 676|[Implement Magic Dictionary](./0676-implement-magic-dictionary.js)|Medium| 677|[Map Sum Pairs](./0677-map-sum-pairs.js)|Medium| 678|[Valid Parenthesis String](./0678-valid-parenthesis-string.js)|Medium| +679|[24 Game](./0679-24-game.js)|Hard| 680|[Valid Palindrome II](./0680-valid-palindrome-ii.js)|Easy| 684|[Redundant Connection](./0684-redundant-connection.js)|Medium| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| From 19cd7f0c2849922a10d182c871967b0fb604443a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 9 Mar 2025 21:24:35 -0500 Subject: [PATCH 870/919] Add solution #3306 --- ...taining-every-vowel-and-k-consonants-ii.js | 48 +++++++++++++++++++ README.md | 1 + 2 files changed, 49 insertions(+) create mode 100644 3306-count-of-substrings-containing-every-vowel-and-k-consonants-ii.js diff --git a/3306-count-of-substrings-containing-every-vowel-and-k-consonants-ii.js b/3306-count-of-substrings-containing-every-vowel-and-k-consonants-ii.js new file mode 100644 index 00000000..7e8f635d --- /dev/null +++ b/3306-count-of-substrings-containing-every-vowel-and-k-consonants-ii.js @@ -0,0 +1,48 @@ +/** + * 3306. Count of Substrings Containing Every Vowel and K Consonants II + * https://leetcode.com/problems/count-of-substrings-containing-every-vowel-and-k-consonants-ii/ + * Difficulty: Medium + * + * You are given a string word and a non-negative integer k. + * + * Return the total number of substrings of word that contain every vowel ('a', 'e', 'i', 'o', and + * 'u') at least once and exactly k consonants. + */ + +/** + * @param {string} word + * @param {number} k + * @return {number} + */ +function countOfSubstrings(word, k) { + return helper(word, k) - helper(word, k - 1); + + function helper(word, k) { + const vowels = { a: 0, e: 0, i: 0, o: 0, u: 0 }; + let count = 0; + let left = 0; + let consonants = k; + + for (let right = 0; right < word.length; right++) { + const character = word[right]; + if (character in vowels) { + vowels[character]++; + } else { + consonants--; + } + + while (vowels.a > 0 && vowels.e > 0 && vowels.i > 0 && vowels.o > 0 + && vowels.u > 0 && consonants < 0) { + const leftCharacter = word[left]; + if (leftCharacter in vowels) { + vowels[leftCharacter]--; + } else { + consonants++; + } + left++; + } + count += right - left + 1; + } + return count; + } +} diff --git a/README.md b/README.md index 58015099..028bd5c9 100644 --- a/README.md +++ b/README.md @@ -836,6 +836,7 @@ 3174|[Clear Digits](./3174-clear-digits.js)|Easy| 3208|[Alternating Groups II](./3208-alternating-groups-ii.js)|Medium| 3223|[Minimum Length of String After Operations](./3223-minimum-length-of-string-after-operations.js)|Medium| +3306|[Count of Substrings Containing Every Vowel and K Consonants II](./3306-count-of-substrings-containing-every-vowel-and-k-consonants-ii.js)|Medium| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| 3396|[Minimum Number of Operations to Make Elements in Array Distinct](./3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy| 3397|[Maximum Number of Distinct Elements After Operations](./3397-maximum-number-of-distinct-elements-after-operations.js)|Medium| From 2169b922dea03c992fac567eb177304ff1c88db9 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 9 Mar 2025 21:26:08 -0500 Subject: [PATCH 871/919] Add solution #3461 --- ...-are-equal-in-string-after-operations-i.js | 29 +++++++++++++++++++ README.md | 1 + 2 files changed, 30 insertions(+) create mode 100644 3461-check-if-digits-are-equal-in-string-after-operations-i.js diff --git a/3461-check-if-digits-are-equal-in-string-after-operations-i.js b/3461-check-if-digits-are-equal-in-string-after-operations-i.js new file mode 100644 index 00000000..bd801d33 --- /dev/null +++ b/3461-check-if-digits-are-equal-in-string-after-operations-i.js @@ -0,0 +1,29 @@ +/** + * 3461. Check If Digits Are Equal in String After Operations I + * https://leetcode.com/problems/check-if-digits-are-equal-in-string-after-operations-i/ + * Difficulty: Easy + * + * You are given a string s consisting of digits. Perform the following operation repeatedly + * until the string has exactly two digits: + * - For each pair of consecutive digits in s, starting from the first digit, calculate a new + * digit as the sum of the two digits modulo 10. + * - Replace s with the sequence of newly calculated digits, maintaining the order in which + * they are computed. + * + * Return true if the final two digits in s are the same; otherwise, return false. + */ + +/** + * @param {string} s + * @return {boolean} + */ +var hasSameDigits = function(s) { + while (s.length > 2) { + let next = ''; + for (let i = 0; i < s.length - 1; i++) { + next += (parseInt(s[i]) + parseInt(s[i + 1])) % 10; + } + s = next; + } + return s[0] === s[1]; +}; diff --git a/README.md b/README.md index 028bd5c9..d9d0c406 100644 --- a/README.md +++ b/README.md @@ -842,6 +842,7 @@ 3397|[Maximum Number of Distinct Elements After Operations](./3397-maximum-number-of-distinct-elements-after-operations.js)|Medium| 3402|[Minimum Operations to Make Columns Strictly Increasing](./3402-minimum-operations-to-make-columns-strictly-increasing.js)|Easy| 3452|[Sum of Good Numbers](./3452-sum-of-good-numbers.js)|Easy| +3461|[Check If Digits Are Equal in String After Operations I](./3461-check-if-digits-are-equal-in-string-after-operations-i.js)|Easy| ## License From 9ff69b5c02e4f10002841d9e42a438b912bb1112 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 9 Mar 2025 21:27:22 -0500 Subject: [PATCH 872/919] Add solution #3462 --- 3462-maximum-sum-with-at-most-k-elements.js | 26 +++++++++++++++++++++ README.md | 1 + 2 files changed, 27 insertions(+) create mode 100644 3462-maximum-sum-with-at-most-k-elements.js diff --git a/3462-maximum-sum-with-at-most-k-elements.js b/3462-maximum-sum-with-at-most-k-elements.js new file mode 100644 index 00000000..aafcd08f --- /dev/null +++ b/3462-maximum-sum-with-at-most-k-elements.js @@ -0,0 +1,26 @@ +/** + * 3462. Maximum Sum With at Most K Elements + * https://leetcode.com/problems/maximum-sum-with-at-most-k-elements/ + * Difficulty: Medium + * + * You are given a 2D integer matrix grid of size n x m, an integer array limits of length n, and + * an integer k. The task is to find the maximum sum of at most k elements from the matrix grid + * such that: + * - The number of elements taken from the ith row of grid does not exceed limits[i]. + * + * Return the maximum sum. + */ + +/** + * @param {number[][]} grid + * @param {number[]} limits + * @param {number} k + * @return {number} + */ +var maxSum = function(grid, limits, k) { + const result = []; + grid.forEach((row, i) => { + result.push(...row.slice().sort((a, b) => b - a).slice(0, limits[i])); + }); + return result.sort((a, b) => b - a).slice(0, k).reduce((sum, num) => sum + num, 0); +}; diff --git a/README.md b/README.md index d9d0c406..76fdc87c 100644 --- a/README.md +++ b/README.md @@ -843,6 +843,7 @@ 3402|[Minimum Operations to Make Columns Strictly Increasing](./3402-minimum-operations-to-make-columns-strictly-increasing.js)|Easy| 3452|[Sum of Good Numbers](./3452-sum-of-good-numbers.js)|Easy| 3461|[Check If Digits Are Equal in String After Operations I](./3461-check-if-digits-are-equal-in-string-after-operations-i.js)|Easy| +3462|[Maximum Sum With at Most K Elements](./3462-maximum-sum-with-at-most-k-elements.js)|Medium| ## License From 2d38c775c540dddd30ef7a020cb281b10bffd5eb Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 9 Mar 2025 21:31:53 -0500 Subject: [PATCH 873/919] Add solution #3463 --- ...are-equal-in-string-after-operations-ii.js | 63 +++++++++++++++++++ README.md | 1 + 2 files changed, 64 insertions(+) create mode 100644 3463-check-if-digits-are-equal-in-string-after-operations-ii.js diff --git a/3463-check-if-digits-are-equal-in-string-after-operations-ii.js b/3463-check-if-digits-are-equal-in-string-after-operations-ii.js new file mode 100644 index 00000000..6315d00c --- /dev/null +++ b/3463-check-if-digits-are-equal-in-string-after-operations-ii.js @@ -0,0 +1,63 @@ +/** + * 3463. Check If Digits Are Equal in String After Operations II + * https://leetcode.com/problems/check-if-digits-are-equal-in-string-after-operations-ii/ + * Difficulty: Hard + * + * You are given a string s consisting of digits. Perform the following operation repeatedly until + * the string has exactly two digits: + * - For each pair of consecutive digits in s, starting from the first digit, calculate a new digit + * as the sum of the two digits modulo 10. + * - Replace s with the sequence of newly calculated digits, maintaining the order in which they + * are computed. + * + * Return true if the final two digits in s are the same; otherwise, return false. + */ + +/** + * @param {string} s + * @return {boolean} + */ +var hasSameDigits = function(s) { + const n = s.length; + const binomialMod2 = (k, n) => (k & n) === k ? 1 : 0; + const binomialMod5 = (k, n) => { + if (k > n) return 0; + let result = 1; + const pascalMod5 = [ + [1, 0, 0, 0, 0], + [1, 1, 0, 0, 0], + [1, 2, 1, 0, 0], + [1, 3, 3, 1, 0], + [1, 4, 1, 4, 1] + ]; + + while (k > 0 || n > 0) { + const ki = k % 5; + const ni = n % 5; + if (ki > ni) return 0; + result = (result * pascalMod5[ni][ki]) % 5; + k = Math.floor(k / 5); + n = Math.floor(n / 5); + } + return result; + }; + + const binomialMod10 = (k, n) => { + const mod2 = binomialMod2(k, n); + const mod5 = binomialMod5(k, n); + for (let i = 0; i < 10; i++) { + if (i % 2 === mod2 && i % 5 === mod5) return i; + } + return 0; + }; + + let sum1 = 0; + let sum2 = 0; + for (let i = 0; i <= n - 2; i++) { + const coeff = binomialMod10(i, n - 2); + sum1 = (sum1 + coeff * +s[i]) % 10; + sum2 = (sum2 + coeff * +s[i + 1]) % 10; + } + + return sum1 === sum2; +}; diff --git a/README.md b/README.md index 76fdc87c..a95000b8 100644 --- a/README.md +++ b/README.md @@ -844,6 +844,7 @@ 3452|[Sum of Good Numbers](./3452-sum-of-good-numbers.js)|Easy| 3461|[Check If Digits Are Equal in String After Operations I](./3461-check-if-digits-are-equal-in-string-after-operations-i.js)|Easy| 3462|[Maximum Sum With at Most K Elements](./3462-maximum-sum-with-at-most-k-elements.js)|Medium| +3463|[Check If Digits Are Equal in String After Operations II](./3463-check-if-digits-are-equal-in-string-after-operations-ii.js)|Hard| ## License From d861720c9838b3db242373d9583f479c0a0d7b89 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Sun, 9 Mar 2025 21:37:27 -0500 Subject: [PATCH 874/919] Add solution #682 --- 0682-baseball-game.js | 41 +++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 42 insertions(+) create mode 100644 0682-baseball-game.js diff --git a/0682-baseball-game.js b/0682-baseball-game.js new file mode 100644 index 00000000..df460824 --- /dev/null +++ b/0682-baseball-game.js @@ -0,0 +1,41 @@ +/** + * 682. Baseball Game + * https://leetcode.com/problems/baseball-game/ + * Difficulty: Easy + * + * You are keeping the scores for a baseball game with strange rules. At the beginning of the + * game, you start with an empty record. + * + * You are given a list of strings operations, where operations[i] is the ith operation you + * must apply to the record and is one of the following: + * - An integer x. + * - Record a new score of x. + * - '+'. + * - Record a new score that is the sum of the previous two scores. + * - 'D'. + * - Record a new score that is the double of the previous score. + * - 'C'. + * - Invalidate the previous score, removing it from the record. + * + * Return the sum of all the scores on the record after applying all the operations. + * + * The test cases are generated such that the answer and all intermediate calculations fit in a + * 32-bit integer and that all operations are valid. + */ + +/** + * @param {string[]} ops + * @return {number} + */ +var calPoints = function(ops) { + const stack = []; + + for (const op of ops) { + if (op === 'C') stack.pop(); + else if (op === 'D') stack.push(stack.at(-1) * 2); + else if (op === '+') stack.push(stack.at(-1) + stack.at(-2)); + else stack.push(Number(op)); + } + + return stack.reduce((sum, num) => sum + num, 0); +}; diff --git a/README.md b/README.md index a95000b8..29d808f6 100644 --- a/README.md +++ b/README.md @@ -514,6 +514,7 @@ 678|[Valid Parenthesis String](./0678-valid-parenthesis-string.js)|Medium| 679|[24 Game](./0679-24-game.js)|Hard| 680|[Valid Palindrome II](./0680-valid-palindrome-ii.js)|Easy| +682|[Baseball Game](./0682-baseball-game.js)|Easy| 684|[Redundant Connection](./0684-redundant-connection.js)|Medium| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| 693|[Binary Number with Alternating Bits](./0693-binary-number-with-alternating-bits.js)|Easy| From a690f0084c8a07a82809f7fbf9ec4ff54a43e409 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 10 Mar 2025 01:07:50 -0500 Subject: [PATCH 875/919] Add solution #685 --- 0685-redundant-connection-ii.js | 56 +++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 57 insertions(+) create mode 100644 0685-redundant-connection-ii.js diff --git a/0685-redundant-connection-ii.js b/0685-redundant-connection-ii.js new file mode 100644 index 00000000..810daf08 --- /dev/null +++ b/0685-redundant-connection-ii.js @@ -0,0 +1,56 @@ +/** + * 685. Redundant Connection II + * https://leetcode.com/problems/redundant-connection-ii/ + * Difficulty: Hard + * + * In this problem, a rooted tree is a directed graph such that, there is exactly one node + * (the root) for which all other nodes are descendants of this node, plus every node has + * exactly one parent, except for the root node which has no parents. + * + * The given input is a directed graph that started as a rooted tree with n nodes (with + * distinct values from 1 to n), with one additional directed edge added. The added edge + * has two different vertices chosen from 1 to n, and was not an edge that already existed. + * + * The resulting graph is given as a 2D-array of edges. Each element of edges is a pair + * [ui, vi] that represents a directed edge connecting nodes ui and vi, where ui is a parent + * of child vi. + * + * Return an edge that can be removed so that the resulting graph is a rooted tree of n + * nodes. If there are multiple answers, return the answer that occurs last in the given 2D-array. + */ + +/** + * @param {number[][]} edges + * @return {number[]} + */ +var findRedundantDirectedConnection = function(edges) { + const n = edges.length; + const parent = Array.from({ length: n + 1 }, (_, i) => i); + const rank = new Uint32Array(n + 1); + const parents = new Int32Array(n + 1).fill(-1); + let conflict = -1; + let cycle = -1; + + edges.forEach(([u, v], i) => { + if (parents[v] !== -1) conflict = i; + else { + parents[v] = u; + union(u, v) || (cycle = i); + } + }); + + return conflict === -1 ? edges[cycle] : cycle === -1 + ? edges[conflict] : [parents[edges[conflict][1]], edges[conflict][1]]; + + function find(x) { + return parent[x] === x ? x : (parent[x] = find(parent[x])); + } + function union(x, y) { + const [px, py] = [find(x), find(y)]; + if (px === py) return false; + rank[px] < rank[py] + ? parent[px] = py + : rank[px] > rank[py] ? parent[py] = px : (parent[py] = px, rank[px]++); + return true; + } +}; diff --git a/README.md b/README.md index 29d808f6..f07a08cc 100644 --- a/README.md +++ b/README.md @@ -516,6 +516,7 @@ 680|[Valid Palindrome II](./0680-valid-palindrome-ii.js)|Easy| 682|[Baseball Game](./0682-baseball-game.js)|Easy| 684|[Redundant Connection](./0684-redundant-connection.js)|Medium| +685|[Redundant Connection II](./0685-redundant-connection-ii.js)|Hard| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| 693|[Binary Number with Alternating Bits](./0693-binary-number-with-alternating-bits.js)|Easy| 695|[Max Area of Island](./0695-max-area-of-island.js)|Medium| From 095dc7f92e5072701445d3416ad890ed9600b436 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 10 Mar 2025 01:10:21 -0500 Subject: [PATCH 876/919] Add solution #687 --- 0687-longest-univalue-path.js | 40 +++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 41 insertions(+) create mode 100644 0687-longest-univalue-path.js diff --git a/0687-longest-univalue-path.js b/0687-longest-univalue-path.js new file mode 100644 index 00000000..a17e7865 --- /dev/null +++ b/0687-longest-univalue-path.js @@ -0,0 +1,40 @@ +/** + * 687. Longest Univalue Path + * https://leetcode.com/problems/longest-univalue-path/ + * Difficulty: Medium + * + * Given the root of a binary tree, return the length of the longest path, where each node + * in the path has the same value. This path may or may not pass through the root. + * + * The length of the path between two nodes is represented by the number of edges between them. + */ + +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number} + */ +var longestUnivaluePath = function(root) { + let max = 0; + dfs(root); + return max; + + function dfs(node) { + if (!node) return 0; + + const left = dfs(node.left); + const right = dfs(node.right); + const leftPath = node.left?.val === node.val ? left + 1 : 0; + const rightPath = node.right?.val === node.val ? right + 1 : 0; + + max = Math.max(max, leftPath + rightPath); + return Math.max(leftPath, rightPath); + } +}; diff --git a/README.md b/README.md index f07a08cc..7c963165 100644 --- a/README.md +++ b/README.md @@ -518,6 +518,7 @@ 684|[Redundant Connection](./0684-redundant-connection.js)|Medium| 685|[Redundant Connection II](./0685-redundant-connection-ii.js)|Hard| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| +687|[Longest Univalue Path](./0687-longest-univalue-path.js)|Medium| 693|[Binary Number with Alternating Bits](./0693-binary-number-with-alternating-bits.js)|Easy| 695|[Max Area of Island](./0695-max-area-of-island.js)|Medium| 696|[Count Binary Substrings](./0696-count-binary-substrings.js)|Easy| From 128a2429cc4aff5f885cf3246848da51bd049fb7 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 10 Mar 2025 01:13:31 -0500 Subject: [PATCH 877/919] Add solution #688 --- 0688-knight-probability-in-chessboard.js | 49 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 50 insertions(+) create mode 100644 0688-knight-probability-in-chessboard.js diff --git a/0688-knight-probability-in-chessboard.js b/0688-knight-probability-in-chessboard.js new file mode 100644 index 00000000..122adba0 --- /dev/null +++ b/0688-knight-probability-in-chessboard.js @@ -0,0 +1,49 @@ +/** + * 688. Knight Probability in Chessboard + * https://leetcode.com/problems/knight-probability-in-chessboard/ + * Difficulty: Medium + * + * On an n x n chessboard, a knight starts at the cell (row, column) and attempts to make exactly + * k moves. The rows and columns are 0-indexed, so the top-left cell is (0, 0), and the bottom-right + * cell is (n - 1, n - 1). + * + * A chess knight has eight possible moves it can make, as illustrated below. Each move is two cells + * in a cardinal direction, then one cell in an orthogonal direction. + * + * Each time the knight is to move, it chooses one of eight possible moves uniformly at random + * (even if the piece would go off the chessboard) and moves there. + * + * The knight continues moving until it has made exactly k moves or has moved off the chessboard. + * + * Return the probability that the knight remains on the board after it has stopped moving. + */ + +/** + * @param {number} n + * @param {number} k + * @param {number} row + * @param {number} column + * @return {number} + */ +var knightProbability = function(n, k, row, column) { + const moves = [[-2, -1], [-2, 1], [-1, -2], [-1, 2], [1, -2], [1, 2], [2, -1], [2, 1]]; + const dp = new Map(); + + return calc(k, row, column); + + function calc(movesLeft, r, c) { + if (r < 0 || r >= n || c < 0 || c >= n) return 0; + if (movesLeft === 0) return 1; + + const key = `${movesLeft},${r},${c}`; + if (dp.has(key)) return dp.get(key); + + let prob = 0; + for (const [dr, dc] of moves) { + prob += calc(movesLeft - 1, r + dr, c + dc) / 8; + } + + dp.set(key, prob); + return prob; + } +}; diff --git a/README.md b/README.md index 7c963165..6172511b 100644 --- a/README.md +++ b/README.md @@ -519,6 +519,7 @@ 685|[Redundant Connection II](./0685-redundant-connection-ii.js)|Hard| 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| 687|[Longest Univalue Path](./0687-longest-univalue-path.js)|Medium| +688|[Knight Probability in Chessboard](./0688-knight-probability-in-chessboard.js)|Medium| 693|[Binary Number with Alternating Bits](./0693-binary-number-with-alternating-bits.js)|Easy| 695|[Max Area of Island](./0695-max-area-of-island.js)|Medium| 696|[Count Binary Substrings](./0696-count-binary-substrings.js)|Easy| From a727b7d358dc308c11ca73120b16c366f64bf07d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 10 Mar 2025 01:18:14 -0500 Subject: [PATCH 878/919] Add solution #689 --- ...imum-sum-of-3-non-overlapping-subarrays.js | 55 +++++++++++++++++++ README.md | 1 + 2 files changed, 56 insertions(+) create mode 100644 0689-maximum-sum-of-3-non-overlapping-subarrays.js diff --git a/0689-maximum-sum-of-3-non-overlapping-subarrays.js b/0689-maximum-sum-of-3-non-overlapping-subarrays.js new file mode 100644 index 00000000..c76d8060 --- /dev/null +++ b/0689-maximum-sum-of-3-non-overlapping-subarrays.js @@ -0,0 +1,55 @@ +/** + * 689. Maximum Sum of 3 Non-Overlapping Subarrays + * https://leetcode.com/problems/maximum-sum-of-3-non-overlapping-subarrays/ + * Difficulty: Hard + * + * Given an integer array nums and an integer k, find three non-overlapping subarrays of + * length k with maximum sum and return them. + * + * Return the result as a list of indices representing the starting position of each + * interval (0-indexed). If there are multiple answers, return the lexicographically + * smallest one. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {number[]} + */ +var maxSumOfThreeSubarrays = function(nums, k) { + const n = nums.length; + let [sumFirst, sumSecond, sumThird] = [0, 0, 0]; + let [maxFirst, maxFirstSecond, maxTotal] = [0, 0, 0]; + let [startFirst, startFirstBest, startSecondBest] = [0, 0, k]; + let result = [0, k, 2 * k]; + + for (let i = 0; i < k; i++) { + sumFirst += nums[i]; + sumSecond += nums[i + k]; + sumThird += nums[i + 2 * k]; + } + [maxFirst, maxFirstSecond, maxTotal] = [ + sumFirst, sumFirst + sumSecond, + sumFirst + sumSecond + sumThird + ]; + + for (let i = 1; i <= n - 3 * k; i++) { + sumFirst += nums[i + k - 1] - nums[i - 1]; + sumSecond += nums[i + 2 * k - 1] - nums[i + k - 1]; + sumThird += nums[i + 3 * k - 1] - nums[i + 2 * k - 1]; + + if (sumFirst > maxFirst) [maxFirst, startFirst] = [sumFirst, i]; + if (maxFirst + sumSecond > maxFirstSecond) { + [maxFirstSecond, startFirstBest, startSecondBest] = [maxFirst + sumSecond, startFirst, i + k]; + } + if (maxFirstSecond + sumThird > maxTotal) { + [maxTotal, ...result] = [ + maxFirstSecond + sumThird, + startFirstBest, + startSecondBest, i + 2 * k + ]; + } + } + + return result; +}; diff --git a/README.md b/README.md index 6172511b..55d41b05 100644 --- a/README.md +++ b/README.md @@ -520,6 +520,7 @@ 686|[Repeated String Match](./0686-repeated-string-match.js)|Easy| 687|[Longest Univalue Path](./0687-longest-univalue-path.js)|Medium| 688|[Knight Probability in Chessboard](./0688-knight-probability-in-chessboard.js)|Medium| +689|[Maximum Sum of 3 Non-Overlapping Subarrays](./0689-maximum-sum-of-3-non-overlapping-subarrays.js)|Hard| 693|[Binary Number with Alternating Bits](./0693-binary-number-with-alternating-bits.js)|Easy| 695|[Max Area of Island](./0695-max-area-of-island.js)|Medium| 696|[Count Binary Substrings](./0696-count-binary-substrings.js)|Easy| From 8928509e42b01b069e24d4fff78c70a3c2d3d7de Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Mon, 10 Mar 2025 01:20:38 -0500 Subject: [PATCH 879/919] Add solution #690 --- 0690-employee-importance.js | 41 +++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 42 insertions(+) create mode 100644 0690-employee-importance.js diff --git a/0690-employee-importance.js b/0690-employee-importance.js new file mode 100644 index 00000000..47633b40 --- /dev/null +++ b/0690-employee-importance.js @@ -0,0 +1,41 @@ +/** + * 690. Employee Importance + * https://leetcode.com/problems/employee-importance/ + * Difficulty: Medium + * + * You have a data structure of employee information, including the employee's unique ID, + * importance value, and direct subordinates' IDs. + * + * You are given an array of employees employees where: + * - employees[i].id is the ID of the ith employee. + * - employees[i].importance is the importance value of the ith employee. + * - employees[i].subordinates is a list of the IDs of the direct subordinates of the ith employee. + * + * Given an integer id that represents an employee's ID, return the total importance value of this + * employee and all their direct and indirect subordinates. + */ + +/** + * Definition for Employee. + * function Employee(id, importance, subordinates) { + * this.id = id; + * this.importance = importance; + * this.subordinates = subordinates; + * } + */ + +/** + * @param {Employee[]} employees + * @param {number} id + * @return {number} + */ +var GetImportance = function(employees, id) { + const map = new Map(employees.map(e => [e.id, e])); + return dfs(id); + + function dfs(id) { + if (!map.has(id)) return 0; + const e = map.get(id); + return e.importance + e.subordinates.reduce((sum, id) => sum + dfs(id), 0); + } +}; diff --git a/README.md b/README.md index 55d41b05..7d1ca9d7 100644 --- a/README.md +++ b/README.md @@ -521,6 +521,7 @@ 687|[Longest Univalue Path](./0687-longest-univalue-path.js)|Medium| 688|[Knight Probability in Chessboard](./0688-knight-probability-in-chessboard.js)|Medium| 689|[Maximum Sum of 3 Non-Overlapping Subarrays](./0689-maximum-sum-of-3-non-overlapping-subarrays.js)|Hard| +690|[Employee Importance](./0690-employee-importance.js)|Medium| 693|[Binary Number with Alternating Bits](./0693-binary-number-with-alternating-bits.js)|Easy| 695|[Max Area of Island](./0695-max-area-of-island.js)|Medium| 696|[Count Binary Substrings](./0696-count-binary-substrings.js)|Easy| From 2629def723b80b6f3c89a9ec517d68c24244a279 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 11 Mar 2025 17:07:21 -0500 Subject: [PATCH 880/919] Add solution #1358 --- ...strings-containing-all-three-characters.js | 32 +++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 1358-number-of-substrings-containing-all-three-characters.js diff --git a/1358-number-of-substrings-containing-all-three-characters.js b/1358-number-of-substrings-containing-all-three-characters.js new file mode 100644 index 00000000..99459b80 --- /dev/null +++ b/1358-number-of-substrings-containing-all-three-characters.js @@ -0,0 +1,32 @@ +/** + * 1358. Number of Substrings Containing All Three Characters + * https://leetcode.com/problems/number-of-substrings-containing-all-three-characters/ + * Difficulty: Medium + * + * Given a string s consisting only of characters a, b and c. + * + * Return the number of substrings containing at least one occurrence of all these + * characters a, b and c. + */ + +/** + * @param {string} s + * @return {number} + */ +var numberOfSubstrings = function(s) { + const count = [0, 0, 0]; + let result = 0; + let left = 0; + + for (let right = 0; right < s.length; right++) { + count[s[right].charCodeAt(0) - 97]++; + + while (count[0] > 0 && count[1] > 0 && count[2] > 0) { + result += s.length - right; + count[s[left].charCodeAt(0) - 97]--; + left++; + } + } + + return result; +}; diff --git a/README.md b/README.md index 7d1ca9d7..06bdffb1 100644 --- a/README.md +++ b/README.md @@ -653,6 +653,7 @@ 1351|[Count Negative Numbers in a Sorted Matrix](./1351-count-negative-numbers-in-a-sorted-matrix.js)|Easy| 1352|[Product of the Last K Numbers](./1352-product-of-the-last-k-numbers.js)|Medium| 1356|[Sort Integers by The Number of 1 Bits](./1356-sort-integers-by-the-number-of-1-bits.js)|Easy| +1358|[Number of Substrings Containing All Three Characters](./1358-number-of-substrings-containing-all-three-characters.js)|Medium| 1360|[Number of Days Between Two Dates](./1360-number-of-days-between-two-dates.js)|Easy| 1365|[How Many Numbers Are Smaller Than the Current Number](./1365-how-many-numbers-are-smaller-than-the-current-number.js)|Easy| 1366|[Rank Teams by Votes](./1366-rank-teams-by-votes.js)|Medium| From 4d2d0f059225dfdf3d33e35cf16810fbe419390c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 11 Mar 2025 17:08:41 -0500 Subject: [PATCH 881/919] Add solution #692 --- 0692-top-k-frequent-words.js | 24 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 0692-top-k-frequent-words.js diff --git a/0692-top-k-frequent-words.js b/0692-top-k-frequent-words.js new file mode 100644 index 00000000..8ac88865 --- /dev/null +++ b/0692-top-k-frequent-words.js @@ -0,0 +1,24 @@ +/** + * 692. Top K Frequent Words + * https://leetcode.com/problems/top-k-frequent-words/ + * Difficulty: Medium + * + * Given an array of strings words and an integer k, return the k most frequent strings. + * + * Return the answer sorted by the frequency from highest to lowest. Sort the words with + * the same frequency by their lexicographical order. + */ + +/** + * @param {string[]} words + * @param {number} k + * @return {string[]} + */ +var topKFrequent = function(words, k) { + const map = new Map(); + words.forEach(word => map.set(word, (map.get(word) || 0) + 1)); + return [...map.entries()] + .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])) + .slice(0, k) + .map(([word]) => word); +}; diff --git a/README.md b/README.md index 06bdffb1..9e93ee07 100644 --- a/README.md +++ b/README.md @@ -522,6 +522,7 @@ 688|[Knight Probability in Chessboard](./0688-knight-probability-in-chessboard.js)|Medium| 689|[Maximum Sum of 3 Non-Overlapping Subarrays](./0689-maximum-sum-of-3-non-overlapping-subarrays.js)|Hard| 690|[Employee Importance](./0690-employee-importance.js)|Medium| +692|[Top K Frequent Words](./0692-top-k-frequent-words.js)|Medium| 693|[Binary Number with Alternating Bits](./0693-binary-number-with-alternating-bits.js)|Easy| 695|[Max Area of Island](./0695-max-area-of-island.js)|Medium| 696|[Count Binary Substrings](./0696-count-binary-substrings.js)|Easy| From bc1d40387c7dc79534a147328c2044126b49fec0 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 11 Mar 2025 17:11:46 -0500 Subject: [PATCH 882/919] Add solution #698 --- 0698-partition-to-k-equal-sum-subsets.js | 45 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 46 insertions(+) create mode 100644 0698-partition-to-k-equal-sum-subsets.js diff --git a/0698-partition-to-k-equal-sum-subsets.js b/0698-partition-to-k-equal-sum-subsets.js new file mode 100644 index 00000000..34020cc0 --- /dev/null +++ b/0698-partition-to-k-equal-sum-subsets.js @@ -0,0 +1,45 @@ +/** + * 698. Partition to K Equal Sum Subsets + * https://leetcode.com/problems/partition-to-k-equal-sum-subsets/ + * Difficulty: Medium + * + * Given an integer array nums and an integer k, return true if it is possible to divide this + * array into k non-empty subsets whose sums are all equal. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {boolean} + */ +var canPartitionKSubsets = function(nums, k) { + const sum = nums.reduce((a, b) => a + b); + if (sum % k !== 0) { + return false; + } + + const target = sum / k; + nums.sort((a, b) => b - a); + if (nums[0] > target) { + return false; + } + + const used = new Array(nums.length).fill(false); + return backtrack(0, 0, 0); + + function backtrack(index, count, updatedSum) { + if (count === k) return true; + if (updatedSum === target) return backtrack(0, count + 1, 0); + if (updatedSum > target) return false; + + for (let i = index; i < nums.length; i++) { + if (!used[i]) { + used[i] = true; + if (backtrack(i + 1, count, updatedSum + nums[i])) return true; + used[i] = false; + if (updatedSum === 0) break; + } + } + return false; + } +}; diff --git a/README.md b/README.md index 9e93ee07..a17d94df 100644 --- a/README.md +++ b/README.md @@ -527,6 +527,7 @@ 695|[Max Area of Island](./0695-max-area-of-island.js)|Medium| 696|[Count Binary Substrings](./0696-count-binary-substrings.js)|Easy| 697|[Degree of an Array](./0697-degree-of-an-array.js)|Easy| +698|[Partition to K Equal Sum Subsets](./0698-partition-to-k-equal-sum-subsets.js)|Medium| 700|[Search in a Binary Search Tree](./0700-search-in-a-binary-search-tree.js)|Easy| 701|[Insert into a Binary Search Tree](./0701-insert-into-a-binary-search-tree.js)|Medium| 703|[Kth Largest Element in a Stream](./0703-kth-largest-element-in-a-stream.js)|Easy| From a12331ed35fa431f56b7ae4d60ccd7e8e2a0a6a4 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 11 Mar 2025 17:17:27 -0500 Subject: [PATCH 883/919] Add solution #699 --- 0699-falling-squares.js | 51 +++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 52 insertions(+) create mode 100644 0699-falling-squares.js diff --git a/0699-falling-squares.js b/0699-falling-squares.js new file mode 100644 index 00000000..b0192a62 --- /dev/null +++ b/0699-falling-squares.js @@ -0,0 +1,51 @@ +/** + * 699. Falling Squares + * https://leetcode.com/problems/falling-squares/ + * Difficulty: Hard + * + * There are several squares being dropped onto the X-axis of a 2D plane. + * + * You are given a 2D integer array positions where positions[i] = [lefti, sideLengthi] + * represents the ith square with a side length of sideLengthi that is dropped with its + * left edge aligned with X-coordinate lefti. + * + * Each square is dropped one at a time from a height above any landed squares. It then + * falls downward (negative Y direction) until it either lands on the top side of another + * square or on the X-axis. A square brushing the left/right side of another square does + * not count as landing on it. Once it lands, it freezes in place and cannot be moved. + * + * After each square is dropped, you must record the height of the current tallest stack + * of squares. + * + * Return an integer array ans where ans[i] represents the height described above after + * dropping the ith square. + */ + +/** + * @param {number[][]} positions + * @return {number[]} + */ +var fallingSquares = function(positions) { + const map = new Map(); + const result = []; + let max = 0; + + for (const [left, side] of positions) { + const right = left + side; + let height = 0; + + for (const [start, [i, n]] of map) { + const end = start + i; + if (right > start && left < end) { + height = Math.max(height, n); + } + } + + height += side; + map.set(left, [side, height]); + max = Math.max(max, height); + result.push(max); + } + + return result; +}; diff --git a/README.md b/README.md index a17d94df..75f901ed 100644 --- a/README.md +++ b/README.md @@ -528,6 +528,7 @@ 696|[Count Binary Substrings](./0696-count-binary-substrings.js)|Easy| 697|[Degree of an Array](./0697-degree-of-an-array.js)|Easy| 698|[Partition to K Equal Sum Subsets](./0698-partition-to-k-equal-sum-subsets.js)|Medium| +699|[Falling Squares](./0699-falling-squares.js)|Hard| 700|[Search in a Binary Search Tree](./0700-search-in-a-binary-search-tree.js)|Easy| 701|[Insert into a Binary Search Tree](./0701-insert-into-a-binary-search-tree.js)|Medium| 703|[Kth Largest Element in a Stream](./0703-kth-largest-element-in-a-stream.js)|Easy| From 1f739c72304580d0a75ee2ab18dd2b1a08ae79ef Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 11 Mar 2025 17:25:16 -0500 Subject: [PATCH 884/919] Add solution #707 --- 0707-design-linked-list.js | 110 +++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 111 insertions(+) create mode 100644 0707-design-linked-list.js diff --git a/0707-design-linked-list.js b/0707-design-linked-list.js new file mode 100644 index 00000000..d0f67519 --- /dev/null +++ b/0707-design-linked-list.js @@ -0,0 +1,110 @@ +/** + * 707. Design Linked List + * https://leetcode.com/problems/design-linked-list/ + * Difficulty: Medium + * + * Design your implementation of the linked list. You can choose to use a singly or + * doubly linked list. + * + * A node in a singly linked list should have two attributes: val and next. val is the value + * of the current node, and next is a pointer/reference to the next node. + * + * If you want to use the doubly linked list, you will need one more attribute prev to indicate + * the previous node in the linked list. Assume all nodes in the linked list are 0-indexed. + * + * Implement the MyLinkedList class: + * - MyLinkedList() Initializes the MyLinkedList object. + * - int get(int index) Get the value of the indexth node in the linked list. If the + * index is invalid, return -1. + * - void addAtHead(int val) Add a node of value val before the first element of the + * linked list. After the insertion, the new node will be the first node of the linked list. + * - void addAtTail(int val) Append a node of value val as the last element of the linked list. + * - void addAtIndex(int index, int val) Add a node of value val before the indexth node + * in the linked list. If index equals the length of the linked list, the node will be + * appended to the end of the linked list. If index is greater than the length, the node + * will not be inserted. + * - void deleteAtIndex(int index) Delete the indexth node in the linked list, if the index + * is valid. + */ + +var MyLinkedList = function() { + this.head = null; + this.size = 0; +}; + +/** + * @param {number} index + * @return {number} + */ +MyLinkedList.prototype.get = function(index) { + if (index < 0 || index >= this.size) return -1; + let current = this.head; + while (index--) current = current.next; + return current.val; +}; + +/** + * @param {number} val + * @return {void} + */ +MyLinkedList.prototype.addAtHead = function(val) { + const node = new Node(val); + node.next = this.head; + this.head = node; + this.size++; +}; + +/** + * @param {number} val + * @return {void} + */ +MyLinkedList.prototype.addAtTail = function(val) { + const node = new Node(val); + if (!this.head) { + this.head = node; + } else { + let current = this.head; + while (current.next) current = current.next; + current.next = node; + } + this.size++; +}; + +/** + * @param {number} index + * @param {number} val + * @return {void} + */ +MyLinkedList.prototype.addAtIndex = function(index, val) { + if (index < 0 || index > this.size) return; + if (index === 0) return this.addAtHead(val); + const node = new Node(val); + let current = this.head; + while (--index) current = current.next; + node.next = current.next; + current.next = node; + this.size++; +}; + +/** + * @param {number} index + * @return {void} + */ +MyLinkedList.prototype.deleteAtIndex = function(index) { + if (index < 0 || index >= this.size) return; + this.size--; + if (index === 0) { + this.head = this.head.next; + return; + } + let current = this.head; + while (--index) current = current.next; + current.next = current.next.next; +}; + +class Node { + constructor(val) { + this.val = val; + this.next = null; + } +} diff --git a/README.md b/README.md index 75f901ed..6b471c69 100644 --- a/README.md +++ b/README.md @@ -535,6 +535,7 @@ 704|[Binary Search](./0704-binary-search.js)|Easy| 705|[Design HashSet](./0705-design-hashset.js)|Easy| 706|[Design HashMap](./0706-design-hashmap.js)|Easy| +707|[Design Linked List](./0707-design-linked-list.js)|Medium| 713|[Subarray Product Less Than K](./0713-subarray-product-less-than-k.js)|Medium| 714|[Best Time to Buy and Sell Stock with Transaction Fee](./0714-best-time-to-buy-and-sell-stock-with-transaction-fee.js)|Medium| 717|[1-bit and 2-bit Characters](./0717-1-bit-and-2-bit-characters.js)|Easy| From eec82f37e929946128c87ac4157b992a63f9a0e3 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 11 Mar 2025 17:38:59 -0500 Subject: [PATCH 885/919] Add solution #710 --- 0710-random-pick-with-blacklist.js | 43 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 44 insertions(+) create mode 100644 0710-random-pick-with-blacklist.js diff --git a/0710-random-pick-with-blacklist.js b/0710-random-pick-with-blacklist.js new file mode 100644 index 00000000..2715bb35 --- /dev/null +++ b/0710-random-pick-with-blacklist.js @@ -0,0 +1,43 @@ +/** + * 710. Random Pick with Blacklist + * https://leetcode.com/problems/random-pick-with-blacklist/ + * Difficulty: Hard + * + * You are given an integer n and an array of unique integers blacklist. Design an algorithm to + * pick a random integer in the range [0, n - 1] that is not in blacklist. Any integer that is + * in the mentioned range and not in blacklist should be equally likely to be returned. + * + * Optimize your algorithm such that it minimizes the number of calls to the built-in random + * function of your language. + * + * Implement the Solution class: + * - Solution(int n, int[] blacklist) Initializes the object with the integer n and the + * blacklisted integers blacklist. + * - int pick() Returns a random integer in the range [0, n - 1] and not in blacklist. + */ + +/** + * @param {number} n + * @param {number[]} blacklist + */ +var Solution = function(n, blacklist) { + this.size = n - blacklist.length; + this.mapping = new Map(); + blacklist = new Set(blacklist); + + let last = n - 1; + for (const b of blacklist) { + if (b < this.size) { + while (blacklist.has(last)) last--; + this.mapping.set(b, last--); + } + } +}; + +/** + * @return {number} + */ +Solution.prototype.pick = function() { + const index = Math.floor(Math.random() * this.size); + return this.mapping.get(index) ?? index; +}; diff --git a/README.md b/README.md index 6b471c69..76ab70de 100644 --- a/README.md +++ b/README.md @@ -536,6 +536,7 @@ 705|[Design HashSet](./0705-design-hashset.js)|Easy| 706|[Design HashMap](./0706-design-hashmap.js)|Easy| 707|[Design Linked List](./0707-design-linked-list.js)|Medium| +710|[Random Pick with Blacklist](./0710-random-pick-with-blacklist.js)|Hard| 713|[Subarray Product Less Than K](./0713-subarray-product-less-than-k.js)|Medium| 714|[Best Time to Buy and Sell Stock with Transaction Fee](./0714-best-time-to-buy-and-sell-stock-with-transaction-fee.js)|Medium| 717|[1-bit and 2-bit Characters](./0717-1-bit-and-2-bit-characters.js)|Easy| From 878ebd02b2f3e98352b8763fc5f746b56a57c8ee Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 11 Mar 2025 17:41:09 -0500 Subject: [PATCH 886/919] Add solution #712 --- ...inimum-ascii-delete-sum-for-two-strings.js | 41 +++++++++++++++++++ README.md | 1 + 2 files changed, 42 insertions(+) create mode 100644 0712-minimum-ascii-delete-sum-for-two-strings.js diff --git a/0712-minimum-ascii-delete-sum-for-two-strings.js b/0712-minimum-ascii-delete-sum-for-two-strings.js new file mode 100644 index 00000000..65eb0438 --- /dev/null +++ b/0712-minimum-ascii-delete-sum-for-two-strings.js @@ -0,0 +1,41 @@ +/** + * 712. Minimum ASCII Delete Sum for Two Strings + * https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/ + * Difficulty: Medium + * + * Given two strings s1 and s2, return the lowest ASCII sum of deleted characters to + * make two strings equal. + */ + +/** + * @param {string} s1 + * @param {string} s2 + * @return {number} + */ +var minimumDeleteSum = function(s1, s2) { + const dp = new Array(s1.length + 1).fill().map(() => { + return new Array(s2.length + 1).fill(0); + }); + + for (let i = 1; i <= s1.length; i++) { + dp[i][0] = dp[i - 1][0] + s1.charCodeAt(i - 1); + } + for (let j = 1; j <= s2.length; j++) { + dp[0][j] = dp[0][j - 1] + s2.charCodeAt(j - 1); + } + + for (let i = 1; i <= s1.length; i++) { + for (let j = 1; j <= s2.length; j++) { + if (s1[i - 1] === s2[j - 1]) { + dp[i][j] = dp[i - 1][j - 1]; + } else { + dp[i][j] = Math.min( + dp[i - 1][j] + s1.charCodeAt(i - 1), + dp[i][j - 1] + s2.charCodeAt(j - 1) + ); + } + } + } + + return dp[s1.length][s2.length]; +}; diff --git a/README.md b/README.md index 76ab70de..a8a3e8a3 100644 --- a/README.md +++ b/README.md @@ -537,6 +537,7 @@ 706|[Design HashMap](./0706-design-hashmap.js)|Easy| 707|[Design Linked List](./0707-design-linked-list.js)|Medium| 710|[Random Pick with Blacklist](./0710-random-pick-with-blacklist.js)|Hard| +712|[Minimum ASCII Delete Sum for Two Strings](./0712-minimum-ascii-delete-sum-for-two-strings.js)|Medium| 713|[Subarray Product Less Than K](./0713-subarray-product-less-than-k.js)|Medium| 714|[Best Time to Buy and Sell Stock with Transaction Fee](./0714-best-time-to-buy-and-sell-stock-with-transaction-fee.js)|Medium| 717|[1-bit and 2-bit Characters](./0717-1-bit-and-2-bit-characters.js)|Easy| From d9b609c3fbe7976495fec8972d3ceb93b19b5efe Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 11 Mar 2025 17:43:20 -0500 Subject: [PATCH 887/919] Add solution #715 --- 0715-range-module.js | 79 ++++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 80 insertions(+) create mode 100644 0715-range-module.js diff --git a/0715-range-module.js b/0715-range-module.js new file mode 100644 index 00000000..dd76c8c8 --- /dev/null +++ b/0715-range-module.js @@ -0,0 +1,79 @@ +/** + * 715. Range Module + * https://leetcode.com/problems/range-module/ + * Difficulty: Hard + * + * A Range Module is a module that tracks ranges of numbers. Design a data structure to track the + * ranges represented as half-open intervals and query about them. + * + * A half-open interval [left, right) denotes all the real numbers x where left <= x < right. + * + * Implement the RangeModule class: + * - RangeModule() Initializes the object of the data structure. + * - void addRange(int left, int right) Adds the half-open interval [left, right), tracking every + * real number in that interval. Adding an interval that partially overlaps with currently tracked + * numbers should add any numbers in the interval [left, right) that are not already tracked. + * - boolean queryRange(int left, int right) Returns true if every real number in the interval + * [left, right) is currently being tracked, and false otherwise. + * - void removeRange(int left, int right) Stops tracking every real number currently being tracked + * in the half-open interval [left, right). + */ + +var RangeModule = function() { + this.ranges = []; +}; + +/** + * @param {number} left + * @param {number} right + * @return {void} + */ +RangeModule.prototype.addRange = function(left, right) { + const intervals = []; + let placed = false; + for (const [start, end] of this.ranges) { + if (start > right && !placed) { + intervals.push([left, right]); + placed = true; + } + if (end < left || start > right) { + intervals.push([start, end]); + } else { + left = Math.min(left, start); + right = Math.max(right, end); + } + } + if (!placed) intervals.push([left, right]); + this.ranges = intervals; +}; + +/** + * @param {number} left + * @param {number} right + * @return {boolean} + */ +RangeModule.prototype.queryRange = function(left, right) { + for (const [start, end] of this.ranges) { + if (start <= left && end >= right) return true; + if (start > left) break; + } + return false; +}; + +/** + * @param {number} left + * @param {number} right + * @return {void} + */ +RangeModule.prototype.removeRange = function(left, right) { + const intervals = []; + for (const [start, end] of this.ranges) { + if (end <= left || start >= right) { + intervals.push([start, end]); + } else { + if (start < left) intervals.push([start, left]); + if (end > right) intervals.push([right, end]); + } + } + this.ranges = intervals; +}; diff --git a/README.md b/README.md index a8a3e8a3..d3bc43cd 100644 --- a/README.md +++ b/README.md @@ -540,6 +540,7 @@ 712|[Minimum ASCII Delete Sum for Two Strings](./0712-minimum-ascii-delete-sum-for-two-strings.js)|Medium| 713|[Subarray Product Less Than K](./0713-subarray-product-less-than-k.js)|Medium| 714|[Best Time to Buy and Sell Stock with Transaction Fee](./0714-best-time-to-buy-and-sell-stock-with-transaction-fee.js)|Medium| +715|[Range Module](./0715-range-module.js)|Hard| 717|[1-bit and 2-bit Characters](./0717-1-bit-and-2-bit-characters.js)|Easy| 720|[Longest Word in Dictionary](./0720-longest-word-in-dictionary.js)|Medium| 722|[Remove Comments](./0722-remove-comments.js)|Medium| From ed159d0ed44db182505c1b8d785070fcf62afe53 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 11 Mar 2025 17:46:01 -0500 Subject: [PATCH 888/919] Add solution #718 --- 0718-maximum-length-of-repeated-subarray.js | 31 +++++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 0718-maximum-length-of-repeated-subarray.js diff --git a/0718-maximum-length-of-repeated-subarray.js b/0718-maximum-length-of-repeated-subarray.js new file mode 100644 index 00000000..97a29b28 --- /dev/null +++ b/0718-maximum-length-of-repeated-subarray.js @@ -0,0 +1,31 @@ +/** + * 718. Maximum Length of Repeated Subarray + * https://leetcode.com/problems/maximum-length-of-repeated-subarray/ + * Difficulty: Medium + * + * Given two integer arrays nums1 and nums2, return the maximum length of a subarray + * that appears in both arrays. + */ + +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number} + */ +var findLength = function(nums1, nums2) { + const dp = new Array(nums1.length + 1).fill().map(() => { + return new Array(nums2.length + 1).fill(0); + }); + let result = 0; + + for (let i = 1; i <= nums1.length; i++) { + for (let j = 1; j <= nums2.length; j++) { + if (nums1[i - 1] === nums2[j - 1]) { + dp[i][j] = dp[i - 1][j - 1] + 1; + result = Math.max(result, dp[i][j]); + } + } + } + + return result; +}; diff --git a/README.md b/README.md index d3bc43cd..360fb7be 100644 --- a/README.md +++ b/README.md @@ -542,6 +542,7 @@ 714|[Best Time to Buy and Sell Stock with Transaction Fee](./0714-best-time-to-buy-and-sell-stock-with-transaction-fee.js)|Medium| 715|[Range Module](./0715-range-module.js)|Hard| 717|[1-bit and 2-bit Characters](./0717-1-bit-and-2-bit-characters.js)|Easy| +718|[Maximum Length of Repeated Subarray](./0718-maximum-length-of-repeated-subarray.js)|Medium| 720|[Longest Word in Dictionary](./0720-longest-word-in-dictionary.js)|Medium| 722|[Remove Comments](./0722-remove-comments.js)|Medium| 724|[Find Pivot Index](./0724-find-pivot-index.js)|Easy| From 8fc0f9568c80387dd280871dd0b9af8cb68fef9d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Tue, 11 Mar 2025 17:48:15 -0500 Subject: [PATCH 889/919] Add solution #719 --- 0719-find-k-th-smallest-pair-distance.js | 40 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 41 insertions(+) create mode 100644 0719-find-k-th-smallest-pair-distance.js diff --git a/0719-find-k-th-smallest-pair-distance.js b/0719-find-k-th-smallest-pair-distance.js new file mode 100644 index 00000000..fd442d98 --- /dev/null +++ b/0719-find-k-th-smallest-pair-distance.js @@ -0,0 +1,40 @@ +/** + * 719. Find K-th Smallest Pair Distance + * https://leetcode.com/problems/find-k-th-smallest-pair-distance/ + * Difficulty: Hard + * + * The distance of a pair of integers a and b is defined as the absolute difference between a and b. + * + * Given an integer array nums and an integer k, return the kth smallest distance among all the + * pairs nums[i] and nums[j] where 0 <= i < j < nums.length. + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var smallestDistancePair = function(nums, k) { + nums.sort((a, b) => a - b); + let left = 0; + let right = nums[nums.length - 1] - nums[0]; + + while (left < right) { + const middle = Math.floor((left + right) / 2); + let count = 0; + let j = 0; + + for (let i = 0; i < nums.length; i++) { + while (j < nums.length && nums[j] - nums[i] <= middle) j++; + count += j - i - 1; + } + + if (count < k) { + left = middle + 1; + } else { + right = middle; + } + } + + return left; +}; diff --git a/README.md b/README.md index 360fb7be..9140d561 100644 --- a/README.md +++ b/README.md @@ -543,6 +543,7 @@ 715|[Range Module](./0715-range-module.js)|Hard| 717|[1-bit and 2-bit Characters](./0717-1-bit-and-2-bit-characters.js)|Easy| 718|[Maximum Length of Repeated Subarray](./0718-maximum-length-of-repeated-subarray.js)|Medium| +719|[Find K-th Smallest Pair Distance](./0719-find-k-th-smallest-pair-distance.js)|Hard| 720|[Longest Word in Dictionary](./0720-longest-word-in-dictionary.js)|Medium| 722|[Remove Comments](./0722-remove-comments.js)|Medium| 724|[Find Pivot Index](./0724-find-pivot-index.js)|Easy| From ed6ae9ba0c9fc23552f89cc8b6cadbaa186c0890 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 12 Mar 2025 16:17:45 -0500 Subject: [PATCH 890/919] Add solution #691 --- 0691-stickers-to-spell-word.js | 46 ++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 47 insertions(+) create mode 100644 0691-stickers-to-spell-word.js diff --git a/0691-stickers-to-spell-word.js b/0691-stickers-to-spell-word.js new file mode 100644 index 00000000..a3bf884c --- /dev/null +++ b/0691-stickers-to-spell-word.js @@ -0,0 +1,46 @@ +/** + * 691. Stickers to Spell Word + * https://leetcode.com/problems/stickers-to-spell-word/ + * Difficulty: Hard + * + * We are given n different types of stickers. Each sticker has a lowercase English word on it. + * + * You would like to spell out the given string target by cutting individual letters from your + * collection of stickers and rearranging them. You can use each sticker more than once if you + * want, and you have infinite quantities of each sticker. + * + * Return the minimum number of stickers that you need to spell out target. If the task is + * impossible, return -1. + * + * Note: In all test cases, all words were chosen randomly from the 1000 most common US English + * words, and target was chosen as a concatenation of two random words. + */ + +/** + * @param {string[]} stickers + * @param {string} target + * @return {number} + */ +var minStickers = function(stickers, target) { + const dp = new Map([['', 0]]); + return helper(target); + + function helper(str) { + if (dp.has(str)) return dp.get(str); + let result = Infinity; + + for (const s of stickers.filter(s => s.includes(str[0]))) { + result = Math.min(result, 1 + helper(calcDiff(str, s))); + } + + dp.set(str, result === Infinity || result === 0 ? -1 : result); + return dp.get(str); + } + + function calcDiff(str1, str2) { + for (const c of str2) { + if (str1.includes(c)) str1 = str1.replace(c, ''); + } + return str1; + } +}; diff --git a/README.md b/README.md index 9140d561..38435bff 100644 --- a/README.md +++ b/README.md @@ -522,6 +522,7 @@ 688|[Knight Probability in Chessboard](./0688-knight-probability-in-chessboard.js)|Medium| 689|[Maximum Sum of 3 Non-Overlapping Subarrays](./0689-maximum-sum-of-3-non-overlapping-subarrays.js)|Hard| 690|[Employee Importance](./0690-employee-importance.js)|Medium| +691|[Stickers to Spell Word](./0691-stickers-to-spell-word.js)|Hard| 692|[Top K Frequent Words](./0692-top-k-frequent-words.js)|Medium| 693|[Binary Number with Alternating Bits](./0693-binary-number-with-alternating-bits.js)|Easy| 695|[Max Area of Island](./0695-max-area-of-island.js)|Medium| From 4531ad7f777f51e9ce05514dca54c4eb5d98670b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 12 Mar 2025 16:21:55 -0500 Subject: [PATCH 891/919] Add solution #721 --- 0721-accounts-merge.js | 49 ++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 50 insertions(+) create mode 100644 0721-accounts-merge.js diff --git a/0721-accounts-merge.js b/0721-accounts-merge.js new file mode 100644 index 00000000..69b6c7cf --- /dev/null +++ b/0721-accounts-merge.js @@ -0,0 +1,49 @@ +/** + * 721. Accounts Merge + * https://leetcode.com/problems/accounts-merge/ + * Difficulty: Medium + * + * Given a list of accounts where each element accounts[i] is a list of strings, where the first + * element accounts[i][0] is a name, and the rest of the elements are emails representing emails + * of the account. + * + * Now, we would like to merge these accounts. Two accounts definitely belong to the same person + * if there is some common email to both accounts. Note that even if two accounts have the same + * name, they may belong to different people as people could have the same name. A person can + * have any number of accounts initially, but all of their accounts definitely have the same name. + * + * After merging the accounts, return the accounts in the following format: the first element of + * each account is the name, and the rest of the elements are emails in sorted order. The accounts + * themselves can be returned in any order. + */ + +/** + * @param {string[][]} accounts + * @return {string[][]} + */ +var accountsMerge = function(accounts) { + const parent = new Map(); + const names = new Map(); + const groups = new Map(); + + const find = node => { + if (!parent.has(node)) parent.set(node, node); + return parent.get(node) === node ? node : parent.set(node, find(parent.get(node))).get(node); + }; + + for (const [name, ...emails] of accounts) { + for (const email of emails) { + names.set(email, name); + find(email); + parent.set(find(email), find(emails[0])); + } + } + + for (const email of parent.keys()) { + const root = find(email); + if (!groups.has(root)) groups.set(root, new Set()); + groups.get(root).add(email); + } + + return Array.from(groups, ([root, emails]) => [names.get(root), ...[...emails].sort()]); +}; diff --git a/README.md b/README.md index 38435bff..7f1ef926 100644 --- a/README.md +++ b/README.md @@ -546,6 +546,7 @@ 718|[Maximum Length of Repeated Subarray](./0718-maximum-length-of-repeated-subarray.js)|Medium| 719|[Find K-th Smallest Pair Distance](./0719-find-k-th-smallest-pair-distance.js)|Hard| 720|[Longest Word in Dictionary](./0720-longest-word-in-dictionary.js)|Medium| +721|[Accounts Merge](./0721-accounts-merge.js)|Medium| 722|[Remove Comments](./0722-remove-comments.js)|Medium| 724|[Find Pivot Index](./0724-find-pivot-index.js)|Easy| 733|[Flood Fill](./0733-flood-fill.js)|Easy| From 354c0defa9dc9d535e7585266d4ca78030988557 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 12 Mar 2025 16:23:54 -0500 Subject: [PATCH 892/919] Add solution #725 --- 0725-split-linked-list-in-parts.js | 56 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 57 insertions(+) create mode 100644 0725-split-linked-list-in-parts.js diff --git a/0725-split-linked-list-in-parts.js b/0725-split-linked-list-in-parts.js new file mode 100644 index 00000000..0659048d --- /dev/null +++ b/0725-split-linked-list-in-parts.js @@ -0,0 +1,56 @@ +/** + * 725. Split Linked List in Parts + * https://leetcode.com/problems/split-linked-list-in-parts/ + * Difficulty: Medium + * + * Given the head of a singly linked list and an integer k, split the linked list into k + * consecutive linked list parts. + * + * The length of each part should be as equal as possible: no two parts should have a size + * differing by more than one. This may lead to some parts being null. + * + * The parts should be in the order of occurrence in the input list, and parts occurring + * earlier should always have a size greater than or equal to parts occurring later. + * + * Return an array of the k parts. + */ + +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @param {number} k + * @return {ListNode[]} + */ +var splitListToParts = function(head, k) { + let count = 0; + let current = head; + + while (current) { + count++; + current = current.next; + } + + const base = Math.floor(count / k); + const extra = count % k; + const result = new Array(k).fill(null); + + current = head; + for (let i = 0; i < k && current; i++) { + result[i] = current; + const partSize = base + (i < extra ? 1 : 0); + for (let j = 1; j < partSize; j++) { + current = current.next; + } + const next = current.next; + current.next = null; + current = next; + } + + return result; +}; diff --git a/README.md b/README.md index 7f1ef926..114daa0e 100644 --- a/README.md +++ b/README.md @@ -549,6 +549,7 @@ 721|[Accounts Merge](./0721-accounts-merge.js)|Medium| 722|[Remove Comments](./0722-remove-comments.js)|Medium| 724|[Find Pivot Index](./0724-find-pivot-index.js)|Easy| +725|[Split Linked List in Parts](./0725-split-linked-list-in-parts.js)|Medium| 733|[Flood Fill](./0733-flood-fill.js)|Easy| 735|[Asteroid Collision](./0735-asteroid-collision.js)|Medium| 739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium| From 3c17a5f2543901fe44809c3da3d26bc080d6e7f7 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 12 Mar 2025 16:27:52 -0500 Subject: [PATCH 893/919] Add solution #726 --- 0726-number-of-atoms.js | 69 +++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 70 insertions(+) create mode 100644 0726-number-of-atoms.js diff --git a/0726-number-of-atoms.js b/0726-number-of-atoms.js new file mode 100644 index 00000000..e1e0496b --- /dev/null +++ b/0726-number-of-atoms.js @@ -0,0 +1,69 @@ +/** + * 726. Number of Atoms + * https://leetcode.com/problems/number-of-atoms/ + * Difficulty: Hard + * + * Given a string formula representing a chemical formula, return the count of each atom. + * + * The atomic element always starts with an uppercase character, then zero or more lowercase + * letters, representing the name. + * + * One or more digits representing that element's count may follow if the count is greater + * than 1. If the count is 1, no digits will follow. + * - For example, "H2O" and "H2O2" are possible, but "H1O2" is impossible. + * + * Two formulas are concatenated together to produce another formula. + * - For example, "H2O2He3Mg4" is also a formula. + * + * A formula placed in parentheses, and a count (optionally added) is also a formula. + * - For example, "(H2O2)" and "(H2O2)3" are formulas. + * + * Return the count of all elements as a string in the following form: the first name (in sorted + * order), followed by its count (if that count is more than 1), followed by the second name + * (in sorted order), followed by its count (if that count is more than 1), and so on. + * + * The test cases are generated so that all the values in the output fit in a 32-bit integer. + */ + +/** + * @param {string} formula + * @return {string} + */ +var countOfAtoms = function(formula) { + const [counts] = parseFormula(formula, 0); + return [...counts].sort().map(([atom, count]) => atom + (count > 1 ? count : '')).join(''); + + function parseFormula(str, index) { + const atomCounts = new Map(); + while (index < str.length && str[index] !== ')') { + if (str[index] === '(') { + const [subCounts, nextIndex] = parseFormula(str, index + 1); + const [multiplier, updatedIndex] = extractNumber(str, nextIndex + 1); + for (const [atom, count] of subCounts) { + atomCounts.set(atom, (atomCounts.get(atom) || 0) + count * (multiplier || 1)); + } + index = updatedIndex; + } else { + const [atom, nextIndex] = extractAtom(str, index); + const [count, updatedIndex] = extractNumber(str, nextIndex); + atomCounts.set(atom, (atomCounts.get(atom) || 0) + (count || 1)); + index = updatedIndex; + } + } + return [atomCounts, index]; + } + + function extractAtom(str, index) { + let atom = str[index]; + while (++index < str.length && /[a-z]/.test(str[index])) atom += str[index]; + return [atom, index]; + } + + function extractNumber(str, index) { + let number = 0; + while (index < str.length && /[0-9]/.test(str[index])) { + number = number * 10 + Number(str[index++]); + } + return [number || null, index]; + } +}; diff --git a/README.md b/README.md index 114daa0e..0e92d7a9 100644 --- a/README.md +++ b/README.md @@ -550,6 +550,7 @@ 722|[Remove Comments](./0722-remove-comments.js)|Medium| 724|[Find Pivot Index](./0724-find-pivot-index.js)|Easy| 725|[Split Linked List in Parts](./0725-split-linked-list-in-parts.js)|Medium| +726|[Number of Atoms](./0726-number-of-atoms.js)|Hard| 733|[Flood Fill](./0733-flood-fill.js)|Easy| 735|[Asteroid Collision](./0735-asteroid-collision.js)|Medium| 739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium| From 6052ccb59470060f1f91990ce91af33e95b427d8 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 12 Mar 2025 16:31:05 -0500 Subject: [PATCH 894/919] Add solution #728 --- 0728-self-dividing-numbers.js | 24 ++++++++++++++++++++++++ README.md | 1 + 2 files changed, 25 insertions(+) create mode 100644 0728-self-dividing-numbers.js diff --git a/0728-self-dividing-numbers.js b/0728-self-dividing-numbers.js new file mode 100644 index 00000000..d54a8628 --- /dev/null +++ b/0728-self-dividing-numbers.js @@ -0,0 +1,24 @@ +/** + * 728. Self Dividing Numbers + * https://leetcode.com/problems/self-dividing-numbers/ + * Difficulty: Easy + * + * A self-dividing number is a number that is divisible by every digit it contains. + * - For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, + * and 128 % 8 == 0. + * + * A self-dividing number is not allowed to contain the digit zero. + * + * Given two integers left and right, return a list of all the self-dividing numbers + * in the range [left, right] (both inclusive). + */ + +/** + * @param {number} left + * @param {number} right + * @return {number[]} + */ +var selfDividingNumbers = function(left, right) { + return Array.from({ length: right - left + 1 }, (_, i) => left + i) + .filter(n => String(n).split('').every(d => d !== '0' && n % d === 0)); +}; diff --git a/README.md b/README.md index 0e92d7a9..032213d3 100644 --- a/README.md +++ b/README.md @@ -551,6 +551,7 @@ 724|[Find Pivot Index](./0724-find-pivot-index.js)|Easy| 725|[Split Linked List in Parts](./0725-split-linked-list-in-parts.js)|Medium| 726|[Number of Atoms](./0726-number-of-atoms.js)|Hard| +728|[Self Dividing Numbers](./0728-self-dividing-numbers.js)|Easy| 733|[Flood Fill](./0733-flood-fill.js)|Easy| 735|[Asteroid Collision](./0735-asteroid-collision.js)|Medium| 739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium| From 690e952cbf3beb4fbd4153bc9f2312ea2fe8c133 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 12 Mar 2025 16:49:23 -0500 Subject: [PATCH 895/919] Add solution #729 --- 0729-my-calendar-i.js | 82 +++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 83 insertions(+) create mode 100644 0729-my-calendar-i.js diff --git a/0729-my-calendar-i.js b/0729-my-calendar-i.js new file mode 100644 index 00000000..51f6cc21 --- /dev/null +++ b/0729-my-calendar-i.js @@ -0,0 +1,82 @@ +/** + * 729. My Calendar I + * https://leetcode.com/problems/my-calendar-i/ + * Difficulty: Medium + * + * You are implementing a program to use as your calendar. We can add a new event if adding the + * event will not cause a double booking. + * + * A double booking happens when two events have some non-empty intersection (i.e., some moment + * is common to both events.). + * + * The event can be represented as a pair of integers startTime and endTime that represents a + * booking on the half-open interval [startTime, endTime), the range of real numbers x such + * that startTime <= x < endTime. + * + * Implement the MyCalendar class: + * - MyCalendar() Initializes the calendar object. + * - boolean book(int startTime, int endTime) Returns true if the event can be added to the + * calendar successfully without causing a double booking. Otherwise, return false and do + * not add the event to the calendar. + */ + +class MyCalendar { + constructor() { + this.events = []; + } + + /** + * @param {number} startTime + * @param {number} endTime + * @returns {boolean} + */ + book(startTime, endTime) { + const event = [startTime, endTime]; + const index = this.findInsertIndex(startTime); + + if (this.overlapsPrevious(index - 1, startTime) || this.overlapsNext(index, endTime)) { + return false; + } + + this.events.splice(index, 0, event); + return true; + } + + /** + * @param {number} startTime + * @returns {number} + */ + findInsertIndex(startTime) { + let left = 0; + let right = this.events.length; + + while (left < right) { + const mid = Math.floor((left + right) / 2); + if (this.events[mid][0] > startTime) { + right = mid; + } else { + left = mid + 1; + } + } + + return left; + } + + /** + * @param {number} prevIndex + * @param {number} startTime + * @returns {boolean} + */ + overlapsPrevious(prevIndex, startTime) { + return prevIndex >= 0 && this.events[prevIndex][1] > startTime; + } + + /** + * @param {number} nextIndex + * @param {number} endTime + * @returns {boolean} + */ + overlapsNext(nextIndex, endTime) { + return nextIndex < this.events.length && this.events[nextIndex][0] < endTime; + } +} diff --git a/README.md b/README.md index 032213d3..1729ce01 100644 --- a/README.md +++ b/README.md @@ -552,6 +552,7 @@ 725|[Split Linked List in Parts](./0725-split-linked-list-in-parts.js)|Medium| 726|[Number of Atoms](./0726-number-of-atoms.js)|Hard| 728|[Self Dividing Numbers](./0728-self-dividing-numbers.js)|Easy| +729|[My Calendar I](./0729-my-calendar-i.js)|Medium| 733|[Flood Fill](./0733-flood-fill.js)|Easy| 735|[Asteroid Collision](./0735-asteroid-collision.js)|Medium| 739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium| From 3195e1945c3ca9d46f3bf29923a83fe556199e7e Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 12 Mar 2025 16:52:15 -0500 Subject: [PATCH 896/919] Add solution #730 --- ...ount-different-palindromic-subsequences.js | 59 +++++++++++++++++++ README.md | 1 + 2 files changed, 60 insertions(+) create mode 100644 0730-count-different-palindromic-subsequences.js diff --git a/0730-count-different-palindromic-subsequences.js b/0730-count-different-palindromic-subsequences.js new file mode 100644 index 00000000..e06f3329 --- /dev/null +++ b/0730-count-different-palindromic-subsequences.js @@ -0,0 +1,59 @@ +/** + * 730. Count Different Palindromic Subsequences + * https://leetcode.com/problems/count-different-palindromic-subsequences/ + * Difficulty: Hard + * + * Given a string s, return the number of different non-empty palindromic subsequences in s. + * Since the answer may be very large, return it modulo 109 + 7. + * + * A subsequence of a string is obtained by deleting zero or more characters from the string. + * + * A sequence is palindromic if it is equal to the sequence reversed. + * + * Two sequences a1, a2, ... and b1, b2, ... are different if there is some i for which ai != bi. + */ + +/** + * @param {string} s + * @return {number} + */ +var countPalindromicSubsequences = function(s) { + const MOD = 1e9 + 7; + const dp = new Array(s.length).fill().map(() => { + return new Array(s.length).fill(0); + }); + + for (let i = 0; i < s.length; i++) { + dp[i][i] = 1; + } + + for (let len = 2; len <= s.length; len++) { + for (let start = 0; start + len <= s.length; start++) { + const end = start + len - 1; + const charStart = s[start]; + const charEnd = s[end]; + + if (charStart !== charEnd) { + dp[start][end] = (dp[start + 1][end] + dp[start][end - 1] - dp[start + 1][end - 1]) % MOD; + } else { + let left = start + 1; + let right = end - 1; + + while (left <= right && s[left] !== charStart) left++; + while (left <= right && s[right] !== charStart) right--; + + if (left > right) { + dp[start][end] = (2 * dp[start + 1][end - 1] + 2) % MOD; + } else if (left === right) { + dp[start][end] = (2 * dp[start + 1][end - 1] + 1) % MOD; + } else { + dp[start][end] = (2 * dp[start + 1][end - 1] - dp[left + 1][right - 1]) % MOD; + } + } + + if (dp[start][end] < 0) dp[start][end] += MOD; + } + } + + return dp[0][s.length - 1]; +}; diff --git a/README.md b/README.md index 1729ce01..88f2ed27 100644 --- a/README.md +++ b/README.md @@ -553,6 +553,7 @@ 726|[Number of Atoms](./0726-number-of-atoms.js)|Hard| 728|[Self Dividing Numbers](./0728-self-dividing-numbers.js)|Easy| 729|[My Calendar I](./0729-my-calendar-i.js)|Medium| +730|[Count Different Palindromic Subsequences](./0730-count-different-palindromic-subsequences.js)|Hard| 733|[Flood Fill](./0733-flood-fill.js)|Easy| 735|[Asteroid Collision](./0735-asteroid-collision.js)|Medium| 739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium| From 0448cdd70ae2de3246a93fa37a30b1f53ff2224d Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 12 Mar 2025 16:54:08 -0500 Subject: [PATCH 897/919] Add solution #731 --- 0731-my-calendar-ii.js | 46 ++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 47 insertions(+) create mode 100644 0731-my-calendar-ii.js diff --git a/0731-my-calendar-ii.js b/0731-my-calendar-ii.js new file mode 100644 index 00000000..b2e05575 --- /dev/null +++ b/0731-my-calendar-ii.js @@ -0,0 +1,46 @@ +/** + * 731. My Calendar II + * https://leetcode.com/problems/my-calendar-ii/ + * Difficulty: Medium + * + * You are implementing a program to use as your calendar. We can add a new event if adding the + * event will not cause a triple booking. + * + * A triple booking happens when three events have some non-empty intersection (i.e., some moment + * is common to all the three events.). + * + * The event can be represented as a pair of integers startTime and endTime that represents a + * booking on the half-open interval [startTime, endTime), the range of real numbers x such that + * startTime <= x < endTime. + * + * Implement the MyCalendarTwo class: + * - MyCalendarTwo() Initializes the calendar object. + * - boolean book(int startTime, int endTime) Returns true if the event can be added to the calendar + * successfully without causing a triple booking. Otherwise, return false and do not add the event + * to the calendar. + */ + +var MyCalendarTwo = function() { + this.bookings = []; + this.overlaps = []; +}; + +/** + * @param {number} startTime + * @param {number} endTime + * @return {boolean} + */ +MyCalendarTwo.prototype.book = function(startTime, endTime) { + for (const [start, end] of this.overlaps) { + if (startTime < end && endTime > start) return false; + } + + for (const [start, end] of this.bookings) { + if (startTime < end && endTime > start) { + this.overlaps.push([Math.max(start, startTime), Math.min(end, endTime)]); + } + } + + this.bookings.push([startTime, endTime]); + return true; +}; diff --git a/README.md b/README.md index 88f2ed27..5669dd5e 100644 --- a/README.md +++ b/README.md @@ -554,6 +554,7 @@ 728|[Self Dividing Numbers](./0728-self-dividing-numbers.js)|Easy| 729|[My Calendar I](./0729-my-calendar-i.js)|Medium| 730|[Count Different Palindromic Subsequences](./0730-count-different-palindromic-subsequences.js)|Hard| +731|[My Calendar II](./0731-my-calendar-ii.js)|Medium| 733|[Flood Fill](./0733-flood-fill.js)|Easy| 735|[Asteroid Collision](./0735-asteroid-collision.js)|Medium| 739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium| From 6c77a632003e0f5ba90508acb6ac09a1a603fa32 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 12 Mar 2025 16:58:01 -0500 Subject: [PATCH 898/919] Add solution #732 --- 0732-my-calendar-iii.js | 53 +++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 54 insertions(+) create mode 100644 0732-my-calendar-iii.js diff --git a/0732-my-calendar-iii.js b/0732-my-calendar-iii.js new file mode 100644 index 00000000..38b438a1 --- /dev/null +++ b/0732-my-calendar-iii.js @@ -0,0 +1,53 @@ +/** + * 732. My Calendar III + * https://leetcode.com/problems/my-calendar-iii/ + * Difficulty: Hard + * + * A k-booking happens when k events have some non-empty intersection (i.e., there is some time + * that is common to all k events.) + * + * You are given some events [startTime, endTime), after each given event, return an integer k + * representing the maximum k-booking between all the previous events. + * + * Implement the MyCalendarThree class: + * - MyCalendarThree() Initializes the object. + * - int book(int startTime, int endTime) Returns an integer k representing the largest integer + * such that there exists a k-booking in the calendar. + */ + +class MyCalendarThree { + constructor() { + this.events = []; + } + + /** + * @param {number} startTime + * @param {number} endTime + * @returns {number} + */ + book(startTime, endTime) { + this.insertTime(startTime, 1); + this.insertTime(endTime, -1); + let maxBookings = 1; + let currentBookings = 0; + this.events.forEach(event => maxBookings = Math.max(currentBookings += event[1], maxBookings)); + return maxBookings; + } + + /** + * @param {number} targetTime + * @param {number} value + */ + insertTime(targetTime, value) { + const events = this.events; + let left = 0; + let right = events.length - 1; + while (left <= right) { + const mid = left + right >> 1; + if (events[mid][0] < targetTime) left = mid + 1; + else if (events[mid][0] > targetTime) right = mid - 1; + else return events[mid][1] += value; + } + events.splice(left, 0, [targetTime, value]); + } +} diff --git a/README.md b/README.md index 5669dd5e..ec3e7d02 100644 --- a/README.md +++ b/README.md @@ -555,6 +555,7 @@ 729|[My Calendar I](./0729-my-calendar-i.js)|Medium| 730|[Count Different Palindromic Subsequences](./0730-count-different-palindromic-subsequences.js)|Hard| 731|[My Calendar II](./0731-my-calendar-ii.js)|Medium| +732|[My Calendar III](./0732-my-calendar-iii.js)|Hard| 733|[Flood Fill](./0733-flood-fill.js)|Easy| 735|[Asteroid Collision](./0735-asteroid-collision.js)|Medium| 739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium| From e27ca5125cc906c6242b57bb64b608a47f082e3c Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 12 Mar 2025 17:01:56 -0500 Subject: [PATCH 899/919] Add solution #736 --- 0736-parse-lisp-expression.js | 75 +++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 76 insertions(+) create mode 100644 0736-parse-lisp-expression.js diff --git a/0736-parse-lisp-expression.js b/0736-parse-lisp-expression.js new file mode 100644 index 00000000..e465f85e --- /dev/null +++ b/0736-parse-lisp-expression.js @@ -0,0 +1,75 @@ +/** + * 736. Parse Lisp Expression + * https://leetcode.com/problems/parse-lisp-expression/ + * Difficulty: Hard + * + * You are given a string expression representing a Lisp-like expression to return the integer + * value of. + * + * The syntax for these expressions is given as follows. + * - An expression is either an integer, let expression, add expression, mult expression, or an + * assigned variable. Expressions always evaluate to a single integer. + * - (An integer could be positive or negative.) + * - A let expression takes the form "(let v1 e1 v2 e2 ... vn en expr)", where let is always the + * string "let", then there are one or more pairs of alternating variables and expressions, + * meaning that the first variable v1 is assigned the value of the expression e1, the second + * variable v2 is assigned the value of the expression e2, and so on sequentially; and then the + * value of this let expression is the value of the expression expr. + * - An add expression takes the form "(add e1 e2)" where add is always the string "add", there are + * always two expressions e1, e2 and the result is the addition of the evaluation of e1 and the + * evaluation of e2. + * - A mult expression takes the form "(mult e1 e2)" where mult is always the string "mult", there + * are always two expressions e1, e2 and the result is the multiplication of the evaluation of + * e1 and the evaluation of e2. + * - For this question, we will use a smaller subset of variable names. A variable starts with a + * lowercase letter, then zero or more lowercase letters or digits. Additionally, for your + * convenience, the names "add", "let", and "mult" are protected and will never be used as + * variable names. + * - Finally, there is the concept of scope. When an expression of a variable name is evaluated, + * within the context of that evaluation, the innermost scope (in terms of parentheses) is + * checked first for the value of that variable, and then outer scopes are checked sequentially. + * It is guaranteed that every expression is legal. Please see the examples for more details + * on the scope. + */ + +/** + * @param {string} expression + * @return {number} + */ +var evaluate = function(expression) { + return parse(expression, new Map()); + + function parse(exp, scope) { + if (!isNaN(exp)) return parseInt(exp); + if (!exp.startsWith('(')) return scope.get(exp) || 0; + + const tokens = tokenize(exp.slice(1, -1)); + if (tokens[0] === 'add') return parse(tokens[1], scope) + parse(tokens[2], scope); + if (tokens[0] === 'mult') return parse(tokens[1], scope) * parse(tokens[2], scope); + + const newScope = new Map(scope); + for (let i = 1; i < tokens.length - 1; i += 2) { + newScope.set(tokens[i], parse(tokens[i + 1], newScope)); + } + return parse(tokens[tokens.length - 1], newScope); + } + + function tokenize(exp) { + const result = []; + let current = ''; + let depth = 0; + + for (const char of exp) { + if (char === ' ' && depth === 0) { + result.push(current); + current = ''; + } else { + current += char; + if (char === '(') depth++; + if (char === ')') depth--; + } + } + result.push(current); + return result; + } +}; diff --git a/README.md b/README.md index ec3e7d02..a406a508 100644 --- a/README.md +++ b/README.md @@ -558,6 +558,7 @@ 732|[My Calendar III](./0732-my-calendar-iii.js)|Hard| 733|[Flood Fill](./0733-flood-fill.js)|Easy| 735|[Asteroid Collision](./0735-asteroid-collision.js)|Medium| +736|[Parse Lisp Expression](./0736-parse-lisp-expression.js)|Hard| 739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium| 743|[Network Delay Time](./0743-network-delay-time.js)|Medium| 744|[Find Smallest Letter Greater Than Target](./0744-find-smallest-letter-greater-than-target.js)|Easy| From a1266d601bcf6e6752d101f26b9e3eda1639231b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 12 Mar 2025 19:59:56 -0500 Subject: [PATCH 900/919] Add solution #3356 --- 3356-zero-array-transformation-ii.js | 64 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 65 insertions(+) create mode 100644 3356-zero-array-transformation-ii.js diff --git a/3356-zero-array-transformation-ii.js b/3356-zero-array-transformation-ii.js new file mode 100644 index 00000000..59c4b9e4 --- /dev/null +++ b/3356-zero-array-transformation-ii.js @@ -0,0 +1,64 @@ +/** + * 3356. Zero Array Transformation II + * https://leetcode.com/problems/zero-array-transformation-ii/ + * Difficulty: Medium + * + * You are given an integer array nums of length n and a 2D array queries where + * queries[i] = [li, ri, vali]. + * + * Each queries[i] represents the following action on nums: + * - Decrement the value at each index in the range [li, ri] in nums by at most vali. + * - The amount by which each value is decremented can be chosen independently for each index. + * + * A Zero Array is an array with all its elements equal to 0. + * + * Return the minimum possible non-negative value of k, such that after processing the first + * k queries in sequence, nums becomes a Zero Array. If no such k exists, return -1. + */ + +/** + * @param {number[]} nums + * @param {number[][]} queries + * @return {number} + */ +var minZeroArray = function(nums, queries) { + const diff = new Array(nums.length + 1).fill(0); + const total = nums.reduce((sum, num) => sum + num, 0); + let left = 0; + let right = queries.length - 1; + let result = -1; + + if (total === 0) { + return 0; + } + + while (left <= right) { + const mid = Math.floor((left + right) / 2); + if (canZeroOut(mid)) { + result = mid + 1; + right = mid - 1; + } else { + left = mid + 1; + } + } + + return result; + + function canZeroOut(k) { + const tempDiff = new Array(nums.length + 1).fill(0); + for (let i = 0; i <= k; i++) { + const [left, right, val] = queries[i]; + tempDiff[left] += val; + if (right + 1 < nums.length) tempDiff[right + 1] -= val; + } + + let current = 0; + let reduction = 0; + for (let i = 0; i < nums.length; i++) { + current = Math.max(0, current + tempDiff[i]); + reduction += Math.min(nums[i], current); + if (reduction >= total) return true; + } + return reduction >= total; + } +}; diff --git a/README.md b/README.md index a406a508..a4097677 100644 --- a/README.md +++ b/README.md @@ -863,6 +863,7 @@ 3208|[Alternating Groups II](./3208-alternating-groups-ii.js)|Medium| 3223|[Minimum Length of String After Operations](./3223-minimum-length-of-string-after-operations.js)|Medium| 3306|[Count of Substrings Containing Every Vowel and K Consonants II](./3306-count-of-substrings-containing-every-vowel-and-k-consonants-ii.js)|Medium| +3356|[Zero Array Transformation II](./3356-zero-array-transformation-ii.js)|Medium| 3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy| 3396|[Minimum Number of Operations to Make Elements in Array Distinct](./3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy| 3397|[Maximum Number of Distinct Elements After Operations](./3397-maximum-number-of-distinct-elements-after-operations.js)|Medium| From fe4e5e7f8c82cfda871241f009476d0ac7c16fcc Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 12 Mar 2025 20:03:52 -0500 Subject: [PATCH 901/919] Add solution #738 --- 0738-monotone-increasing-digits.js | 33 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 0738-monotone-increasing-digits.js diff --git a/0738-monotone-increasing-digits.js b/0738-monotone-increasing-digits.js new file mode 100644 index 00000000..0505a5c3 --- /dev/null +++ b/0738-monotone-increasing-digits.js @@ -0,0 +1,33 @@ +/** + * 738. Monotone Increasing Digits + * https://leetcode.com/problems/monotone-increasing-digits/ + * Difficulty: Medium + * + * An integer has monotone increasing digits if and only if each pair of adjacent digits + * x and y satisfy x <= y. + * + * Given an integer n, return the largest number that is less than or equal to n with + * monotone increasing digits. + */ + +/** + * @param {number} n + * @return {number} + */ +var monotoneIncreasingDigits = function(n) { + const digits = String(n).split('').map(Number); + let offset = digits.length; + + for (let i = digits.length - 1; i > 0; i--) { + if (digits[i - 1] > digits[i]) { + offset = i; + digits[i - 1]--; + } + } + + for (let i = offset; i < digits.length; i++) { + digits[i] = 9; + } + + return +digits.join(''); +}; diff --git a/README.md b/README.md index a4097677..493ab0a8 100644 --- a/README.md +++ b/README.md @@ -559,6 +559,7 @@ 733|[Flood Fill](./0733-flood-fill.js)|Easy| 735|[Asteroid Collision](./0735-asteroid-collision.js)|Medium| 736|[Parse Lisp Expression](./0736-parse-lisp-expression.js)|Hard| +738|[Monotone Increasing Digits](./0738-monotone-increasing-digits.js)|Medium| 739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium| 743|[Network Delay Time](./0743-network-delay-time.js)|Medium| 744|[Find Smallest Letter Greater Than Target](./0744-find-smallest-letter-greater-than-target.js)|Easy| From 23d2d73c10bdeef2895659bfad4cb501e3aa280a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 12 Mar 2025 20:06:02 -0500 Subject: [PATCH 902/919] Add solution #740 --- 0740-delete-and-earn.js | 35 +++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 36 insertions(+) create mode 100644 0740-delete-and-earn.js diff --git a/0740-delete-and-earn.js b/0740-delete-and-earn.js new file mode 100644 index 00000000..57295b2d --- /dev/null +++ b/0740-delete-and-earn.js @@ -0,0 +1,35 @@ +/** + * 740. Delete and Earn + * https://leetcode.com/problems/delete-and-earn/ + * Difficulty: Medium + * + * You are given an integer array nums. You want to maximize the number of points you get by + * performing the following operation any number of times: + * - Pick any nums[i] and delete it to earn nums[i] points. Afterwards, you must delete every + * element equal to nums[i] - 1 and every element equal to nums[i] + 1. + * + * Return the maximum number of points you can earn by applying the above operation some number + * of times. + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var deleteAndEarn = function(nums) { + const points = new Array(10001).fill(0); + let previous = 0; + let result = 0; + + for (const num of nums) { + points[num] += num; + } + + for (const value of points) { + const temp = result; + result = Math.max(result, previous + value); + previous = temp; + } + + return result; +}; diff --git a/README.md b/README.md index 493ab0a8..b5e08a33 100644 --- a/README.md +++ b/README.md @@ -561,6 +561,7 @@ 736|[Parse Lisp Expression](./0736-parse-lisp-expression.js)|Hard| 738|[Monotone Increasing Digits](./0738-monotone-increasing-digits.js)|Medium| 739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium| +740|[Delete and Earn](./0740-delete-and-earn.js)|Medium| 743|[Network Delay Time](./0743-network-delay-time.js)|Medium| 744|[Find Smallest Letter Greater Than Target](./0744-find-smallest-letter-greater-than-target.js)|Easy| 745|[Prefix and Suffix Search](./0745-prefix-and-suffix-search.js)|Hard| From 3ef404801d8985fa0cce65ca0571e84b46caba4a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 12 Mar 2025 20:09:59 -0500 Subject: [PATCH 903/919] Add solution #741 --- 0741-cherry-pickup.js | 63 +++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 64 insertions(+) create mode 100644 0741-cherry-pickup.js diff --git a/0741-cherry-pickup.js b/0741-cherry-pickup.js new file mode 100644 index 00000000..b9d347ed --- /dev/null +++ b/0741-cherry-pickup.js @@ -0,0 +1,63 @@ +/** + * 741. Cherry Pickup + * https://leetcode.com/problems/cherry-pickup/ + * Difficulty: Hard + * + * You are given an n x n grid representing a field of cherries, each cell is one of three + * possible integers. + * - 0 means the cell is empty, so you can pass through, + * - 1 means the cell contains a cherry that you can pick up and pass through, or + * - -1 means the cell contains a thorn that blocks your way. + * + * Return the maximum number of cherries you can collect by following the rules below: + * - Starting at the position (0, 0) and reaching (n - 1, n - 1) by moving right or down through + * valid path cells (cells with value 0 or 1). + * - After reaching (n - 1, n - 1), returning to (0, 0) by moving left or up through valid path + * cells. + * - When passing through a path cell containing a cherry, you pick it up, and the cell becomes + * an empty cell 0. + * - If there is no valid path between (0, 0) and (n - 1, n - 1), then no cherries can be collected. + */ + +/** + * @param {number[][]} grid + * @return {number} + */ +var cherryPickup = function(grid) { + const n = grid.length; + const dp = Array.from({ length: n }, () => + Array.from({ length: n }, () => + new Array(2 * n - 1).fill(-1)) + ); + + if (grid[0][0] === -1) return 0; + dp[0][0][0] = grid[0][0]; + + for (let t = 1; t <= 2 * n - 2; t++) { + for (let x1 = Math.max(0, t - n + 1); x1 <= Math.min(n - 1, t); x1++) { + for (let x2 = Math.max(0, t - n + 1); x2 <= Math.min(n - 1, t); x2++) { + const y1 = t - x1; + const y2 = t - x2; + + if (grid[x1][y1] === -1 || grid[x2][y2] === -1) continue; + + const cherries = grid[x1][y1] + (x1 === x2 ? 0 : grid[x2][y2]); + let maxPrev = -1; + + for (const px1 of [x1 - 1, x1]) { + for (const px2 of [x2 - 1, x2]) { + if (px1 >= 0 && px2 >= 0 && dp[px1][px2][t - 1] >= 0) { + maxPrev = Math.max(maxPrev, dp[px1][px2][t - 1]); + } + } + } + + if (maxPrev >= 0) { + dp[x1][x2][t] = maxPrev + cherries; + } + } + } + } + + return dp[n - 1][n - 1][2 * n - 2] < 0 ? 0 : dp[n - 1][n - 1][2 * n - 2]; +}; diff --git a/README.md b/README.md index b5e08a33..305c24d1 100644 --- a/README.md +++ b/README.md @@ -562,6 +562,7 @@ 738|[Monotone Increasing Digits](./0738-monotone-increasing-digits.js)|Medium| 739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium| 740|[Delete and Earn](./0740-delete-and-earn.js)|Medium| +741|[Cherry Pickup](./0741-cherry-pickup.js)|Hard| 743|[Network Delay Time](./0743-network-delay-time.js)|Medium| 744|[Find Smallest Letter Greater Than Target](./0744-find-smallest-letter-greater-than-target.js)|Easy| 745|[Prefix and Suffix Search](./0745-prefix-and-suffix-search.js)|Hard| From 924865be92e6071ffb473d41975680fbee88aa13 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Wed, 12 Mar 2025 20:15:04 -0500 Subject: [PATCH 904/919] Add solution #749 --- 0749-contain-virus.js | 91 +++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 92 insertions(+) create mode 100644 0749-contain-virus.js diff --git a/0749-contain-virus.js b/0749-contain-virus.js new file mode 100644 index 00000000..a9fca54d --- /dev/null +++ b/0749-contain-virus.js @@ -0,0 +1,91 @@ +/** + * 749. Contain Virus + * https://leetcode.com/problems/contain-virus/ + * Difficulty: Hard + * + * A virus is spreading rapidly, and your task is to quarantine the infected area by + * installing walls. + * + * The world is modeled as an m x n binary grid isInfected, where isInfected[i][j] == 0 + * represents uninfected cells, and isInfected[i][j] == 1 represents cells contaminated + * with the virus. A wall (and only one wall) can be installed between any two 4-directionally + * adjacent cells, on the shared boundary. + * + * Every night, the virus spreads to all neighboring cells in all four directions unless + * blocked by a wall. Resources are limited. Each day, you can install walls around only one + * region (i.e., the affected area (continuous block of infected cells) that threatens the + * most uninfected cells the following night). There will never be a tie. + * + * Return the number of walls used to quarantine all the infected regions. If the world will + * become fully infected, return the number of walls used. + */ + +/** + * @param {number[][]} isInfected + * @return {number} + */ +var containVirus = function(isInfected) { + const verticalBarriers = new Set(); + const horizontalBarriers = new Set(); + const grid = isInfected; + const rows = grid.length; + const cols = grid[0].length; + const directions = [[-1, 0, -cols, -cols], [1, 0, cols, 0], [0, -1, -1, -1], [0, 1, 1, 0]]; + let target; + let nextState; + let maxThreat; + let threatenedCells; + let nextVertical; + let nextHorizontal; + let verticalWalls; + let horizontalWalls; + let startRow; + let startCol; + + while (true) { + target = 1; + nextState = 2; + maxThreat = 0; + grid.forEach((row, r) => row.forEach((cell, c) => cell && exploreRegion(r, c))); + if (maxThreat === 0) return verticalBarriers.size + horizontalBarriers.size; + target = 2; + nextState = 0; + traverseRegion(startRow, startCol); + verticalWalls.forEach(pos => verticalBarriers.add(pos)); + horizontalWalls.forEach(pos => horizontalBarriers.add(pos)); + nextState = 1; + threatenedCells = new Set(); + grid.forEach((row, r) => row.forEach((cell, c) => cell && traverseRegion(r, c))); + threatenedCells.forEach(pos => grid[Math.floor(pos / cols)][pos % cols] = 1); + } + + function exploreRegion(row, col) { + threatenedCells = new Set(); + nextVertical = new Set(); + nextHorizontal = new Set(); + traverseRegion(row, col); + if (threatenedCells.size < maxThreat) return; + maxThreat = threatenedCells.size; + verticalWalls = nextVertical; + horizontalWalls = nextHorizontal; + startRow = row; + startCol = col; + } + + function traverseRegion(row, col) { + if (grid[row][col] !== target) return; + grid[row][col] = nextState; + const position = cols * row + col; + for (let i = 0; i < 4; i++) { + const [deltaRow, deltaCol, threatOffset, wallOffset] = directions[i]; + const newRow = row + deltaRow; + const newCol = col + deltaCol; + if (newRow < 0 || newRow === rows || newCol < 0 || newCol === cols) continue; + traverseRegion(newRow, newCol); + if (grid[newRow][newCol] + || (deltaRow ? verticalBarriers : horizontalBarriers).has(position + wallOffset)) continue; + if (nextState) threatenedCells.add(position + threatOffset); + if (nextState > 1) (deltaRow ? nextVertical : nextHorizontal).add(position + wallOffset); + } + } +}; diff --git a/README.md b/README.md index 305c24d1..917d4080 100644 --- a/README.md +++ b/README.md @@ -569,6 +569,7 @@ 746|[Min Cost Climbing Stairs](./0746-min-cost-climbing-stairs.js)|Easy| 747|[Largest Number At Least Twice of Others](./0747-largest-number-at-least-twice-of-others.js)|Easy| 748|[Shortest Completing Word](./0748-shortest-completing-word.js)|Easy| +749|[Contain Virus](./0749-contain-virus.js)|Hard| 762|[Prime Number of Set Bits in Binary Representation](./0762-prime-number-of-set-bits-in-binary-representation.js)|Easy| 763|[Partition Labels](./0763-partition-labels.js)|Medium| 783|[Minimum Distance Between BST Nodes](./0783-minimum-distance-between-bst-nodes.js)|Easy| From 2efe5c1c460960e2b28fa67107f69abaedd46dc1 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 13 Mar 2025 01:16:34 -0500 Subject: [PATCH 905/919] Add solution #752 --- 0752-open-the-lock.js | 54 +++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 55 insertions(+) create mode 100644 0752-open-the-lock.js diff --git a/0752-open-the-lock.js b/0752-open-the-lock.js new file mode 100644 index 00000000..873036ab --- /dev/null +++ b/0752-open-the-lock.js @@ -0,0 +1,54 @@ +/** + * 752. Open the Lock + * https://leetcode.com/problems/open-the-lock/ + * Difficulty: Medium + * + * You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', + * '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example + * we can turn '9' to be '0', or '0' to be '9'. Each move consists of turning one wheel one slot. + * + * The lock initially starts at '0000', a string representing the state of the 4 wheels. + * + * You are given a list of deadends dead ends, meaning if the lock displays any of these codes, + * the wheels of the lock will stop turning and you will be unable to open it. + * + * Given a target representing the value of the wheels that will unlock the lock, return the + * minimum total number of turns required to open the lock, or -1 if it is impossible. + */ + +/** + * @param {string[]} deadends + * @param {string} target + * @return {number} + */ +var openLock = function(deadends, target) { + const dead = new Set(deadends); + const queue = [['0000', 0]]; + const seen = new Set(['0000']); + + if (dead.has('0000')) return -1; + while (queue.length) { + const [combo, turns] = queue.shift(); + if (combo === target) return turns; + + for (let i = 0; i < 4; i++) { + const current = combo[i]; + const up = (parseInt(current) + 1) % 10; + const down = (parseInt(current) + 9) % 10; + + const nextUp = combo.slice(0, i) + up + combo.slice(i + 1); + if (!seen.has(nextUp) && !dead.has(nextUp)) { + queue.push([nextUp, turns + 1]); + seen.add(nextUp); + } + + const nextDown = combo.slice(0, i) + down + combo.slice(i + 1); + if (!seen.has(nextDown) && !dead.has(nextDown)) { + queue.push([nextDown, turns + 1]); + seen.add(nextDown); + } + } + } + + return -1; +}; diff --git a/README.md b/README.md index 917d4080..396a7406 100644 --- a/README.md +++ b/README.md @@ -570,6 +570,7 @@ 747|[Largest Number At Least Twice of Others](./0747-largest-number-at-least-twice-of-others.js)|Easy| 748|[Shortest Completing Word](./0748-shortest-completing-word.js)|Easy| 749|[Contain Virus](./0749-contain-virus.js)|Hard| +752|[Open the Lock](./0752-open-the-lock.js)|Medium| 762|[Prime Number of Set Bits in Binary Representation](./0762-prime-number-of-set-bits-in-binary-representation.js)|Easy| 763|[Partition Labels](./0763-partition-labels.js)|Medium| 783|[Minimum Distance Between BST Nodes](./0783-minimum-distance-between-bst-nodes.js)|Easy| From 81417460587b1eac5a29955411eefcb531df08e1 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 13 Mar 2025 01:20:33 -0500 Subject: [PATCH 906/919] Add solution #753 --- 0753-cracking-the-safe.js | 54 +++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 55 insertions(+) create mode 100644 0753-cracking-the-safe.js diff --git a/0753-cracking-the-safe.js b/0753-cracking-the-safe.js new file mode 100644 index 00000000..52ff0014 --- /dev/null +++ b/0753-cracking-the-safe.js @@ -0,0 +1,54 @@ +/** + * 753. Cracking the Safe + * https://leetcode.com/problems/cracking-the-safe/ + * Difficulty: Hard + * + * There is a safe protected by a password. The password is a sequence of n digits where each + * digit can be in the range [0, k - 1]. + * + * The safe has a peculiar way of checking the password. When you enter in a sequence, it checks + * the most recent n digits that were entered each time you type a digit. + * + * For example, the correct password is "345" and you enter in "012345": + * - After typing 0, the most recent 3 digits is "0", which is incorrect. + * - After typing 1, the most recent 3 digits is "01", which is incorrect. + * - After typing 2, the most recent 3 digits is "012", which is incorrect. + * - After typing 3, the most recent 3 digits is "123", which is incorrect. + * - After typing 4, the most recent 3 digits is "234", which is incorrect. + * - After typing 5, the most recent 3 digits is "345", which is correct and the safe unlocks. + * + * Return any string of minimum length that will unlock the safe at some point of entering it. + */ + +/** + * @param {number} n + * @param {number} k + * @return {string} + */ +var crackSafe = function(n, k) { + if (n === 1) return Array.from({ length: k }, (_, i) => i).join(''); + const seen = new Set(); + const targetSize = k ** n; + let sequence = '0'.repeat(n); + + seen.add(sequence); + build(sequence); + return sequence; + + function build(curr) { + if (seen.size === targetSize) return true; + + const prefix = curr.slice(-n + 1); + for (let digit = 0; digit < k; digit++) { + const next = prefix + digit; + if (!seen.has(next)) { + seen.add(next); + sequence += digit; + if (build(sequence)) return true; + sequence = sequence.slice(0, -1); + seen.delete(next); + } + } + return false; + } +}; diff --git a/README.md b/README.md index 396a7406..0c4b3843 100644 --- a/README.md +++ b/README.md @@ -571,6 +571,7 @@ 748|[Shortest Completing Word](./0748-shortest-completing-word.js)|Easy| 749|[Contain Virus](./0749-contain-virus.js)|Hard| 752|[Open the Lock](./0752-open-the-lock.js)|Medium| +753|[Cracking the Safe](./0753-cracking-the-safe.js)|Hard| 762|[Prime Number of Set Bits in Binary Representation](./0762-prime-number-of-set-bits-in-binary-representation.js)|Easy| 763|[Partition Labels](./0763-partition-labels.js)|Medium| 783|[Minimum Distance Between BST Nodes](./0783-minimum-distance-between-bst-nodes.js)|Easy| From fff9c79c9954da2c786da48c2fda3c0da5c586b6 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 13 Mar 2025 01:23:28 -0500 Subject: [PATCH 907/919] Add solution #754 --- 0754-reach-a-number.js | 31 +++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 0754-reach-a-number.js diff --git a/0754-reach-a-number.js b/0754-reach-a-number.js new file mode 100644 index 00000000..4150f53f --- /dev/null +++ b/0754-reach-a-number.js @@ -0,0 +1,31 @@ +/** + * 754. Reach a Number + * https://leetcode.com/problems/reach-a-number/ + * Difficulty: Medium + * + * You are standing at position 0 on an infinite number line. There is a destination at + * position target. + * + * You can make some number of moves numMoves so that: + * - On each move, you can either go left or right. + * - During the ith move (starting from i == 1 to i == numMoves), you take i steps in the + * chosen direction. + * + * Given the integer target, return the minimum number of moves required (i.e., the minimum + * numMoves) to reach the destination. + */ + +/** + * @param {number} target + * @return {number} + */ +var reachNumber = function(target) { + const absTarget = Math.abs(target); + let moves = Math.floor(Math.sqrt(2 * absTarget)); + + while (true) { + const sum = moves * (moves + 1) / 2; + if (sum >= absTarget && (sum - absTarget) % 2 === 0) return moves; + moves++; + } +}; diff --git a/README.md b/README.md index 0c4b3843..39af4a4a 100644 --- a/README.md +++ b/README.md @@ -572,6 +572,7 @@ 749|[Contain Virus](./0749-contain-virus.js)|Hard| 752|[Open the Lock](./0752-open-the-lock.js)|Medium| 753|[Cracking the Safe](./0753-cracking-the-safe.js)|Hard| +754|[Reach a Number](./0754-reach-a-number.js)|Medium| 762|[Prime Number of Set Bits in Binary Representation](./0762-prime-number-of-set-bits-in-binary-representation.js)|Easy| 763|[Partition Labels](./0763-partition-labels.js)|Medium| 783|[Minimum Distance Between BST Nodes](./0783-minimum-distance-between-bst-nodes.js)|Easy| From 036f8a804b882480b068e6d44416badcfc58017a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 13 Mar 2025 01:26:10 -0500 Subject: [PATCH 908/919] Add solution #756 --- 0756-pyramid-transition-matrix.js | 53 +++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 54 insertions(+) create mode 100644 0756-pyramid-transition-matrix.js diff --git a/0756-pyramid-transition-matrix.js b/0756-pyramid-transition-matrix.js new file mode 100644 index 00000000..65392426 --- /dev/null +++ b/0756-pyramid-transition-matrix.js @@ -0,0 +1,53 @@ +/** + * 756. Pyramid Transition Matrix + * https://leetcode.com/problems/pyramid-transition-matrix/ + * Difficulty: Medium + * + * You are stacking blocks to form a pyramid. Each block has a color, which is represented by + * a single letter. Each row of blocks contains one less block than the row beneath it and is + * centered on top. + * + * To make the pyramid aesthetically pleasing, there are only specific triangular patterns that + * are allowed. A triangular pattern consists of a single block stacked on top of two blocks. + * The patterns are given as a list of three-letter strings allowed, where the first two characters + * of a pattern represent the left and right bottom blocks respectively, and the third character + * is the top block. + * + * For example, "ABC" represents a triangular pattern with a 'C' block stacked on top of an 'A' + * (left) and 'B' (right) block. Note that this is different from "BAC" where 'B' is on the left + * bottom and 'A' is on the right bottom. + * + * You start with a bottom row of blocks bottom, given as a single string, that you must use as + * the base of the pyramid. + * + * Given bottom and allowed, return true if you can build the pyramid all the way to the top such + * that every triangular pattern in the pyramid is in allowed, or false otherwise. + */ + +/** + * @param {string} bottom + * @param {string[]} allowed + * @return {boolean} + */ +var pyramidTransition = function(bottom, allowed) { + const transitions = new Map(); + for (const [left, right, top] of allowed) { + const key = left + right; + transitions.set(key, (transitions.get(key) || '') + top); + } + + function canBuild(row, nextRow = '') { + if (row.length === 1) return true; + if (nextRow.length === row.length - 1) return canBuild(nextRow); + + const pair = row.slice(nextRow.length, nextRow.length + 2); + const options = transitions.get(pair) || ''; + + for (const top of options) { + if (canBuild(row, nextRow + top)) return true; + } + return false; + } + + return canBuild(bottom); +}; diff --git a/README.md b/README.md index 39af4a4a..7a1a181d 100644 --- a/README.md +++ b/README.md @@ -573,6 +573,7 @@ 752|[Open the Lock](./0752-open-the-lock.js)|Medium| 753|[Cracking the Safe](./0753-cracking-the-safe.js)|Hard| 754|[Reach a Number](./0754-reach-a-number.js)|Medium| +756|[Pyramid Transition Matrix](./0756-pyramid-transition-matrix.js)|Medium| 762|[Prime Number of Set Bits in Binary Representation](./0762-prime-number-of-set-bits-in-binary-representation.js)|Easy| 763|[Partition Labels](./0763-partition-labels.js)|Medium| 783|[Minimum Distance Between BST Nodes](./0783-minimum-distance-between-bst-nodes.js)|Easy| From 90a439a4e56a1507af776868a9623ef4e73f9234 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 13 Mar 2025 01:27:44 -0500 Subject: [PATCH 909/919] Add solution #757 --- 0757-set-intersection-size-at-least-two.js | 45 ++++++++++++++++++++++ README.md | 1 + 2 files changed, 46 insertions(+) create mode 100644 0757-set-intersection-size-at-least-two.js diff --git a/0757-set-intersection-size-at-least-two.js b/0757-set-intersection-size-at-least-two.js new file mode 100644 index 00000000..7ee9b0b2 --- /dev/null +++ b/0757-set-intersection-size-at-least-two.js @@ -0,0 +1,45 @@ +/** + * 757. Set Intersection Size At Least Two + * https://leetcode.com/problems/set-intersection-size-at-least-two/ + * Difficulty: Hard + * + * You are given a 2D integer array intervals where intervals[i] = [starti, endi] represents + * all the integers from starti to endi inclusively. + * + * A containing set is an array nums where each interval from intervals has at least two + * integers in nums. + * + * For example, if intervals = [[1,3], [3,7], [8,9]], then [1,2,4,7,8,9] and [2,3,4,8,9] + * are containing sets. + * + * Return the minimum possible size of a containing set. + */ + +/** + * @param {number[][]} intervals + * @return {number} + */ +var intersectionSizeTwo = function(intervals) { + intervals.sort((a, b) => a[1] - b[1] || b[0] - a[0]); + let size = 0; + let smallest = -1; + let secondSmallest = -1; + + for (const [start, end] of intervals) { + const hasTwo = start <= smallest; + const hasOne = start <= secondSmallest; + + if (hasTwo) continue; + if (hasOne) { + smallest = secondSmallest; + secondSmallest = end; + size++; + } else { + smallest = end - 1; + secondSmallest = end; + size += 2; + } + } + + return size; +}; diff --git a/README.md b/README.md index 7a1a181d..2374fef9 100644 --- a/README.md +++ b/README.md @@ -574,6 +574,7 @@ 753|[Cracking the Safe](./0753-cracking-the-safe.js)|Hard| 754|[Reach a Number](./0754-reach-a-number.js)|Medium| 756|[Pyramid Transition Matrix](./0756-pyramid-transition-matrix.js)|Medium| +757|[Set Intersection Size At Least Two](./0757-set-intersection-size-at-least-two.js)|Hard| 762|[Prime Number of Set Bits in Binary Representation](./0762-prime-number-of-set-bits-in-binary-representation.js)|Easy| 763|[Partition Labels](./0763-partition-labels.js)|Medium| 783|[Minimum Distance Between BST Nodes](./0783-minimum-distance-between-bst-nodes.js)|Easy| From 8e37736e19557f8d12c832bd3011560e794afd7f Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 13 Mar 2025 01:30:35 -0500 Subject: [PATCH 910/919] Add solution #761 --- 0761-special-binary-string.js | 41 +++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 42 insertions(+) create mode 100644 0761-special-binary-string.js diff --git a/0761-special-binary-string.js b/0761-special-binary-string.js new file mode 100644 index 00000000..63fa5c32 --- /dev/null +++ b/0761-special-binary-string.js @@ -0,0 +1,41 @@ +/** + * 761. Special Binary String + * https://leetcode.com/problems/special-binary-string/ + * Difficulty: Hard + * + * Special binary strings are binary strings with the following two properties: + * - The number of 0's is equal to the number of 1's. + * - Every prefix of the binary string has at least as many 1's as 0's. + * + * You are given a special binary string s. + * + * A move consists of choosing two consecutive, non-empty, special substrings of s, + * and swapping them. Two strings are consecutive if the last character of the first + * string is exactly one index before the first character of the second string. + * + * Return the lexicographically largest resulting string possible after applying + * the mentioned operations on the string. + */ + +/** + * @param {string} s + * @return {string} + */ +function makeLargestSpecial(s) { + if (s.length <= 2) return s; + + let count = 0; + let start = 0; + const specials = []; + + for (let i = 0; i < s.length; i++) { + count += s[i] === '1' ? 1 : -1; + + if (count === 0) { + specials.push('1' + makeLargestSpecial(s.slice(start + 1, i)) + '0'); + start = i + 1; + } + } + + return specials.sort().reverse().join(''); +} diff --git a/README.md b/README.md index 2374fef9..2cfd8905 100644 --- a/README.md +++ b/README.md @@ -575,6 +575,7 @@ 754|[Reach a Number](./0754-reach-a-number.js)|Medium| 756|[Pyramid Transition Matrix](./0756-pyramid-transition-matrix.js)|Medium| 757|[Set Intersection Size At Least Two](./0757-set-intersection-size-at-least-two.js)|Hard| +761|[Special Binary String](./0761-special-binary-string.js)|Hard| 762|[Prime Number of Set Bits in Binary Representation](./0762-prime-number-of-set-bits-in-binary-representation.js)|Easy| 763|[Partition Labels](./0763-partition-labels.js)|Medium| 783|[Minimum Distance Between BST Nodes](./0783-minimum-distance-between-bst-nodes.js)|Easy| From 3bbbd505bd6a2a70d0c2deb1dfd17012d1ffce59 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 13 Mar 2025 01:32:54 -0500 Subject: [PATCH 911/919] Add solution #764 --- 0764-largest-plus-sign.js | 58 +++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 59 insertions(+) create mode 100644 0764-largest-plus-sign.js diff --git a/0764-largest-plus-sign.js b/0764-largest-plus-sign.js new file mode 100644 index 00000000..512bfddf --- /dev/null +++ b/0764-largest-plus-sign.js @@ -0,0 +1,58 @@ +/** + * 764. Largest Plus Sign + * https://leetcode.com/problems/largest-plus-sign/ + * Difficulty: Medium + * + * You are given an integer n. You have an n x n binary grid grid with all values initially + * 1's except for some indices given in the array mines. The ith element of the array mines + * is defined as mines[i] = [xi, yi] where grid[xi][yi] == 0. + * + * Return the order of the largest axis-aligned plus sign of 1's contained in grid. If + * there is none, return 0. + * + * An axis-aligned plus sign of 1's of order k has some center grid[r][c] == 1 along with four + * arms of length k - 1 going up, down, left, and right, and made of 1's. Note that there could + * be 0's or 1's beyond the arms of the plus sign, only the relevant area of the plus sign is + * checked for 1's. + */ + +/** + * @param {number} n + * @param {number[][]} mines + * @return {number} + */ +function orderOfLargestPlusSign(n, mines) { + const grid = Array(n).fill().map(() => Array(n).fill(1)); + mines.forEach(([x, y]) => grid[x][y] = 0); + + const left = Array(n).fill().map(() => Array(n).fill(0)); + const right = Array(n).fill().map(() => Array(n).fill(0)); + const up = Array(n).fill().map(() => Array(n).fill(0)); + const down = Array(n).fill().map(() => Array(n).fill(0)); + + for (let i = 0; i < n; i++) { + for (let j = 0; j < n; j++) { + left[i][j] = grid[i][j] ? (j > 0 ? left[i][j-1] + 1 : 1) : 0; + up[i][j] = grid[i][j] ? (i > 0 ? up[i-1][j] + 1 : 1) : 0; + } + } + + for (let i = n - 1; i >= 0; i--) { + for (let j = n - 1; j >= 0; j--) { + right[i][j] = grid[i][j] ? (j < n-1 ? right[i][j+1] + 1 : 1) : 0; + down[i][j] = grid[i][j] ? (i < n-1 ? down[i+1][j] + 1 : 1) : 0; + } + } + + let maxOrder = 0; + for (let i = 0; i < n; i++) { + for (let j = 0; j < n; j++) { + maxOrder = Math.max( + maxOrder, + Math.min(left[i][j], right[i][j], up[i][j], down[i][j]) + ); + } + } + + return maxOrder; +} diff --git a/README.md b/README.md index 2cfd8905..acfa73d8 100644 --- a/README.md +++ b/README.md @@ -578,6 +578,7 @@ 761|[Special Binary String](./0761-special-binary-string.js)|Hard| 762|[Prime Number of Set Bits in Binary Representation](./0762-prime-number-of-set-bits-in-binary-representation.js)|Easy| 763|[Partition Labels](./0763-partition-labels.js)|Medium| +764|[Largest Plus Sign](./0764-largest-plus-sign.js)|Medium| 783|[Minimum Distance Between BST Nodes](./0783-minimum-distance-between-bst-nodes.js)|Easy| 784|[Letter Case Permutation](./0784-letter-case-permutation.js)|Medium| 790|[Domino and Tromino Tiling](./0790-domino-and-tromino-tiling.js)|Medium| From 3f9e5b31aec25cafe4d1e0de9971bee505a4d233 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 13 Mar 2025 01:34:53 -0500 Subject: [PATCH 912/919] Add solution #765 --- 0765-couples-holding-hands.js | 46 +++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 47 insertions(+) create mode 100644 0765-couples-holding-hands.js diff --git a/0765-couples-holding-hands.js b/0765-couples-holding-hands.js new file mode 100644 index 00000000..e464cc7f --- /dev/null +++ b/0765-couples-holding-hands.js @@ -0,0 +1,46 @@ +/** + * 765. Couples Holding Hands + * https://leetcode.com/problems/couples-holding-hands/ + * Difficulty: Hard + * + * There are n couples sitting in 2n seats arranged in a row and want to hold hands. + * + * The people and seats are represented by an integer array row where row[i] is the ID of the + * person sitting in the ith seat. The couples are numbered in order, the first couple being + * (0, 1), the second couple being (2, 3), and so on with the last couple being (2n - 2, 2n - 1). + * + * Return the minimum number of swaps so that every couple is sitting side by side. A swap + * consists of choosing any two people, then they stand up and switch seats. + */ + +/** + * @param {number[]} row + * @return {number} + */ +function minSwapsCouples(row) { + const n = row.length / 2; + const partner = new Array(2 * n); + const position = new Array(2 * n); + + for (let i = 0; i < 2 * n; i++) { + partner[i] = i % 2 === 0 ? i + 1 : i - 1; + position[row[i]] = i; + } + + let swaps = 0; + for (let i = 0; i < 2 * n; i += 2) { + const current = row[i]; + const expected = partner[current]; + const nextPerson = row[i + 1]; + + if (nextPerson !== expected) { + row[i + 1] = expected; + row[position[expected]] = nextPerson; + position[nextPerson] = position[expected]; + position[expected] = i + 1; + swaps++; + } + } + + return swaps; +} diff --git a/README.md b/README.md index acfa73d8..2f47a0e1 100644 --- a/README.md +++ b/README.md @@ -579,6 +579,7 @@ 762|[Prime Number of Set Bits in Binary Representation](./0762-prime-number-of-set-bits-in-binary-representation.js)|Easy| 763|[Partition Labels](./0763-partition-labels.js)|Medium| 764|[Largest Plus Sign](./0764-largest-plus-sign.js)|Medium| +765|[Couples Holding Hands](./0765-couples-holding-hands.js)|Hard| 783|[Minimum Distance Between BST Nodes](./0783-minimum-distance-between-bst-nodes.js)|Easy| 784|[Letter Case Permutation](./0784-letter-case-permutation.js)|Medium| 790|[Domino and Tromino Tiling](./0790-domino-and-tromino-tiling.js)|Medium| From 109113e17304ee93984f384ff0eb4d050b98116a Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 13 Mar 2025 01:36:17 -0500 Subject: [PATCH 913/919] Add solution #766 --- 0766-toeplitz-matrix.js | 28 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 29 insertions(+) create mode 100644 0766-toeplitz-matrix.js diff --git a/0766-toeplitz-matrix.js b/0766-toeplitz-matrix.js new file mode 100644 index 00000000..3dabc686 --- /dev/null +++ b/0766-toeplitz-matrix.js @@ -0,0 +1,28 @@ +/** + * 766. Toeplitz Matrix + * https://leetcode.com/problems/toeplitz-matrix/ + * Difficulty: Easy + * + * Given an m x n matrix, return true if the matrix is Toeplitz. Otherwise, return false. + * + * A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements. + */ + +/** + * @param {number[][]} matrix + * @return {boolean} + */ +function isToeplitzMatrix(matrix) { + const rows = matrix.length; + const cols = matrix[0].length; + + for (let r = 0; r < rows - 1; r++) { + for (let c = 0; c < cols - 1; c++) { + if (matrix[r][c] !== matrix[r + 1][c + 1]) { + return false; + } + } + } + + return true; +} diff --git a/README.md b/README.md index 2f47a0e1..fe02e7d5 100644 --- a/README.md +++ b/README.md @@ -580,6 +580,7 @@ 763|[Partition Labels](./0763-partition-labels.js)|Medium| 764|[Largest Plus Sign](./0764-largest-plus-sign.js)|Medium| 765|[Couples Holding Hands](./0765-couples-holding-hands.js)|Hard| +766|[Toeplitz Matrix](./0766-toeplitz-matrix.js)|Easy| 783|[Minimum Distance Between BST Nodes](./0783-minimum-distance-between-bst-nodes.js)|Easy| 784|[Letter Case Permutation](./0784-letter-case-permutation.js)|Medium| 790|[Domino and Tromino Tiling](./0790-domino-and-tromino-tiling.js)|Medium| From 11cbc1d0e7ab9c0260ec65f7ac135464773371d9 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 13 Mar 2025 01:37:43 -0500 Subject: [PATCH 914/919] Add solution #767 --- 0767-reorganize-string.js | 42 +++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 43 insertions(+) create mode 100644 0767-reorganize-string.js diff --git a/0767-reorganize-string.js b/0767-reorganize-string.js new file mode 100644 index 00000000..b76729a6 --- /dev/null +++ b/0767-reorganize-string.js @@ -0,0 +1,42 @@ +/** + * 767. Reorganize String + * https://leetcode.com/problems/reorganize-string/ + * Difficulty: Medium + * + * Given a string s, rearrange the characters of s so that any two adjacent characters are + * not the same. + * + * Return any possible rearrangement of s or return "" if not possible. + */ + +/** + * @param {string} s + * @return {string} + */ +var reorganizeString = function(s) { + const charCount = new Map(); + for (const char of s) { + charCount.set(char, (charCount.get(char) || 0) + 1); + } + + const maxHeap = [...charCount.entries()] + .sort((a, b) => b[1] - a[1]); + + if (maxHeap[0][1] > Math.ceil(s.length / 2)) { + return ''; + } + + const result = []; + let index = 0; + + while (maxHeap.length) { + const [char, count] = maxHeap.shift(); + for (let i = 0; i < count; i++) { + result[index] = char; + index += 2; + if (index >= s.length) index = 1; + } + } + + return result.join(''); +}; diff --git a/README.md b/README.md index fe02e7d5..770993f6 100644 --- a/README.md +++ b/README.md @@ -581,6 +581,7 @@ 764|[Largest Plus Sign](./0764-largest-plus-sign.js)|Medium| 765|[Couples Holding Hands](./0765-couples-holding-hands.js)|Hard| 766|[Toeplitz Matrix](./0766-toeplitz-matrix.js)|Easy| +767|[Reorganize String](./0767-reorganize-string.js)|Medium| 783|[Minimum Distance Between BST Nodes](./0783-minimum-distance-between-bst-nodes.js)|Easy| 784|[Letter Case Permutation](./0784-letter-case-permutation.js)|Medium| 790|[Domino and Tromino Tiling](./0790-domino-and-tromino-tiling.js)|Medium| From d03e7fcd0209625ef7c020afefb984952f461b04 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 13 Mar 2025 20:16:49 -0500 Subject: [PATCH 915/919] Add solution #2226 --- ...maximum-candies-allocated-to-k-children.js | 40 +++++++++++++++++++ README.md | 1 + 2 files changed, 41 insertions(+) create mode 100644 2226-maximum-candies-allocated-to-k-children.js diff --git a/2226-maximum-candies-allocated-to-k-children.js b/2226-maximum-candies-allocated-to-k-children.js new file mode 100644 index 00000000..98f340a4 --- /dev/null +++ b/2226-maximum-candies-allocated-to-k-children.js @@ -0,0 +1,40 @@ +/** + * 2226. Maximum Candies Allocated to K Children + * https://leetcode.com/problems/maximum-candies-allocated-to-k-children/ + * Difficulty: Medium + * + * You are given a 0-indexed integer array candies. Each element in the array denotes a pile of + * candies of size candies[i]. You can divide each pile into any number of sub piles, but you + * cannot merge two piles together. + * + * You are also given an integer k. You should allocate piles of candies to k children such that + * each child gets the same number of candies. Each child can be allocated candies from only one + * pile of candies and some piles of candies may go unused. + * + * Return the maximum number of candies each child can get. + */ + +/** + * @param {number[]} candies + * @param {number} k + * @return {number} + */ +var maximumCandies = function(candies, k) { + let left = 0; + let right = 1e7 + 1; + + while (left + 1 !== right) { + const middle = Math.floor((left + right) / 2); + let piles = 0; + for (const candy of candies) { + piles += Math.floor(candy / middle); + } + if (piles >= k) { + left = middle; + } else { + right = middle; + } + } + + return left; +}; diff --git a/README.md b/README.md index 770993f6..b5481ddd 100644 --- a/README.md +++ b/README.md @@ -792,6 +792,7 @@ 2161|[Partition Array According to Given Pivot](./2161-partition-array-according-to-given-pivot.js)|Medium| 2185|[Counting Words With a Given Prefix](./2185-counting-words-with-a-given-prefix.js)|Easy| 2215|[Find the Difference of Two Arrays](./2215-find-the-difference-of-two-arrays.js)|Easy| +2226|[Maximum Candies Allocated to K Children](./2226-maximum-candies-allocated-to-k-children.js)|Medium| 2235|[Add Two Integers](./2235-add-two-integers.js)|Easy| 2244|[Minimum Rounds to Complete All Tasks](./2244-minimum-rounds-to-complete-all-tasks.js)|Medium| 2270|[Number of Ways to Split Array](./2270-number-of-ways-to-split-array.js)|Medium| From f85a0b1215761e2a0965b24e8f5a7e2c18e1f9af Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 13 Mar 2025 20:18:11 -0500 Subject: [PATCH 916/919] Add solution #768 --- 0768-max-chunks-to-make-sorted-ii.js | 34 ++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 0768-max-chunks-to-make-sorted-ii.js diff --git a/0768-max-chunks-to-make-sorted-ii.js b/0768-max-chunks-to-make-sorted-ii.js new file mode 100644 index 00000000..ec519b62 --- /dev/null +++ b/0768-max-chunks-to-make-sorted-ii.js @@ -0,0 +1,34 @@ +/** + * 768. Max Chunks To Make Sorted II + * https://leetcode.com/problems/max-chunks-to-make-sorted-ii/ + * Difficulty: Hard + * + * You are given an integer array arr. + * + * We split arr into some number of chunks (i.e., partitions), and individually sort each chunk. + * After concatenating them, the result should equal the sorted array. + * + * Return the largest number of chunks we can make to sort the array. + */ + +/** + * @param {number[]} arr + * @return {number} + */ +var maxChunksToSorted = function(arr) { + const stack = []; + + for (const num of arr) { + if (stack.length === 0 || stack[stack.length - 1] <= num) { + stack.push(num); + } else { + const max = stack.pop(); + while (stack.length && stack[stack.length - 1] > num) { + stack.pop(); + } + stack.push(max); + } + } + + return stack.length; +}; diff --git a/README.md b/README.md index b5481ddd..7db017cf 100644 --- a/README.md +++ b/README.md @@ -582,6 +582,7 @@ 765|[Couples Holding Hands](./0765-couples-holding-hands.js)|Hard| 766|[Toeplitz Matrix](./0766-toeplitz-matrix.js)|Easy| 767|[Reorganize String](./0767-reorganize-string.js)|Medium| +768|[Max Chunks To Make Sorted II](./0768-max-chunks-to-make-sorted-ii.js)|Hard| 783|[Minimum Distance Between BST Nodes](./0783-minimum-distance-between-bst-nodes.js)|Easy| 784|[Letter Case Permutation](./0784-letter-case-permutation.js)|Medium| 790|[Domino and Tromino Tiling](./0790-domino-and-tromino-tiling.js)|Medium| From 9e8115b19ecdbdde698db2a59da9f8ed7eef14ec Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 13 Mar 2025 20:19:52 -0500 Subject: [PATCH 917/919] Add solution #769 --- 0769-max-chunks-to-make-sorted.js | 30 ++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 0769-max-chunks-to-make-sorted.js diff --git a/0769-max-chunks-to-make-sorted.js b/0769-max-chunks-to-make-sorted.js new file mode 100644 index 00000000..e0869491 --- /dev/null +++ b/0769-max-chunks-to-make-sorted.js @@ -0,0 +1,30 @@ +/** + * 769. Max Chunks To Make Sorted + * https://leetcode.com/problems/max-chunks-to-make-sorted/ + * Difficulty: Medium + * + * You are given an integer array arr of length n that represents a permutation of the integers + * in the range [0, n - 1]. + * + * We split arr into some number of chunks (i.e., partitions), and individually sort each chunk. + * After concatenating them, the result should equal the sorted array. + * + * Return the largest number of chunks we can make to sort the array. + */ + +/** + * @param {number[]} arr + * @return {number} + */ +var maxChunksToSorted = function(arr) { + let result = 0; + + for (let i = 0, max = 0; i < arr.length; i++) { + max = Math.max(max, arr[i]); + if (max === i) { + result++; + } + } + + return result; +}; diff --git a/README.md b/README.md index 7db017cf..cd5540aa 100644 --- a/README.md +++ b/README.md @@ -583,6 +583,7 @@ 766|[Toeplitz Matrix](./0766-toeplitz-matrix.js)|Easy| 767|[Reorganize String](./0767-reorganize-string.js)|Medium| 768|[Max Chunks To Make Sorted II](./0768-max-chunks-to-make-sorted-ii.js)|Hard| +769|[Max Chunks To Make Sorted](./0769-max-chunks-to-make-sorted.js)|Medium| 783|[Minimum Distance Between BST Nodes](./0783-minimum-distance-between-bst-nodes.js)|Easy| 784|[Letter Case Permutation](./0784-letter-case-permutation.js)|Medium| 790|[Domino and Tromino Tiling](./0790-domino-and-tromino-tiling.js)|Medium| From f54e64297b0b0941aae09d2abf7976675a83c841 Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 13 Mar 2025 20:30:00 -0500 Subject: [PATCH 918/919] Add solution #770 --- 0770-basic-calculator-iv.js | 230 ++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 231 insertions(+) create mode 100644 0770-basic-calculator-iv.js diff --git a/0770-basic-calculator-iv.js b/0770-basic-calculator-iv.js new file mode 100644 index 00000000..4f588a25 --- /dev/null +++ b/0770-basic-calculator-iv.js @@ -0,0 +1,230 @@ +/** + * 770. Basic Calculator IV + * https://leetcode.com/problems/basic-calculator-iv/ + * Difficulty: Hard + * + * Given an expression such as expression = "e + 8 - a + 5" and an evaluation map such as {"e": 1} + * (given in terms of evalvars = ["e"] and evalints = [1]), return a list of tokens representing + * the simplified expression, such as ["-1*a","14"] + * - An expression alternates chunks and symbols, with a space separating each chunk and symbol. + * - A chunk is either an expression in parentheses, a variable, or a non-negative integer. + * - A variable is a string of lowercase letters (not including digits.) Note that variables can + * be multiple letters, and note that variables never have a leading coefficient or unary operator + * like "2x" or "-x". + * + * Expressions are evaluated in the usual order: brackets first, then multiplication, then addition + * and subtraction. + * + * - For example, expression = "1 + 2 * 3" has an answer of ["7"]. + * + * The format of the output is as follows: + * - For each term of free variables with a non-zero coefficient, we write the free variables within + * a term in sorted order lexicographically. + * - For example, we would never write a term like "b*a*c", only "a*b*c". + * - Terms have degrees equal to the number of free variables being multiplied, counting + * multiplicity. We write the largest degree terms of our answer first, breaking ties by + * lexicographic order ignoring the leading coefficient of the term. + * - For example, "a*a*b*c" has degree 4. + * - The leading coefficient of the term is placed directly to the left with an asterisk separating + * it from the variables (if they exist.) A leading coefficient of 1 is still printed. + * - An example of a well-formatted answer is ["-2*a*a*a", "3*a*a*b", "3*b*b", "4*a", "5*c", "-6"]. + * - Terms (including constant terms) with coefficient 0 are not included. + * - For example, an expression of "0" has an output of []. + * + * Note: You may assume that the given expression is always valid. All intermediate results will be + * in the range of [-231, 231 - 1]. + */ + +/** + * @param {string} expression + * @param {string[]} evalvars + * @param {number[]} evalints + * @return {string[]} + */ +var basicCalculatorIV = function(expression, evalvars, evalints) { + const map = new Map(); + for (let i = 0; i < evalvars.length; i++) { + map.set(evalvars[i], evalints[i]); + } + + const result = parse(expression, map); + return result.toStringArray(); + + function parse(expr, map) { + const tokens = tokenize(expr); + return parseExpr(tokens, 0, map)[0]; + } + + function tokenize(expr) { + const tokens = []; + let i = 0; + + while (i < expr.length) { + if (expr[i] === ' ') { + i++; continue; + } + + if ('+-*()'.includes(expr[i])) { + tokens.push(expr[i++]); + continue; + } + + if (/[a-z]/.test(expr[i])) { + let variable = ''; + while (i < expr.length && /[a-z]/.test(expr[i])) { + variable += expr[i++]; + } + tokens.push(variable); + continue; + } + + if (/\d/.test(expr[i])) { + let num = ''; + while (i < expr.length && /\d/.test(expr[i])) { + num += expr[i++]; + } + tokens.push(parseInt(num)); + continue; + } + + i++; + } + + return tokens; + } + + function parseExpr(tokens, start, map) { + let [left, pos] = parseTerm(tokens, start, map); + + while (pos < tokens.length && (tokens[pos] === '+' || tokens[pos] === '-')) { + const op = tokens[pos]; + const [right, nextPos] = parseTerm(tokens, pos + 1, map); + + left = op === '+' ? left.add(right) : left.subtract(right); + pos = nextPos; + } + + return [left, pos]; + } + + function parseTerm(tokens, start, map) { + let [left, pos] = parseFactor(tokens, start, map); + + while (pos < tokens.length && tokens[pos] === '*') { + const [right, nextPos] = parseFactor(tokens, pos + 1, map); + left = left.multiply(right); + pos = nextPos; + } + + return [left, pos]; + } + + function parseFactor(tokens, start, map) { + const token = tokens[start]; + + if (token === '(') { + const [expr, pos] = parseExpr(tokens, start + 1, map); + return [expr, pos + 1]; + } + + if (typeof token === 'string' && /[a-z]/.test(token)) { + return map.has(token) + ? [new Expression([new Term(map.get(token))]), start + 1] + : [new Expression([new Term(1, [token])]), start + 1]; + } + + if (typeof token === 'number') { + return [new Expression([new Term(token)]), start + 1]; + } + + throw new Error(`Unexpected token: ${token}`); + } +}; + +class Term { + constructor(coefficient = 0, variables = []) { + this.coefficient = coefficient; + this.variables = [...variables].sort(); + } + + multiply(other) { + return new Term( + this.coefficient * other.coefficient, + [...this.variables, ...other.variables].sort() + ); + } + + toString() { + if (this.coefficient === 0) return ''; + if (this.variables.length === 0) return `${this.coefficient}`; + return `${this.coefficient}*${this.variables.join('*')}`; + } + + get degree() { + return this.variables.length; + } + + compare(other) { + if (this.degree !== other.degree) return other.degree - this.degree; + + for (let i = 0; i < this.degree; i++) { + if (this.variables[i] !== other.variables[i]) { + return this.variables[i].localeCompare(other.variables[i]); + } + } + return 0; + } +} + +class Expression { + constructor(terms = []) { + this.terms = terms; + } + + add(other, multiplier = 1) { + const termMap = new Map(); + + for (const term of this.terms) { + const key = term.variables.join('*'); + termMap.set(key, term); + } + + for (const term of other.terms) { + const key = term.variables.join('*'); + if (termMap.has(key)) { + termMap.get(key).coefficient += term.coefficient * multiplier; + } else { + const newTerm = new Term(term.coefficient * multiplier, term.variables); + this.terms.push(newTerm); + termMap.set(key, newTerm); + } + } + + this.terms = this.terms.filter(term => term.coefficient !== 0); + return this; + } + + subtract(other) { + return this.add(other, -1); + } + + multiply(other) { + const result = new Expression(); + + for (const term1 of this.terms) { + for (const term2 of other.terms) { + const product = term1.multiply(term2); + if (product.coefficient !== 0) { + result.add(new Expression([product])); + } + } + } + + return result; + } + + toStringArray() { + this.terms.sort((a, b) => a.compare(b)); + return this.terms.map(term => term.toString()).filter(Boolean); + } +} diff --git a/README.md b/README.md index cd5540aa..2bfd1e5f 100644 --- a/README.md +++ b/README.md @@ -584,6 +584,7 @@ 767|[Reorganize String](./0767-reorganize-string.js)|Medium| 768|[Max Chunks To Make Sorted II](./0768-max-chunks-to-make-sorted-ii.js)|Hard| 769|[Max Chunks To Make Sorted](./0769-max-chunks-to-make-sorted.js)|Medium| +770|[Basic Calculator IV](./0770-basic-calculator-iv.js)|Hard| 783|[Minimum Distance Between BST Nodes](./0783-minimum-distance-between-bst-nodes.js)|Easy| 784|[Letter Case Permutation](./0784-letter-case-permutation.js)|Medium| 790|[Domino and Tromino Tiling](./0790-domino-and-tromino-tiling.js)|Medium| From 3e06a6542fbfcdf71d331bbfb48d07bfbcadef7b Mon Sep 17 00:00:00 2001 From: Josh Crozier Date: Thu, 13 Mar 2025 20:34:10 -0500 Subject: [PATCH 919/919] Add solution #773 --- 0773-sliding-puzzle.js | 51 ++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 52 insertions(+) create mode 100644 0773-sliding-puzzle.js diff --git a/0773-sliding-puzzle.js b/0773-sliding-puzzle.js new file mode 100644 index 00000000..c8345ead --- /dev/null +++ b/0773-sliding-puzzle.js @@ -0,0 +1,51 @@ +/** + * 773. Sliding Puzzle + * https://leetcode.com/problems/sliding-puzzle/ + * Difficulty: Hard + * + * On an 2 x 3 board, there are five tiles labeled from 1 to 5, and an empty square represented by + * 0. A move consists of choosing 0 and a 4-directionally adjacent number and swapping it. + * + * The state of the board is solved if and only if the board is [[1,2,3],[4,5,0]]. + * + * Given the puzzle board board, return the least number of moves required so that the state of the + * board is solved. If it is impossible for the state of the board to be solved, return -1. + */ + +/** + * @param {number[][]} board + * @return {number} + */ +var slidingPuzzle = function(board) { + const target = '123450'; + const moves = [ + [1, 3], [0, 2, 4], [1, 5], + [0, 4], [1, 3, 5], [2, 4] + ]; + + const start = board.flat().join(''); + if (start === target) return 0; + + const queue = [[start, 0]]; + const seen = new Set([start]); + + while (queue.length) { + const [state, steps] = queue.shift(); + const index = state.indexOf('0'); + + for (const next of moves[index]) { + const chars = state.split(''); + [chars[index], chars[next]] = [chars[next], chars[index]]; + const nextState = chars.join(''); + + if (nextState === target) return steps + 1; + + if (!seen.has(nextState)) { + seen.add(nextState); + queue.push([nextState, steps + 1]); + } + } + } + + return -1; +}; diff --git a/README.md b/README.md index 2bfd1e5f..f4d2a1f6 100644 --- a/README.md +++ b/README.md @@ -585,6 +585,7 @@ 768|[Max Chunks To Make Sorted II](./0768-max-chunks-to-make-sorted-ii.js)|Hard| 769|[Max Chunks To Make Sorted](./0769-max-chunks-to-make-sorted.js)|Medium| 770|[Basic Calculator IV](./0770-basic-calculator-iv.js)|Hard| +773|[Sliding Puzzle](./0773-sliding-puzzle.js)|Hard| 783|[Minimum Distance Between BST Nodes](./0783-minimum-distance-between-bst-nodes.js)|Easy| 784|[Letter Case Permutation](./0784-letter-case-permutation.js)|Medium| 790|[Domino and Tromino Tiling](./0790-domino-and-tromino-tiling.js)|Medium|